blob: c8d6e44c2f54d53af48441dc6262d4e24a025155 [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:
Rex Xu5e317ff2017-03-16 23:02:39 +0800456 if (!memberDeclaration) {
457 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800458#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800459 if (glslangIntermediate->getStage() == EShLangVertex ||
460 glslangIntermediate->getStage() == EShLangTessControl ||
461 glslangIntermediate->getStage() == EShLangTessEvaluation) {
462
463 builder.addExtension(spv::E_SPV_NV_viewport_array2);
464 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
465 }
chaoc771d89f2017-01-13 01:10:53 -0800466#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800467 }
John Kessenich92187592016-02-01 13:45:25 -0700468 return spv::BuiltInViewportIndex;
469
John Kessenich5e801132016-02-15 11:09:46 -0700470 case glslang::EbvSampleId:
471 builder.addCapability(spv::CapabilitySampleRateShading);
472 return spv::BuiltInSampleId;
473
474 case glslang::EbvSamplePosition:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSamplePosition;
477
478 case glslang::EbvSampleMask:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSampleMask;
481
John Kessenich78a45572016-07-08 14:05:15 -0600482 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800483 if (!memberDeclaration) {
484 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
489
chaoc771d89f2017-01-13 01:10:53 -0800490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
chaoc771d89f2017-01-13 01:10:53 -0800493#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800494 }
495
John Kessenich78a45572016-07-08 14:05:15 -0600496 return spv::BuiltInLayer;
497
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvVertexId: return spv::BuiltInVertexId;
500 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700501 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
502 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800503
John Kessenichda581a22015-10-14 14:10:30 -0600504 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800505 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
506 builder.addCapability(spv::CapabilityDrawParameters);
507 return spv::BuiltInBaseVertex;
508
John Kessenichda581a22015-10-14 14:10:30 -0600509 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800510 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
511 builder.addCapability(spv::CapabilityDrawParameters);
512 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200513
John Kessenichda581a22015-10-14 14:10:30 -0600514 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800515 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
516 builder.addCapability(spv::CapabilityDrawParameters);
517 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200518
519 case glslang::EbvPrimitiveId:
520 if (glslangIntermediate->getStage() == EShLangFragment)
521 builder.addCapability(spv::CapabilityGeometry);
522 return spv::BuiltInPrimitiveId;
523
Rex Xu37cdcee2017-06-29 17:46:34 +0800524 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800525 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
526 builder.addCapability(spv::CapabilityStencilExportEXT);
527 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800528
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
531 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
532 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
533 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
534 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
535 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
536 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600537 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
538 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
539 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
540 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
541 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
542 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
543 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
544 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800545
Rex Xu574ab042016-04-14 16:53:07 +0800546 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800547 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800548 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
549 return spv::BuiltInSubgroupSize;
550
Rex Xu574ab042016-04-14 16:53:07 +0800551 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800552 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800553 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
554 return spv::BuiltInSubgroupLocalInvocationId;
555
Rex Xu574ab042016-04-14 16:53:07 +0800556 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800557 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
558 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
559 return spv::BuiltInSubgroupEqMaskKHR;
560
Rex Xu574ab042016-04-14 16:53:07 +0800561 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800562 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
563 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
564 return spv::BuiltInSubgroupGeMaskKHR;
565
Rex Xu574ab042016-04-14 16:53:07 +0800566 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800567 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
568 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
569 return spv::BuiltInSubgroupGtMaskKHR;
570
Rex Xu574ab042016-04-14 16:53:07 +0800571 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800572 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
573 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
574 return spv::BuiltInSubgroupLeMaskKHR;
575
Rex Xu574ab042016-04-14 16:53:07 +0800576 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
578 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
579 return spv::BuiltInSubgroupLtMaskKHR;
580
Rex Xu9d93a232016-05-05 12:30:44 +0800581#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800582 case glslang::EbvBaryCoordNoPersp:
583 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
584 return spv::BuiltInBaryCoordNoPerspAMD;
585
586 case glslang::EbvBaryCoordNoPerspCentroid:
587 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
588 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
589
590 case glslang::EbvBaryCoordNoPerspSample:
591 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
592 return spv::BuiltInBaryCoordNoPerspSampleAMD;
593
594 case glslang::EbvBaryCoordSmooth:
595 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
596 return spv::BuiltInBaryCoordSmoothAMD;
597
598 case glslang::EbvBaryCoordSmoothCentroid:
599 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
600 return spv::BuiltInBaryCoordSmoothCentroidAMD;
601
602 case glslang::EbvBaryCoordSmoothSample:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordSmoothSampleAMD;
605
606 case glslang::EbvBaryCoordPullModel:
607 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
608 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800609#endif
chaoc771d89f2017-01-13 01:10:53 -0800610
John Kessenich6c8aaac2017-02-27 01:20:51 -0700611 case glslang::EbvDeviceIndex:
612 builder.addExtension(spv::E_SPV_KHR_device_group);
613 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700614 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700615
616 case glslang::EbvViewIndex:
617 builder.addExtension(spv::E_SPV_KHR_multiview);
618 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700619 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700620
chaoc771d89f2017-01-13 01:10:53 -0800621#ifdef NV_EXTENSIONS
622 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800623 if (!memberDeclaration) {
624 builder.addExtension(spv::E_SPV_NV_viewport_array2);
625 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
626 }
chaoc771d89f2017-01-13 01:10:53 -0800627 return spv::BuiltInViewportMaskNV;
628 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800629 if (!memberDeclaration) {
630 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
631 builder.addCapability(spv::CapabilityShaderStereoViewNV);
632 }
chaoc771d89f2017-01-13 01:10:53 -0800633 return spv::BuiltInSecondaryPositionNV;
634 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800635 if (!memberDeclaration) {
636 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
637 builder.addCapability(spv::CapabilityShaderStereoViewNV);
638 }
chaoc771d89f2017-01-13 01:10:53 -0800639 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800640 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800641 if (!memberDeclaration) {
642 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
643 builder.addCapability(spv::CapabilityPerViewAttributesNV);
644 }
chaocdf3956c2017-02-14 14:52:34 -0800645 return spv::BuiltInPositionPerViewNV;
646 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800647 if (!memberDeclaration) {
648 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
649 builder.addCapability(spv::CapabilityPerViewAttributesNV);
650 }
chaocdf3956c2017-02-14 14:52:34 -0800651 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800652#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800653 default:
654 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600655 }
656}
657
Rex Xufc618912015-09-09 16:42:49 +0800658// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700659spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800660{
661 assert(type.getBasicType() == glslang::EbtSampler);
662
John Kessenich5d0fa972016-02-15 11:57:00 -0700663 // Check for capabilities
664 switch (type.getQualifier().layoutFormat) {
665 case glslang::ElfRg32f:
666 case glslang::ElfRg16f:
667 case glslang::ElfR11fG11fB10f:
668 case glslang::ElfR16f:
669 case glslang::ElfRgba16:
670 case glslang::ElfRgb10A2:
671 case glslang::ElfRg16:
672 case glslang::ElfRg8:
673 case glslang::ElfR16:
674 case glslang::ElfR8:
675 case glslang::ElfRgba16Snorm:
676 case glslang::ElfRg16Snorm:
677 case glslang::ElfRg8Snorm:
678 case glslang::ElfR16Snorm:
679 case glslang::ElfR8Snorm:
680
681 case glslang::ElfRg32i:
682 case glslang::ElfRg16i:
683 case glslang::ElfRg8i:
684 case glslang::ElfR16i:
685 case glslang::ElfR8i:
686
687 case glslang::ElfRgb10a2ui:
688 case glslang::ElfRg32ui:
689 case glslang::ElfRg16ui:
690 case glslang::ElfRg8ui:
691 case glslang::ElfR16ui:
692 case glslang::ElfR8ui:
693 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
694 break;
695
696 default:
697 break;
698 }
699
700 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800701 switch (type.getQualifier().layoutFormat) {
702 case glslang::ElfNone: return spv::ImageFormatUnknown;
703 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
704 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
705 case glslang::ElfR32f: return spv::ImageFormatR32f;
706 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
707 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
708 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
709 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
710 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
711 case glslang::ElfR16f: return spv::ImageFormatR16f;
712 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
713 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
714 case glslang::ElfRg16: return spv::ImageFormatRg16;
715 case glslang::ElfRg8: return spv::ImageFormatRg8;
716 case glslang::ElfR16: return spv::ImageFormatR16;
717 case glslang::ElfR8: return spv::ImageFormatR8;
718 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
719 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
720 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
721 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
722 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
723 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
724 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
725 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
726 case glslang::ElfR32i: return spv::ImageFormatR32i;
727 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
728 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
729 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
730 case glslang::ElfR16i: return spv::ImageFormatR16i;
731 case glslang::ElfR8i: return spv::ImageFormatR8i;
732 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
733 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
734 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
735 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
736 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
737 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
738 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
739 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
740 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
741 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600742 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800743 }
744}
745
Rex Xu57e65922017-07-04 23:23:40 +0800746spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
747{
748 switch (selectionControl) {
749 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
750 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
751 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
752 default: return spv::SelectionControlMaskNone;
753 }
754}
755
steve-lunargf1709e72017-05-02 20:14:50 -0600756spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
757{
758 switch (loopControl) {
759 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
760 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
761 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
762 // TODO: DependencyInfinite
763 // TODO: DependencyLength
764 default: return spv::LoopControlMaskNone;
765 }
766}
767
John Kessenicha5c5fb62017-05-05 05:09:58 -0600768// Translate glslang type to SPIR-V storage class.
769spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
770{
771 if (type.getQualifier().isPipeInput())
772 return spv::StorageClassInput;
773 else if (type.getQualifier().isPipeOutput())
774 return spv::StorageClassOutput;
775 else if (type.getBasicType() == glslang::EbtAtomicUint)
776 return spv::StorageClassAtomicCounter;
777 else if (type.containsOpaque())
778 return spv::StorageClassUniformConstant;
779 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
780 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
781 return spv::StorageClassStorageBuffer;
782 } else if (type.getQualifier().isUniformOrBuffer()) {
783 if (type.getQualifier().layoutPushConstant)
784 return spv::StorageClassPushConstant;
785 if (type.getBasicType() == glslang::EbtBlock)
786 return spv::StorageClassUniform;
787 else
788 return spv::StorageClassUniformConstant;
789 } else {
790 switch (type.getQualifier().storage) {
791 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
792 case glslang::EvqGlobal: return spv::StorageClassPrivate;
793 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
794 case glslang::EvqTemporary: return spv::StorageClassFunction;
795 default:
796 assert(0);
797 return spv::StorageClassFunction;
798 }
799 }
800}
801
qining25262b32016-05-06 17:25:16 -0400802// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700803// descriptor set.
804bool IsDescriptorResource(const glslang::TType& type)
805{
John Kessenichf7497e22016-03-08 21:36:22 -0700806 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700807 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700808 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700809
810 // non block...
811 // basically samplerXXX/subpass/sampler/texture are all included
812 // if they are the global-scope-class, not the function parameter
813 // (or local, if they ever exist) class.
814 if (type.getBasicType() == glslang::EbtSampler)
815 return type.getQualifier().isUniformOrBuffer();
816
817 // None of the above.
818 return false;
819}
820
John Kesseniche0b6cad2015-12-24 10:30:13 -0700821void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
822{
823 if (child.layoutMatrix == glslang::ElmNone)
824 child.layoutMatrix = parent.layoutMatrix;
825
826 if (parent.invariant)
827 child.invariant = true;
828 if (parent.nopersp)
829 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800830#ifdef AMD_EXTENSIONS
831 if (parent.explicitInterp)
832 child.explicitInterp = true;
833#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700834 if (parent.flat)
835 child.flat = true;
836 if (parent.centroid)
837 child.centroid = true;
838 if (parent.patch)
839 child.patch = true;
840 if (parent.sample)
841 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800842 if (parent.coherent)
843 child.coherent = true;
844 if (parent.volatil)
845 child.volatil = true;
846 if (parent.restrict)
847 child.restrict = true;
848 if (parent.readonly)
849 child.readonly = true;
850 if (parent.writeonly)
851 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700852}
853
John Kessenichf2b7f332016-09-01 17:05:23 -0600854bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700855{
John Kessenich7b9fa252016-01-21 18:56:57 -0700856 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600857 // - struct members might inherit from a struct declaration
858 // (note that non-block structs don't explicitly inherit,
859 // only implicitly, meaning no decoration involved)
860 // - affect decorations on the struct members
861 // (note smooth does not, and expecting something like volatile
862 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700863 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600864 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700865}
866
John Kessenich140f3df2015-06-26 16:58:36 -0600867//
868// Implement the TGlslangToSpvTraverser class.
869//
870
John Kessenich121853f2017-05-31 17:11:16 -0600871TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
872 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
873 : TIntermTraverser(true, false, true),
874 options(options),
875 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600876 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400877 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700878 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600879 glslangIntermediate(glslangIntermediate)
880{
881 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
882
883 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700884 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich121853f2017-05-31 17:11:16 -0600885 if (options.generateDebugInfo) {
886 builder.setSourceFile(glslangIntermediate->getSourceFile());
887 builder.setSourceText(glslangIntermediate->getSourceText());
John Kesseniche485c7a2017-05-31 18:50:53 -0600888 builder.setEmitOpLines();
John Kessenich121853f2017-05-31 17:11:16 -0600889 }
John Kessenich140f3df2015-06-26 16:58:36 -0600890 stdBuiltins = builder.import("GLSL.std.450");
891 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600892 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
893 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600894
895 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600896 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
897 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600898 builder.addSourceExtension(it->c_str());
899
900 // Add the top-level modes for this shader.
901
John Kessenich92187592016-02-01 13:45:25 -0700902 if (glslangIntermediate->getXfbMode()) {
903 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600904 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700905 }
John Kessenich140f3df2015-06-26 16:58:36 -0600906
907 unsigned int mode;
908 switch (glslangIntermediate->getStage()) {
909 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600910 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600911 break;
912
steve-lunarge7412492017-03-23 11:56:07 -0600913 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600914 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600915 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600916
steve-lunarge7412492017-03-23 11:56:07 -0600917 glslang::TLayoutGeometry primitive;
918
919 if (glslangIntermediate->getStage() == EShLangTessControl) {
920 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
921 primitive = glslangIntermediate->getOutputPrimitive();
922 } else {
923 primitive = glslangIntermediate->getInputPrimitive();
924 }
925
926 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700927 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
928 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
929 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600930 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600931 }
John Kessenich4016e382016-07-15 11:53:56 -0600932 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600933 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
934
John Kesseniche6903322015-10-13 16:29:02 -0600935 switch (glslangIntermediate->getVertexSpacing()) {
936 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
937 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
938 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600939 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600940 }
John Kessenich4016e382016-07-15 11:53:56 -0600941 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600942 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
943
944 switch (glslangIntermediate->getVertexOrder()) {
945 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
946 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600947 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600948 }
John Kessenich4016e382016-07-15 11:53:56 -0600949 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600950 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
951
952 if (glslangIntermediate->getPointMode())
953 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600954 break;
955
956 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600957 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600958 switch (glslangIntermediate->getInputPrimitive()) {
959 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
960 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
961 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700962 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600963 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600964 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600965 }
John Kessenich4016e382016-07-15 11:53:56 -0600966 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600967 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600968
John Kessenich140f3df2015-06-26 16:58:36 -0600969 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
970
971 switch (glslangIntermediate->getOutputPrimitive()) {
972 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
973 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
974 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600975 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600976 }
John Kessenich4016e382016-07-15 11:53:56 -0600977 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600978 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
979 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
980 break;
981
982 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600983 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600984 if (glslangIntermediate->getPixelCenterInteger())
985 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600986
John Kessenich140f3df2015-06-26 16:58:36 -0600987 if (glslangIntermediate->getOriginUpperLeft())
988 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600989 else
990 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600991
992 if (glslangIntermediate->getEarlyFragmentTests())
993 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
994
chaocc1204522017-06-30 17:14:30 -0700995 if (glslangIntermediate->getPostDepthCoverage()) {
996 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
997 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
998 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
999 }
1000
John Kesseniche6903322015-10-13 16:29:02 -06001001 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001002 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1003 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001004 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001005 }
John Kessenich4016e382016-07-15 11:53:56 -06001006 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001007 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1008
1009 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1010 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001011 break;
1012
1013 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001014 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001015 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1016 glslangIntermediate->getLocalSize(1),
1017 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001018 break;
1019
1020 default:
1021 break;
1022 }
John Kessenich140f3df2015-06-26 16:58:36 -06001023}
1024
John Kessenichfca82622016-11-26 13:23:20 -07001025// Finish creating SPV, after the traversal is complete.
1026void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001027{
John Kessenich517fe7a2016-11-26 13:31:47 -07001028 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001029 builder.setBuildPoint(shaderEntry->getLastBlock());
1030 builder.leaveFunction();
1031 }
1032
John Kessenich7ba63412015-12-20 17:37:07 -07001033 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001034 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1035 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001036
qiningda397332016-03-09 19:54:03 -05001037 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001038}
1039
John Kessenichfca82622016-11-26 13:23:20 -07001040// Write the SPV into 'out'.
1041void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001042{
John Kessenichfca82622016-11-26 13:23:20 -07001043 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001044}
1045
1046//
1047// Implement the traversal functions.
1048//
1049// Return true from interior nodes to have the external traversal
1050// continue on to children. Return false if children were
1051// already processed.
1052//
1053
1054//
qining25262b32016-05-06 17:25:16 -04001055// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001056// - uniform/input reads
1057// - output writes
1058// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1059// - something simple that degenerates into the last bullet
1060//
1061void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1062{
qining75d1d802016-04-06 14:42:01 -04001063 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1064 if (symbol->getType().getQualifier().isSpecConstant())
1065 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1066
John Kessenich140f3df2015-06-26 16:58:36 -06001067 // getSymbolId() will set up all the IO decorations on the first call.
1068 // Formal function parameters were mapped during makeFunctions().
1069 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001070
1071 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1072 if (builder.isPointer(id)) {
1073 spv::StorageClass sc = builder.getStorageClass(id);
1074 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1075 iOSet.insert(id);
1076 }
1077
1078 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001079 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001080 // Prepare to generate code for the access
1081
1082 // L-value chains will be computed left to right. We're on the symbol now,
1083 // which is the left-most part of the access chain, so now is "clear" time,
1084 // followed by setting the base.
1085 builder.clearAccessChain();
1086
1087 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001088 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001089 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001090 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001091 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001092 // These are also pure R-values.
1093 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001094 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001095 builder.setAccessChainRValue(id);
1096 else
1097 builder.setAccessChainLValue(id);
1098 }
1099}
1100
1101bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1102{
John Kesseniche485c7a2017-05-31 18:50:53 -06001103 builder.setLine(node->getLoc().line);
1104
qining40887662016-04-03 22:20:42 -04001105 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1106 if (node->getType().getQualifier().isSpecConstant())
1107 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1108
John Kessenich140f3df2015-06-26 16:58:36 -06001109 // First, handle special cases
1110 switch (node->getOp()) {
1111 case glslang::EOpAssign:
1112 case glslang::EOpAddAssign:
1113 case glslang::EOpSubAssign:
1114 case glslang::EOpMulAssign:
1115 case glslang::EOpVectorTimesMatrixAssign:
1116 case glslang::EOpVectorTimesScalarAssign:
1117 case glslang::EOpMatrixTimesScalarAssign:
1118 case glslang::EOpMatrixTimesMatrixAssign:
1119 case glslang::EOpDivAssign:
1120 case glslang::EOpModAssign:
1121 case glslang::EOpAndAssign:
1122 case glslang::EOpInclusiveOrAssign:
1123 case glslang::EOpExclusiveOrAssign:
1124 case glslang::EOpLeftShiftAssign:
1125 case glslang::EOpRightShiftAssign:
1126 // A bin-op assign "a += b" means the same thing as "a = a + b"
1127 // where a is evaluated before b. For a simple assignment, GLSL
1128 // says to evaluate the left before the right. So, always, left
1129 // node then right node.
1130 {
1131 // get the left l-value, save it away
1132 builder.clearAccessChain();
1133 node->getLeft()->traverse(this);
1134 spv::Builder::AccessChain lValue = builder.getAccessChain();
1135
1136 // evaluate the right
1137 builder.clearAccessChain();
1138 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001139 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001140
1141 if (node->getOp() != glslang::EOpAssign) {
1142 // the left is also an r-value
1143 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001144 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001145
1146 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001147 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001148 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001149 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1150 node->getType().getBasicType());
1151
1152 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001153 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001154 }
1155
1156 // store the result
1157 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001158 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001159
1160 // assignments are expressions having an rValue after they are evaluated...
1161 builder.clearAccessChain();
1162 builder.setAccessChainRValue(rValue);
1163 }
1164 return false;
1165 case glslang::EOpIndexDirect:
1166 case glslang::EOpIndexDirectStruct:
1167 {
1168 // Get the left part of the access chain.
1169 node->getLeft()->traverse(this);
1170
1171 // Add the next element in the chain
1172
David Netoa901ffe2016-06-08 14:11:40 +01001173 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001174 if (! node->getLeft()->getType().isArray() &&
1175 node->getLeft()->getType().isVector() &&
1176 node->getOp() == glslang::EOpIndexDirect) {
1177 // This is essentially a hard-coded vector swizzle of size 1,
1178 // so short circuit the access-chain stuff with a swizzle.
1179 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001180 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001181 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001182 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001183 int spvIndex = glslangIndex;
1184 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1185 node->getOp() == glslang::EOpIndexDirectStruct)
1186 {
1187 // This may be, e.g., an anonymous block-member selection, which generally need
1188 // index remapping due to hidden members in anonymous blocks.
1189 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1190 assert(remapper.size() > 0);
1191 spvIndex = remapper[glslangIndex];
1192 }
John Kessenichebb50532016-05-16 19:22:05 -06001193
David Netoa901ffe2016-06-08 14:11:40 +01001194 // normal case for indexing array or structure or block
1195 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1196
1197 // Add capabilities here for accessing PointSize and clip/cull distance.
1198 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001199 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001200 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001201 }
1202 }
1203 return false;
1204 case glslang::EOpIndexIndirect:
1205 {
1206 // Structure or array or vector indirection.
1207 // Will use native SPIR-V access-chain for struct and array indirection;
1208 // matrices are arrays of vectors, so will also work for a matrix.
1209 // Will use the access chain's 'component' for variable index into a vector.
1210
1211 // This adapter is building access chains left to right.
1212 // Set up the access chain to the left.
1213 node->getLeft()->traverse(this);
1214
1215 // save it so that computing the right side doesn't trash it
1216 spv::Builder::AccessChain partial = builder.getAccessChain();
1217
1218 // compute the next index in the chain
1219 builder.clearAccessChain();
1220 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001221 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001222
1223 // restore the saved access chain
1224 builder.setAccessChain(partial);
1225
1226 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001227 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001228 else
John Kessenichfa668da2015-09-13 14:46:30 -06001229 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001230 }
1231 return false;
1232 case glslang::EOpVectorSwizzle:
1233 {
1234 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001235 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001236 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001237 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001238 }
1239 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001240 case glslang::EOpMatrixSwizzle:
1241 logger->missingFunctionality("matrix swizzle");
1242 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001243 case glslang::EOpLogicalOr:
1244 case glslang::EOpLogicalAnd:
1245 {
1246
1247 // These may require short circuiting, but can sometimes be done as straight
1248 // binary operations. The right operand must be short circuited if it has
1249 // side effects, and should probably be if it is complex.
1250 if (isTrivial(node->getRight()->getAsTyped()))
1251 break; // handle below as a normal binary operation
1252 // otherwise, we need to do dynamic short circuiting on the right operand
1253 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1254 builder.clearAccessChain();
1255 builder.setAccessChainRValue(result);
1256 }
1257 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001258 default:
1259 break;
1260 }
1261
1262 // Assume generic binary op...
1263
John Kessenich32cfd492016-02-02 12:37:46 -07001264 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001265 builder.clearAccessChain();
1266 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001267 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001268
John Kessenich32cfd492016-02-02 12:37:46 -07001269 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001270 builder.clearAccessChain();
1271 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001272 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001273
John Kessenich32cfd492016-02-02 12:37:46 -07001274 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001275 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001276 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001277 convertGlslangToSpvType(node->getType()), left, right,
1278 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001279
John Kessenich50e57562015-12-21 21:21:11 -07001280 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001281 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001282 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001283 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001284 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001285 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001286 return false;
1287 }
John Kessenich140f3df2015-06-26 16:58:36 -06001288}
1289
1290bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1291{
John Kesseniche485c7a2017-05-31 18:50:53 -06001292 builder.setLine(node->getLoc().line);
1293
qining40887662016-04-03 22:20:42 -04001294 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1295 if (node->getType().getQualifier().isSpecConstant())
1296 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1297
John Kessenichfc51d282015-08-19 13:34:18 -06001298 spv::Id result = spv::NoResult;
1299
1300 // try texturing first
1301 result = createImageTextureFunctionCall(node);
1302 if (result != spv::NoResult) {
1303 builder.clearAccessChain();
1304 builder.setAccessChainRValue(result);
1305
1306 return false; // done with this node
1307 }
1308
1309 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001310
1311 if (node->getOp() == glslang::EOpArrayLength) {
1312 // Quite special; won't want to evaluate the operand.
1313
1314 // Normal .length() would have been constant folded by the front-end.
1315 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001316 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001317 assert(node->getOperand()->getType().isRuntimeSizedArray());
1318 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1319 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001320 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1321 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001322
1323 builder.clearAccessChain();
1324 builder.setAccessChainRValue(length);
1325
1326 return false;
1327 }
1328
John Kessenichfc51d282015-08-19 13:34:18 -06001329 // Start by evaluating the operand
1330
John Kessenich8c8505c2016-07-26 12:50:38 -06001331 // Does it need a swizzle inversion? If so, evaluation is inverted;
1332 // operate first on the swizzle base, then apply the swizzle.
1333 spv::Id invertedType = spv::NoType;
1334 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1335 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1336 invertedType = getInvertedSwizzleType(*node->getOperand());
1337
John Kessenich140f3df2015-06-26 16:58:36 -06001338 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001339 if (invertedType != spv::NoType)
1340 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1341 else
1342 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001343
Rex Xufc618912015-09-09 16:42:49 +08001344 spv::Id operand = spv::NoResult;
1345
1346 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1347 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001348 node->getOp() == glslang::EOpAtomicCounter ||
1349 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001350 operand = builder.accessChainGetLValue(); // Special case l-value operands
1351 else
John Kessenich32cfd492016-02-02 12:37:46 -07001352 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001353
John Kessenichf6640762016-08-01 19:44:00 -06001354 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001355 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001356
1357 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001358 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001359 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001360
1361 // if not, then possibly an operation
1362 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001363 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001364
1365 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001366 if (invertedType)
1367 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1368
John Kessenich140f3df2015-06-26 16:58:36 -06001369 builder.clearAccessChain();
1370 builder.setAccessChainRValue(result);
1371
1372 return false; // done with this node
1373 }
1374
1375 // it must be a special case, check...
1376 switch (node->getOp()) {
1377 case glslang::EOpPostIncrement:
1378 case glslang::EOpPostDecrement:
1379 case glslang::EOpPreIncrement:
1380 case glslang::EOpPreDecrement:
1381 {
1382 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001383 spv::Id one = 0;
1384 if (node->getBasicType() == glslang::EbtFloat)
1385 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001386 else if (node->getBasicType() == glslang::EbtDouble)
1387 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001388#ifdef AMD_EXTENSIONS
1389 else if (node->getBasicType() == glslang::EbtFloat16)
1390 one = builder.makeFloat16Constant(1.0F);
1391#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001392 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1393 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001394#ifdef AMD_EXTENSIONS
1395 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1396 one = builder.makeInt16Constant(1);
1397#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001398 else
1399 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001400 glslang::TOperator op;
1401 if (node->getOp() == glslang::EOpPreIncrement ||
1402 node->getOp() == glslang::EOpPostIncrement)
1403 op = glslang::EOpAdd;
1404 else
1405 op = glslang::EOpSub;
1406
John Kessenichf6640762016-08-01 19:44:00 -06001407 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001408 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001409 convertGlslangToSpvType(node->getType()), operand, one,
1410 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001411 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001412
1413 // The result of operation is always stored, but conditionally the
1414 // consumed result. The consumed result is always an r-value.
1415 builder.accessChainStore(result);
1416 builder.clearAccessChain();
1417 if (node->getOp() == glslang::EOpPreIncrement ||
1418 node->getOp() == glslang::EOpPreDecrement)
1419 builder.setAccessChainRValue(result);
1420 else
1421 builder.setAccessChainRValue(operand);
1422 }
1423
1424 return false;
1425
1426 case glslang::EOpEmitStreamVertex:
1427 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1428 return false;
1429 case glslang::EOpEndStreamPrimitive:
1430 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1431 return false;
1432
1433 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001434 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001435 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001436 }
John Kessenich140f3df2015-06-26 16:58:36 -06001437}
1438
1439bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1440{
qining27e04a02016-04-14 16:40:20 -04001441 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1442 if (node->getType().getQualifier().isSpecConstant())
1443 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1444
John Kessenichfc51d282015-08-19 13:34:18 -06001445 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001446 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1447 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001448
1449 // try texturing
1450 result = createImageTextureFunctionCall(node);
1451 if (result != spv::NoResult) {
1452 builder.clearAccessChain();
1453 builder.setAccessChainRValue(result);
1454
1455 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001456 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001457 // "imageStore" is a special case, which has no result
1458 return false;
1459 }
John Kessenichfc51d282015-08-19 13:34:18 -06001460
John Kessenich140f3df2015-06-26 16:58:36 -06001461 glslang::TOperator binOp = glslang::EOpNull;
1462 bool reduceComparison = true;
1463 bool isMatrix = false;
1464 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001465 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001466
1467 assert(node->getOp());
1468
John Kessenichf6640762016-08-01 19:44:00 -06001469 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001470
1471 switch (node->getOp()) {
1472 case glslang::EOpSequence:
1473 {
1474 if (preVisit)
1475 ++sequenceDepth;
1476 else
1477 --sequenceDepth;
1478
1479 if (sequenceDepth == 1) {
1480 // If this is the parent node of all the functions, we want to see them
1481 // early, so all call points have actual SPIR-V functions to reference.
1482 // In all cases, still let the traverser visit the children for us.
1483 makeFunctions(node->getAsAggregate()->getSequence());
1484
John Kessenich6fccb3c2016-09-19 16:01:41 -06001485 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001486 // anything else gets there, so visit out of order, doing them all now.
1487 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1488
John Kessenich6a60c2f2016-12-08 21:01:59 -07001489 // 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 -06001490 // so do them manually.
1491 visitFunctions(node->getAsAggregate()->getSequence());
1492
1493 return false;
1494 }
1495
1496 return true;
1497 }
1498 case glslang::EOpLinkerObjects:
1499 {
1500 if (visit == glslang::EvPreVisit)
1501 linkageOnly = true;
1502 else
1503 linkageOnly = false;
1504
1505 return true;
1506 }
1507 case glslang::EOpComma:
1508 {
1509 // processing from left to right naturally leaves the right-most
1510 // lying around in the access chain
1511 glslang::TIntermSequence& glslangOperands = node->getSequence();
1512 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1513 glslangOperands[i]->traverse(this);
1514
1515 return false;
1516 }
1517 case glslang::EOpFunction:
1518 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001519 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001520 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001521 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001522 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001523 } else {
1524 handleFunctionEntry(node);
1525 }
1526 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001527 if (inEntryPoint)
1528 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001529 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001530 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001531 }
1532
1533 return true;
1534 case glslang::EOpParameters:
1535 // Parameters will have been consumed by EOpFunction processing, but not
1536 // the body, so we still visited the function node's children, making this
1537 // child redundant.
1538 return false;
1539 case glslang::EOpFunctionCall:
1540 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001541 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001542 if (node->isUserDefined())
1543 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001544 // 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 -07001545 if (result) {
1546 builder.clearAccessChain();
1547 builder.setAccessChainRValue(result);
1548 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001549 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001550
1551 return false;
1552 }
1553 case glslang::EOpConstructMat2x2:
1554 case glslang::EOpConstructMat2x3:
1555 case glslang::EOpConstructMat2x4:
1556 case glslang::EOpConstructMat3x2:
1557 case glslang::EOpConstructMat3x3:
1558 case glslang::EOpConstructMat3x4:
1559 case glslang::EOpConstructMat4x2:
1560 case glslang::EOpConstructMat4x3:
1561 case glslang::EOpConstructMat4x4:
1562 case glslang::EOpConstructDMat2x2:
1563 case glslang::EOpConstructDMat2x3:
1564 case glslang::EOpConstructDMat2x4:
1565 case glslang::EOpConstructDMat3x2:
1566 case glslang::EOpConstructDMat3x3:
1567 case glslang::EOpConstructDMat3x4:
1568 case glslang::EOpConstructDMat4x2:
1569 case glslang::EOpConstructDMat4x3:
1570 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001571 case glslang::EOpConstructIMat2x2:
1572 case glslang::EOpConstructIMat2x3:
1573 case glslang::EOpConstructIMat2x4:
1574 case glslang::EOpConstructIMat3x2:
1575 case glslang::EOpConstructIMat3x3:
1576 case glslang::EOpConstructIMat3x4:
1577 case glslang::EOpConstructIMat4x2:
1578 case glslang::EOpConstructIMat4x3:
1579 case glslang::EOpConstructIMat4x4:
1580 case glslang::EOpConstructUMat2x2:
1581 case glslang::EOpConstructUMat2x3:
1582 case glslang::EOpConstructUMat2x4:
1583 case glslang::EOpConstructUMat3x2:
1584 case glslang::EOpConstructUMat3x3:
1585 case glslang::EOpConstructUMat3x4:
1586 case glslang::EOpConstructUMat4x2:
1587 case glslang::EOpConstructUMat4x3:
1588 case glslang::EOpConstructUMat4x4:
1589 case glslang::EOpConstructBMat2x2:
1590 case glslang::EOpConstructBMat2x3:
1591 case glslang::EOpConstructBMat2x4:
1592 case glslang::EOpConstructBMat3x2:
1593 case glslang::EOpConstructBMat3x3:
1594 case glslang::EOpConstructBMat3x4:
1595 case glslang::EOpConstructBMat4x2:
1596 case glslang::EOpConstructBMat4x3:
1597 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001598#ifdef AMD_EXTENSIONS
1599 case glslang::EOpConstructF16Mat2x2:
1600 case glslang::EOpConstructF16Mat2x3:
1601 case glslang::EOpConstructF16Mat2x4:
1602 case glslang::EOpConstructF16Mat3x2:
1603 case glslang::EOpConstructF16Mat3x3:
1604 case glslang::EOpConstructF16Mat3x4:
1605 case glslang::EOpConstructF16Mat4x2:
1606 case glslang::EOpConstructF16Mat4x3:
1607 case glslang::EOpConstructF16Mat4x4:
1608#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001609 isMatrix = true;
1610 // fall through
1611 case glslang::EOpConstructFloat:
1612 case glslang::EOpConstructVec2:
1613 case glslang::EOpConstructVec3:
1614 case glslang::EOpConstructVec4:
1615 case glslang::EOpConstructDouble:
1616 case glslang::EOpConstructDVec2:
1617 case glslang::EOpConstructDVec3:
1618 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001619#ifdef AMD_EXTENSIONS
1620 case glslang::EOpConstructFloat16:
1621 case glslang::EOpConstructF16Vec2:
1622 case glslang::EOpConstructF16Vec3:
1623 case glslang::EOpConstructF16Vec4:
1624#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001625 case glslang::EOpConstructBool:
1626 case glslang::EOpConstructBVec2:
1627 case glslang::EOpConstructBVec3:
1628 case glslang::EOpConstructBVec4:
1629 case glslang::EOpConstructInt:
1630 case glslang::EOpConstructIVec2:
1631 case glslang::EOpConstructIVec3:
1632 case glslang::EOpConstructIVec4:
1633 case glslang::EOpConstructUint:
1634 case glslang::EOpConstructUVec2:
1635 case glslang::EOpConstructUVec3:
1636 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001637 case glslang::EOpConstructInt64:
1638 case glslang::EOpConstructI64Vec2:
1639 case glslang::EOpConstructI64Vec3:
1640 case glslang::EOpConstructI64Vec4:
1641 case glslang::EOpConstructUint64:
1642 case glslang::EOpConstructU64Vec2:
1643 case glslang::EOpConstructU64Vec3:
1644 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001645#ifdef AMD_EXTENSIONS
1646 case glslang::EOpConstructInt16:
1647 case glslang::EOpConstructI16Vec2:
1648 case glslang::EOpConstructI16Vec3:
1649 case glslang::EOpConstructI16Vec4:
1650 case glslang::EOpConstructUint16:
1651 case glslang::EOpConstructU16Vec2:
1652 case glslang::EOpConstructU16Vec3:
1653 case glslang::EOpConstructU16Vec4:
1654#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001655 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001656 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001657 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001658 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001659 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001660 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001661 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001662 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001663 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001664 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001665 std::vector<spv::Id> constituents;
1666 for (int c = 0; c < (int)arguments.size(); ++c)
1667 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001668 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001669 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001670 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001671 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001672 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001673
1674 builder.clearAccessChain();
1675 builder.setAccessChainRValue(constructed);
1676
1677 return false;
1678 }
1679
1680 // These six are component-wise compares with component-wise results.
1681 // Forward on to createBinaryOperation(), requesting a vector result.
1682 case glslang::EOpLessThan:
1683 case glslang::EOpGreaterThan:
1684 case glslang::EOpLessThanEqual:
1685 case glslang::EOpGreaterThanEqual:
1686 case glslang::EOpVectorEqual:
1687 case glslang::EOpVectorNotEqual:
1688 {
1689 // Map the operation to a binary
1690 binOp = node->getOp();
1691 reduceComparison = false;
1692 switch (node->getOp()) {
1693 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1694 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1695 default: binOp = node->getOp(); break;
1696 }
1697
1698 break;
1699 }
1700 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001701 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001702 binOp = glslang::EOpMul;
1703 break;
1704 case glslang::EOpOuterProduct:
1705 // two vectors multiplied to make a matrix
1706 binOp = glslang::EOpOuterProduct;
1707 break;
1708 case glslang::EOpDot:
1709 {
qining25262b32016-05-06 17:25:16 -04001710 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001711 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001712 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001713 binOp = glslang::EOpMul;
1714 break;
1715 }
1716 case glslang::EOpMod:
1717 // when an aggregate, this is the floating-point mod built-in function,
1718 // which can be emitted by the one in createBinaryOperation()
1719 binOp = glslang::EOpMod;
1720 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001721 case glslang::EOpEmitVertex:
1722 case glslang::EOpEndPrimitive:
1723 case glslang::EOpBarrier:
1724 case glslang::EOpMemoryBarrier:
1725 case glslang::EOpMemoryBarrierAtomicCounter:
1726 case glslang::EOpMemoryBarrierBuffer:
1727 case glslang::EOpMemoryBarrierImage:
1728 case glslang::EOpMemoryBarrierShared:
1729 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001730 case glslang::EOpAllMemoryBarrierWithGroupSync:
1731 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1732 case glslang::EOpWorkgroupMemoryBarrier:
1733 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001734 noReturnValue = true;
1735 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1736 break;
1737
John Kessenich426394d2015-07-23 10:22:48 -06001738 case glslang::EOpAtomicAdd:
1739 case glslang::EOpAtomicMin:
1740 case glslang::EOpAtomicMax:
1741 case glslang::EOpAtomicAnd:
1742 case glslang::EOpAtomicOr:
1743 case glslang::EOpAtomicXor:
1744 case glslang::EOpAtomicExchange:
1745 case glslang::EOpAtomicCompSwap:
1746 atomic = true;
1747 break;
1748
John Kessenich0d0c6d32017-07-23 16:08:26 -06001749 case glslang::EOpAtomicCounterAdd:
1750 case glslang::EOpAtomicCounterSubtract:
1751 case glslang::EOpAtomicCounterMin:
1752 case glslang::EOpAtomicCounterMax:
1753 case glslang::EOpAtomicCounterAnd:
1754 case glslang::EOpAtomicCounterOr:
1755 case glslang::EOpAtomicCounterXor:
1756 case glslang::EOpAtomicCounterExchange:
1757 case glslang::EOpAtomicCounterCompSwap:
1758 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1759 builder.addCapability(spv::CapabilityAtomicStorageOps);
1760 atomic = true;
1761 break;
1762
John Kessenich140f3df2015-06-26 16:58:36 -06001763 default:
1764 break;
1765 }
1766
1767 //
1768 // See if it maps to a regular operation.
1769 //
John Kessenich140f3df2015-06-26 16:58:36 -06001770 if (binOp != glslang::EOpNull) {
1771 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1772 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1773 assert(left && right);
1774
1775 builder.clearAccessChain();
1776 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001777 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001778
1779 builder.clearAccessChain();
1780 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001781 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001782
John Kesseniche485c7a2017-05-31 18:50:53 -06001783 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001784 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001785 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001786 left->getType().getBasicType(), reduceComparison);
1787
1788 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001789 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001790 builder.clearAccessChain();
1791 builder.setAccessChainRValue(result);
1792
1793 return false;
1794 }
1795
John Kessenich426394d2015-07-23 10:22:48 -06001796 //
1797 // Create the list of operands.
1798 //
John Kessenich140f3df2015-06-26 16:58:36 -06001799 glslang::TIntermSequence& glslangOperands = node->getSequence();
1800 std::vector<spv::Id> operands;
1801 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001802 // special case l-value operands; there are just a few
1803 bool lvalue = false;
1804 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001805 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001806 case glslang::EOpModf:
1807 if (arg == 1)
1808 lvalue = true;
1809 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001810 case glslang::EOpInterpolateAtSample:
1811 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001812#ifdef AMD_EXTENSIONS
1813 case glslang::EOpInterpolateAtVertex:
1814#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001815 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001816 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001817
1818 // Does it need a swizzle inversion? If so, evaluation is inverted;
1819 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001820 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001821 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1822 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1823 }
Rex Xu7a26c172015-12-08 17:12:09 +08001824 break;
Rex Xud4782c12015-09-06 16:30:11 +08001825 case glslang::EOpAtomicAdd:
1826 case glslang::EOpAtomicMin:
1827 case glslang::EOpAtomicMax:
1828 case glslang::EOpAtomicAnd:
1829 case glslang::EOpAtomicOr:
1830 case glslang::EOpAtomicXor:
1831 case glslang::EOpAtomicExchange:
1832 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001833 case glslang::EOpAtomicCounterAdd:
1834 case glslang::EOpAtomicCounterSubtract:
1835 case glslang::EOpAtomicCounterMin:
1836 case glslang::EOpAtomicCounterMax:
1837 case glslang::EOpAtomicCounterAnd:
1838 case glslang::EOpAtomicCounterOr:
1839 case glslang::EOpAtomicCounterXor:
1840 case glslang::EOpAtomicCounterExchange:
1841 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001842 if (arg == 0)
1843 lvalue = true;
1844 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001845 case glslang::EOpAddCarry:
1846 case glslang::EOpSubBorrow:
1847 if (arg == 2)
1848 lvalue = true;
1849 break;
1850 case glslang::EOpUMulExtended:
1851 case glslang::EOpIMulExtended:
1852 if (arg >= 2)
1853 lvalue = true;
1854 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001855 default:
1856 break;
1857 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001858 builder.clearAccessChain();
1859 if (invertedType != spv::NoType && arg == 0)
1860 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1861 else
1862 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001863 if (lvalue)
1864 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001865 else {
1866 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001867 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001868 }
John Kessenich140f3df2015-06-26 16:58:36 -06001869 }
John Kessenich426394d2015-07-23 10:22:48 -06001870
John Kesseniche485c7a2017-05-31 18:50:53 -06001871 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001872 if (atomic) {
1873 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001874 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001875 } else {
1876 // Pass through to generic operations.
1877 switch (glslangOperands.size()) {
1878 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001879 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001880 break;
1881 case 1:
qining25262b32016-05-06 17:25:16 -04001882 result = createUnaryOperation(
1883 node->getOp(), precision,
1884 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001885 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001886 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001887 break;
1888 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001889 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001890 break;
1891 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001892 if (invertedType)
1893 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001894 }
1895
1896 if (noReturnValue)
1897 return false;
1898
1899 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001900 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001901 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001902 } else {
1903 builder.clearAccessChain();
1904 builder.setAccessChainRValue(result);
1905 return false;
1906 }
1907}
1908
John Kessenich433e9ff2017-01-26 20:31:11 -07001909// This path handles both if-then-else and ?:
1910// The if-then-else has a node type of void, while
1911// ?: has either a void or a non-void node type
1912//
1913// Leaving the result, when not void:
1914// GLSL only has r-values as the result of a :?, but
1915// if we have an l-value, that can be more efficient if it will
1916// become the base of a complex r-value expression, because the
1917// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001918bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1919{
John Kessenich433e9ff2017-01-26 20:31:11 -07001920 // See if it simple and safe to generate OpSelect instead of using control flow.
1921 // Crucially, side effects must be avoided, and there are performance trade-offs.
1922 // Return true if good idea (and safe) for OpSelect, false otherwise.
1923 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001924 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1925 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001926 return false;
1927
1928 if (node->getTrueBlock() == nullptr ||
1929 node->getFalseBlock() == nullptr)
1930 return false;
1931
1932 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1933 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1934
1935 // return true if a single operand to ? : is okay for OpSelect
1936 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001937 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001938 };
1939
1940 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1941 operandOkay(node->getFalseBlock()->getAsTyped());
1942 };
1943
1944 // Emit OpSelect for this selection.
1945 const auto handleAsOpSelect = [&]() {
1946 node->getCondition()->traverse(this);
1947 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1948 node->getTrueBlock()->traverse(this);
1949 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1950 node->getFalseBlock()->traverse(this);
1951 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1952
John Kesseniche485c7a2017-05-31 18:50:53 -06001953 builder.setLine(node->getLoc().line);
1954
John Kesseniche434ad92017-03-30 10:09:28 -06001955 // smear condition to vector, if necessary (AST is always scalar)
1956 if (builder.isVector(trueValue))
1957 condition = builder.smearScalar(spv::NoPrecision, condition,
1958 builder.makeVectorType(builder.makeBoolType(),
1959 builder.getNumComponents(trueValue)));
1960
1961 spv::Id select = builder.createTriOp(spv::OpSelect,
1962 convertGlslangToSpvType(node->getType()), condition,
1963 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001964 builder.clearAccessChain();
1965 builder.setAccessChainRValue(select);
1966 };
1967
1968 // Try for OpSelect
1969
1970 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001971 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1972 if (node->getType().getQualifier().isSpecConstant())
1973 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1974
John Kessenich433e9ff2017-01-26 20:31:11 -07001975 handleAsOpSelect();
1976 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001977 }
1978
Rex Xu57e65922017-07-04 23:23:40 +08001979 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07001980 // Don't handle results as temporaries, because there will be two names
1981 // and better to leave SSA to later passes.
1982 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1983 ? spv::NoResult
1984 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1985
John Kessenich140f3df2015-06-26 16:58:36 -06001986 // emit the condition before doing anything with selection
1987 node->getCondition()->traverse(this);
1988
Rex Xu57e65922017-07-04 23:23:40 +08001989 // Selection control:
1990 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
1991
John Kessenich140f3df2015-06-26 16:58:36 -06001992 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08001993 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001994
John Kessenich433e9ff2017-01-26 20:31:11 -07001995 // emit the "then" statement
1996 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001997 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001998 if (result != spv::NoResult)
1999 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002000 }
2001
John Kessenich433e9ff2017-01-26 20:31:11 -07002002 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002003 ifBuilder.makeBeginElse();
2004 // emit the "else" statement
2005 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002006 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002007 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002008 }
2009
John Kessenich433e9ff2017-01-26 20:31:11 -07002010 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002011 ifBuilder.makeEndIf();
2012
John Kessenich433e9ff2017-01-26 20:31:11 -07002013 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002014 // GLSL only has r-values as the result of a :?, but
2015 // if we have an l-value, that can be more efficient if it will
2016 // become the base of a complex r-value expression, because the
2017 // next layer copies r-values into memory to use the access-chain mechanism
2018 builder.clearAccessChain();
2019 builder.setAccessChainLValue(result);
2020 }
2021
2022 return false;
2023}
2024
2025bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2026{
2027 // emit and get the condition before doing anything with switch
2028 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002029 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002030
Rex Xu57e65922017-07-04 23:23:40 +08002031 // Selection control:
2032 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2033
John Kessenich140f3df2015-06-26 16:58:36 -06002034 // browse the children to sort out code segments
2035 int defaultSegment = -1;
2036 std::vector<TIntermNode*> codeSegments;
2037 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2038 std::vector<int> caseValues;
2039 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2040 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2041 TIntermNode* child = *c;
2042 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002043 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002044 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002045 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002046 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2047 } else
2048 codeSegments.push_back(child);
2049 }
2050
qining25262b32016-05-06 17:25:16 -04002051 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002052 // statements between the last case and the end of the switch statement
2053 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2054 (int)codeSegments.size() == defaultSegment)
2055 codeSegments.push_back(nullptr);
2056
2057 // make the switch statement
2058 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002059 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002060
2061 // emit all the code in the segments
2062 breakForLoop.push(false);
2063 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2064 builder.nextSwitchSegment(segmentBlocks, s);
2065 if (codeSegments[s])
2066 codeSegments[s]->traverse(this);
2067 else
2068 builder.addSwitchBreak();
2069 }
2070 breakForLoop.pop();
2071
2072 builder.endSwitch(segmentBlocks);
2073
2074 return false;
2075}
2076
2077void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2078{
2079 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002080 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002081
2082 builder.clearAccessChain();
2083 builder.setAccessChainRValue(constant);
2084}
2085
2086bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2087{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002088 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002089 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002090
2091 // Loop control:
2092 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2093
2094 // TODO: dependency length
2095
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002096 // Spec requires back edges to target header blocks, and every header block
2097 // must dominate its merge block. Make a header block first to ensure these
2098 // conditions are met. By definition, it will contain OpLoopMerge, followed
2099 // by a block-ending branch. But we don't want to put any other body/test
2100 // instructions in it, since the body/test may have arbitrary instructions,
2101 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002102 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002103 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002104 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002105 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002106 spv::Block& test = builder.makeNewBlock();
2107 builder.createBranch(&test);
2108
2109 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002110 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002111 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002112 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2113
2114 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002115 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002116 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002117 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002118 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002119 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002120
2121 builder.setBuildPoint(&blocks.continue_target);
2122 if (node->getTerminal())
2123 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002124 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002125 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002126 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002127 builder.createBranch(&blocks.body);
2128
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002129 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002130 builder.setBuildPoint(&blocks.body);
2131 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002132 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002133 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002134 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002135
2136 builder.setBuildPoint(&blocks.continue_target);
2137 if (node->getTerminal())
2138 node->getTerminal()->traverse(this);
2139 if (node->getTest()) {
2140 node->getTest()->traverse(this);
2141 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002142 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002143 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002144 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002145 // TODO: unless there was a break/return/discard instruction
2146 // somewhere in the body, this is an infinite loop, so we should
2147 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002148 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002149 }
John Kessenich140f3df2015-06-26 16:58:36 -06002150 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002151 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002152 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002153 return false;
2154}
2155
2156bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2157{
2158 if (node->getExpression())
2159 node->getExpression()->traverse(this);
2160
John Kesseniche485c7a2017-05-31 18:50:53 -06002161 builder.setLine(node->getLoc().line);
2162
John Kessenich140f3df2015-06-26 16:58:36 -06002163 switch (node->getFlowOp()) {
2164 case glslang::EOpKill:
2165 builder.makeDiscard();
2166 break;
2167 case glslang::EOpBreak:
2168 if (breakForLoop.top())
2169 builder.createLoopExit();
2170 else
2171 builder.addSwitchBreak();
2172 break;
2173 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002174 builder.createLoopContinue();
2175 break;
2176 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002177 if (node->getExpression()) {
2178 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2179 spv::Id returnId = accessChainLoad(glslangReturnType);
2180 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2181 builder.clearAccessChain();
2182 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2183 builder.setAccessChainLValue(copyId);
2184 multiTypeStore(glslangReturnType, returnId);
2185 returnId = builder.createLoad(copyId);
2186 }
2187 builder.makeReturn(false, returnId);
2188 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002189 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002190
2191 builder.clearAccessChain();
2192 break;
2193
2194 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002195 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002196 break;
2197 }
2198
2199 return false;
2200}
2201
2202spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2203{
qining25262b32016-05-06 17:25:16 -04002204 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002205 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002206 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002207 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002208 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002209 }
2210
2211 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002212 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002213 spv::Id spvType = convertGlslangToSpvType(node->getType());
2214
Rex Xuf89ad982017-04-07 23:22:33 +08002215#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002216 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2217 node->getType().containsBasicType(glslang::EbtInt16) ||
2218 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002219 if (contains16BitType) {
2220 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2221 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2222 builder.addCapability(spv::CapabilityStorageInputOutput16);
2223 } else if (storageClass == spv::StorageClassPushConstant) {
2224 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2225 builder.addCapability(spv::CapabilityStoragePushConstant16);
2226 } else if (storageClass == spv::StorageClassUniform) {
2227 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2228 builder.addCapability(spv::CapabilityStorageUniform16);
2229 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2230 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2231 }
2232 }
2233#endif
2234
John Kessenich140f3df2015-06-26 16:58:36 -06002235 const char* name = node->getName().c_str();
2236 if (glslang::IsAnonymous(name))
2237 name = "";
2238
2239 return builder.createVariable(storageClass, spvType, name);
2240}
2241
2242// Return type Id of the sampled type.
2243spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2244{
2245 switch (sampler.type) {
2246 case glslang::EbtFloat: return builder.makeFloatType(32);
2247 case glslang::EbtInt: return builder.makeIntType(32);
2248 case glslang::EbtUint: return builder.makeUintType(32);
2249 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002250 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002251 return builder.makeFloatType(32);
2252 }
2253}
2254
John Kessenich8c8505c2016-07-26 12:50:38 -06002255// If node is a swizzle operation, return the type that should be used if
2256// the swizzle base is first consumed by another operation, before the swizzle
2257// is applied.
2258spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2259{
John Kessenichecba76f2017-01-06 00:34:48 -07002260 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002261 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2262 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2263 else
2264 return spv::NoType;
2265}
2266
2267// When inverting a swizzle with a parent op, this function
2268// will apply the swizzle operation to a completed parent operation.
2269spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2270{
2271 std::vector<unsigned> swizzle;
2272 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2273 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2274}
2275
John Kessenich8c8505c2016-07-26 12:50:38 -06002276// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2277void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2278{
2279 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2280 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2281 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2282}
2283
John Kessenich3ac051e2015-12-20 11:29:16 -07002284// Convert from a glslang type to an SPV type, by calling into a
2285// recursive version of this function. This establishes the inherited
2286// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002287spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2288{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002289 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002290}
2291
2292// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002293// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002294// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002295spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002296{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002297 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002298
2299 switch (type.getBasicType()) {
2300 case glslang::EbtVoid:
2301 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002302 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002303 break;
2304 case glslang::EbtFloat:
2305 spvType = builder.makeFloatType(32);
2306 break;
2307 case glslang::EbtDouble:
2308 spvType = builder.makeFloatType(64);
2309 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002310#ifdef AMD_EXTENSIONS
2311 case glslang::EbtFloat16:
2312 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002313 spvType = builder.makeFloatType(16);
2314 break;
2315#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002316 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002317 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2318 // a 32-bit int where non-0 means true.
2319 if (explicitLayout != glslang::ElpNone)
2320 spvType = builder.makeUintType(32);
2321 else
2322 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002323 break;
2324 case glslang::EbtInt:
2325 spvType = builder.makeIntType(32);
2326 break;
2327 case glslang::EbtUint:
2328 spvType = builder.makeUintType(32);
2329 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002330 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002331 spvType = builder.makeIntType(64);
2332 break;
2333 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002334 spvType = builder.makeUintType(64);
2335 break;
Rex Xucabbb782017-03-24 13:41:14 +08002336#ifdef AMD_EXTENSIONS
2337 case glslang::EbtInt16:
2338 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2339 spvType = builder.makeIntType(16);
2340 break;
2341 case glslang::EbtUint16:
2342 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2343 spvType = builder.makeUintType(16);
2344 break;
2345#endif
John Kessenich426394d2015-07-23 10:22:48 -06002346 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002347 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002348 spvType = builder.makeUintType(32);
2349 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002350 case glslang::EbtSampler:
2351 {
2352 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002353 if (sampler.sampler) {
2354 // pure sampler
2355 spvType = builder.makeSamplerType();
2356 } else {
2357 // an image is present, make its type
2358 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2359 sampler.image ? 2 : 1, TranslateImageFormat(type));
2360 if (sampler.combined) {
2361 // already has both image and sampler, make the combined type
2362 spvType = builder.makeSampledImageType(spvType);
2363 }
John Kessenich55e7d112015-11-15 21:33:39 -07002364 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002365 }
John Kessenich140f3df2015-06-26 16:58:36 -06002366 break;
2367 case glslang::EbtStruct:
2368 case glslang::EbtBlock:
2369 {
2370 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002371 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002372
2373 // Try to share structs for different layouts, but not yet for other
2374 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002375 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002376 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002377 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002378 break;
2379
2380 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002381 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002382 memberRemapper[glslangMembers].resize(glslangMembers->size());
2383 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002384 }
2385 break;
2386 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002387 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002388 break;
2389 }
2390
2391 if (type.isMatrix())
2392 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2393 else {
2394 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2395 if (type.getVectorSize() > 1)
2396 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2397 }
2398
2399 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002400 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2401
John Kessenichc9a80832015-09-12 12:17:44 -06002402 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002403 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002404 // We need to decorate array strides for types needing explicit layout, except blocks.
2405 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002406 // Use a dummy glslang type for querying internal strides of
2407 // arrays of arrays, but using just a one-dimensional array.
2408 glslang::TType simpleArrayType(type, 0); // deference type of the array
2409 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2410 simpleArrayType.getArraySizes().dereference();
2411
2412 // Will compute the higher-order strides here, rather than making a whole
2413 // pile of types and doing repetitive recursion on their contents.
2414 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2415 }
John Kessenichf8842e52016-01-04 19:22:56 -07002416
2417 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002418 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002419 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002420 if (stride > 0)
2421 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002422 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002423 }
2424 } else {
2425 // single-dimensional array, and don't yet have stride
2426
John Kessenichf8842e52016-01-04 19:22:56 -07002427 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002428 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2429 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002430 }
John Kessenich31ed4832015-09-09 17:51:38 -06002431
John Kessenichc9a80832015-09-12 12:17:44 -06002432 // Do the outer dimension, which might not be known for a runtime-sized array
2433 if (type.isRuntimeSizedArray()) {
2434 spvType = builder.makeRuntimeArray(spvType);
2435 } else {
2436 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002437 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002438 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002439 if (stride > 0)
2440 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002441 }
2442
2443 return spvType;
2444}
2445
John Kessenich0e737842017-03-24 18:38:16 -06002446// TODO: this functionality should exist at a higher level, in creating the AST
2447//
2448// Identify interface members that don't have their required extension turned on.
2449//
2450bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2451{
2452 auto& extensions = glslangIntermediate->getRequestedExtensions();
2453
Rex Xubcf291a2017-03-29 23:01:36 +08002454 if (member.getFieldName() == "gl_ViewportMask" &&
2455 extensions.find("GL_NV_viewport_array2") == extensions.end())
2456 return true;
2457 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2458 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2459 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002460 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2461 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2462 return true;
2463 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2464 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2465 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002466 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2467 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2468 return true;
John Kessenichd6be6da2017-08-17 23:49:39 -06002469 if ((member.getFieldName() == "gl_ViewportIndex" || member.getFieldName() == "gl_Layer") &&
2470 extensions.find(glslang::E_GL_ARB_shader_viewport_layer_array) == extensions.end() &&
John Kessenich786e8792017-08-19 15:54:49 -06002471 extensions.find("GL_NV_viewport_array2") == extensions.end())
John Kessenichd6be6da2017-08-17 23:49:39 -06002472 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002473
2474 return false;
2475};
2476
John Kessenich6090df02016-06-30 21:18:02 -06002477// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2478// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2479// Mutually recursive with convertGlslangToSpvType().
2480spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2481 const glslang::TTypeList* glslangMembers,
2482 glslang::TLayoutPacking explicitLayout,
2483 const glslang::TQualifier& qualifier)
2484{
2485 // Create a vector of struct types for SPIR-V to consume
2486 std::vector<spv::Id> spvMembers;
2487 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 -06002488 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2489 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2490 if (glslangMember.hiddenMember()) {
2491 ++memberDelta;
2492 if (type.getBasicType() == glslang::EbtBlock)
2493 memberRemapper[glslangMembers][i] = -1;
2494 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002495 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002496 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002497 if (filterMember(glslangMember))
2498 continue;
2499 }
John Kessenich6090df02016-06-30 21:18:02 -06002500 // modify just this child's view of the qualifier
2501 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2502 InheritQualifiers(memberQualifier, qualifier);
2503
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002504 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002505 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002506 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002507
2508 // recurse
2509 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2510 }
2511 }
2512
2513 // Make the SPIR-V type
2514 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002515 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002516 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2517
2518 // Decorate it
2519 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2520
2521 return spvType;
2522}
2523
2524void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2525 const glslang::TTypeList* glslangMembers,
2526 glslang::TLayoutPacking explicitLayout,
2527 const glslang::TQualifier& qualifier,
2528 spv::Id spvType)
2529{
2530 // Name and decorate the non-hidden members
2531 int offset = -1;
2532 int locationOffset = 0; // for use within the members of this struct
2533 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2534 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2535 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002536 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002537 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002538 if (filterMember(glslangMember))
2539 continue;
2540 }
John Kessenich6090df02016-06-30 21:18:02 -06002541
2542 // modify just this child's view of the qualifier
2543 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2544 InheritQualifiers(memberQualifier, qualifier);
2545
2546 // using -1 above to indicate a hidden member
2547 if (member >= 0) {
2548 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2549 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2550 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2551 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002552 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2553 type.getQualifier().storage == glslang::EvqVaryingOut) {
2554 if (type.getBasicType() == glslang::EbtBlock ||
2555 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002556 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2557 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2558 }
2559 }
2560 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2561
Rex Xu286ca432017-07-27 14:33:16 +08002562 if (type.getBasicType() == glslang::EbtBlock &&
2563 qualifier.storage == glslang::EvqBuffer) {
2564 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002565 std::vector<spv::Decoration> memory;
2566 TranslateMemoryDecoration(memberQualifier, memory);
2567 for (unsigned int i = 0; i < memory.size(); ++i)
2568 addMemberDecoration(spvType, member, memory[i]);
2569 }
2570
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002571 // Location assignment was already completed correctly by the front end,
2572 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002573 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002574 // ill-specified and decisions have been made to not allow this.
2575 if (! type.isArray() && memberQualifier.hasLocation())
2576 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002577
John Kessenich2f47bc92016-06-30 21:47:35 -06002578 if (qualifier.hasLocation()) // track for upcoming inheritance
2579 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2580
John Kessenich6090df02016-06-30 21:18:02 -06002581 // component, XFB, others
2582 if (glslangMember.getQualifier().hasComponent())
2583 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2584 if (glslangMember.getQualifier().hasXfbOffset())
2585 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2586 else if (explicitLayout != glslang::ElpNone) {
2587 // figure out what to do with offset, which is accumulating
2588 int nextOffset;
2589 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2590 if (offset >= 0)
2591 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2592 offset = nextOffset;
2593 }
2594
2595 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2596 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2597
2598 // built-in variable decorations
2599 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002600 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002601 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002602
2603#ifdef NV_EXTENSIONS
2604 if (builtIn == spv::BuiltInLayer) {
2605 // SPV_NV_viewport_array2 extension
2606 if (glslangMember.getQualifier().layoutViewportRelative){
2607 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2608 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2609 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2610 }
2611 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2612 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2613 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2614 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2615 }
2616 }
chaocdf3956c2017-02-14 14:52:34 -08002617 if (glslangMember.getQualifier().layoutPassthrough) {
2618 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2619 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2620 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2621 }
chaoc771d89f2017-01-13 01:10:53 -08002622#endif
John Kessenich6090df02016-06-30 21:18:02 -06002623 }
2624 }
2625
2626 // Decorate the structure
2627 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002628 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002629 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2630 builder.addCapability(spv::CapabilityGeometryStreams);
2631 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2632 }
2633 if (glslangIntermediate->getXfbMode()) {
2634 builder.addCapability(spv::CapabilityTransformFeedback);
2635 if (type.getQualifier().hasXfbStride())
2636 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2637 if (type.getQualifier().hasXfbBuffer())
2638 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2639 }
2640}
2641
John Kessenich6c292d32016-02-15 20:58:50 -07002642// Turn the expression forming the array size into an id.
2643// This is not quite trivial, because of specialization constants.
2644// Sometimes, a raw constant is turned into an Id, and sometimes
2645// a specialization constant expression is.
2646spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2647{
2648 // First, see if this is sized with a node, meaning a specialization constant:
2649 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2650 if (specNode != nullptr) {
2651 builder.clearAccessChain();
2652 specNode->traverse(this);
2653 return accessChainLoad(specNode->getAsTyped()->getType());
2654 }
qining25262b32016-05-06 17:25:16 -04002655
John Kessenich6c292d32016-02-15 20:58:50 -07002656 // Otherwise, need a compile-time (front end) size, get it:
2657 int size = arraySizes.getDimSize(dim);
2658 assert(size > 0);
2659 return builder.makeUintConstant(size);
2660}
2661
John Kessenich103bef92016-02-08 21:38:15 -07002662// Wrap the builder's accessChainLoad to:
2663// - localize handling of RelaxedPrecision
2664// - use the SPIR-V inferred type instead of another conversion of the glslang type
2665// (avoids unnecessary work and possible type punning for structures)
2666// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002667spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2668{
John Kessenich103bef92016-02-08 21:38:15 -07002669 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2670 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2671
2672 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002673 if (type.getBasicType() == glslang::EbtBool) {
2674 if (builder.isScalarType(nominalTypeId)) {
2675 // Conversion for bool
2676 spv::Id boolType = builder.makeBoolType();
2677 if (nominalTypeId != boolType)
2678 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2679 } else if (builder.isVectorType(nominalTypeId)) {
2680 // Conversion for bvec
2681 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2682 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2683 if (nominalTypeId != bvecType)
2684 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2685 }
2686 }
John Kessenich103bef92016-02-08 21:38:15 -07002687
2688 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002689}
2690
Rex Xu27253232016-02-23 17:51:09 +08002691// Wrap the builder's accessChainStore to:
2692// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002693//
2694// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002695void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2696{
2697 // Need to convert to abstract types when necessary
2698 if (type.getBasicType() == glslang::EbtBool) {
2699 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2700
2701 if (builder.isScalarType(nominalTypeId)) {
2702 // Conversion for bool
2703 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002704 if (nominalTypeId != boolType) {
2705 // keep these outside arguments, for determinant order-of-evaluation
2706 spv::Id one = builder.makeUintConstant(1);
2707 spv::Id zero = builder.makeUintConstant(0);
2708 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2709 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002710 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002711 } else if (builder.isVectorType(nominalTypeId)) {
2712 // Conversion for bvec
2713 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2714 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002715 if (nominalTypeId != bvecType) {
2716 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002717 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2718 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2719 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002720 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002721 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2722 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002723 }
2724 }
2725
2726 builder.accessChainStore(rvalue);
2727}
2728
John Kessenich4bf71552016-09-02 11:20:21 -06002729// For storing when types match at the glslang level, but not might match at the
2730// SPIR-V level.
2731//
2732// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002733// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002734// as in a member-decorated way.
2735//
2736// NOTE: This function can handle any store request; if it's not special it
2737// simplifies to a simple OpStore.
2738//
2739// Implicitly uses the existing builder.accessChain as the storage target.
2740void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2741{
John Kessenichb3e24e42016-09-11 12:33:43 -06002742 // we only do the complex path here if it's an aggregate
2743 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002744 accessChainStore(type, rValue);
2745 return;
2746 }
2747
John Kessenichb3e24e42016-09-11 12:33:43 -06002748 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002749 spv::Id rType = builder.getTypeId(rValue);
2750 spv::Id lValue = builder.accessChainGetLValue();
2751 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2752 if (lType == rType) {
2753 accessChainStore(type, rValue);
2754 return;
2755 }
2756
John Kessenichb3e24e42016-09-11 12:33:43 -06002757 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002758 // where the two types were the same type in GLSL. This requires member
2759 // by member copy, recursively.
2760
John Kessenichb3e24e42016-09-11 12:33:43 -06002761 // If an array, copy element by element.
2762 if (type.isArray()) {
2763 glslang::TType glslangElementType(type, 0);
2764 spv::Id elementRType = builder.getContainedTypeId(rType);
2765 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2766 // get the source member
2767 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002768
John Kessenichb3e24e42016-09-11 12:33:43 -06002769 // set up the target storage
2770 builder.clearAccessChain();
2771 builder.setAccessChainLValue(lValue);
2772 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002773
John Kessenichb3e24e42016-09-11 12:33:43 -06002774 // store the member
2775 multiTypeStore(glslangElementType, elementRValue);
2776 }
2777 } else {
2778 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002779
John Kessenichb3e24e42016-09-11 12:33:43 -06002780 // loop over structure members
2781 const glslang::TTypeList& members = *type.getStruct();
2782 for (int m = 0; m < (int)members.size(); ++m) {
2783 const glslang::TType& glslangMemberType = *members[m].type;
2784
2785 // get the source member
2786 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2787 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2788
2789 // set up the target storage
2790 builder.clearAccessChain();
2791 builder.setAccessChainLValue(lValue);
2792 builder.accessChainPush(builder.makeIntConstant(m));
2793
2794 // store the member
2795 multiTypeStore(glslangMemberType, memberRValue);
2796 }
John Kessenich4bf71552016-09-02 11:20:21 -06002797 }
2798}
2799
John Kessenichf85e8062015-12-19 13:57:10 -07002800// Decide whether or not this type should be
2801// decorated with offsets and strides, and if so
2802// whether std140 or std430 rules should be applied.
2803glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002804{
John Kessenichf85e8062015-12-19 13:57:10 -07002805 // has to be a block
2806 if (type.getBasicType() != glslang::EbtBlock)
2807 return glslang::ElpNone;
2808
2809 // has to be a uniform or buffer block
2810 if (type.getQualifier().storage != glslang::EvqUniform &&
2811 type.getQualifier().storage != glslang::EvqBuffer)
2812 return glslang::ElpNone;
2813
2814 // return the layout to use
2815 switch (type.getQualifier().layoutPacking) {
2816 case glslang::ElpStd140:
2817 case glslang::ElpStd430:
2818 return type.getQualifier().layoutPacking;
2819 default:
2820 return glslang::ElpNone;
2821 }
John Kessenich31ed4832015-09-09 17:51:38 -06002822}
2823
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002824// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002825int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002826{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002827 int size;
John Kessenich49987892015-12-29 17:11:44 -07002828 int stride;
2829 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002830
2831 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002832}
2833
John Kessenich49987892015-12-29 17:11:44 -07002834// 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 -07002835// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002836int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002837{
John Kessenich49987892015-12-29 17:11:44 -07002838 glslang::TType elementType;
2839 elementType.shallowCopy(matrixType);
2840 elementType.clearArraySizes();
2841
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002842 int size;
John Kessenich49987892015-12-29 17:11:44 -07002843 int stride;
2844 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2845
2846 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002847}
2848
John Kessenich5e4b1242015-08-06 22:53:06 -06002849// Given a member type of a struct, realign the current offset for it, and compute
2850// the next (not yet aligned) offset for the next member, which will get aligned
2851// on the next call.
2852// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2853// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2854// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002855void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002856 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002857{
2858 // this will get a positive value when deemed necessary
2859 nextOffset = -1;
2860
John Kessenich5e4b1242015-08-06 22:53:06 -06002861 // override anything in currentOffset with user-set offset
2862 if (memberType.getQualifier().hasOffset())
2863 currentOffset = memberType.getQualifier().layoutOffset;
2864
2865 // It could be that current linker usage in glslang updated all the layoutOffset,
2866 // in which case the following code does not matter. But, that's not quite right
2867 // once cross-compilation unit GLSL validation is done, as the original user
2868 // settings are needed in layoutOffset, and then the following will come into play.
2869
John Kessenichf85e8062015-12-19 13:57:10 -07002870 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002871 if (! memberType.getQualifier().hasOffset())
2872 currentOffset = -1;
2873
2874 return;
2875 }
2876
John Kessenichf85e8062015-12-19 13:57:10 -07002877 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002878 if (currentOffset < 0)
2879 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002880
John Kessenich5e4b1242015-08-06 22:53:06 -06002881 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2882 // but possibly not yet correctly aligned.
2883
2884 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002885 int dummyStride;
2886 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002887
2888 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002889 // TODO: make this consistent in early phases of code:
2890 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2891 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2892 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002893 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002894 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002895 int dummySize;
2896 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2897 if (componentAlignment <= 4)
2898 memberAlignment = componentAlignment;
2899 }
2900
2901 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002902 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002903
2904 // Bump up to vec4 if there is a bad straddle
2905 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2906 glslang::RoundToPow2(currentOffset, 16);
2907
John Kessenich5e4b1242015-08-06 22:53:06 -06002908 nextOffset = currentOffset + memberSize;
2909}
2910
David Netoa901ffe2016-06-08 14:11:40 +01002911void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002912{
David Netoa901ffe2016-06-08 14:11:40 +01002913 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2914 switch (glslangBuiltIn)
2915 {
2916 case glslang::EbvClipDistance:
2917 case glslang::EbvCullDistance:
2918 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002919#ifdef NV_EXTENSIONS
2920 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002921 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002922 case glslang::EbvViewportMaskNV:
2923 case glslang::EbvSecondaryPositionNV:
2924 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002925 case glslang::EbvPositionPerViewNV:
2926 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002927#endif
David Netoa901ffe2016-06-08 14:11:40 +01002928 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2929 // Alternately, we could just call this for any glslang built-in, since the
2930 // capability already guards against duplicates.
2931 TranslateBuiltInDecoration(glslangBuiltIn, false);
2932 break;
2933 default:
2934 // Capabilities were already generated when the struct was declared.
2935 break;
2936 }
John Kessenichebb50532016-05-16 19:22:05 -06002937}
2938
John Kessenich6fccb3c2016-09-19 16:01:41 -06002939bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002940{
John Kessenicheee9d532016-09-19 18:09:30 -06002941 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002942}
2943
2944// Make all the functions, skeletally, without actually visiting their bodies.
2945void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2946{
John Kessenichfad62972017-07-18 02:35:46 -06002947 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2948 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2949 if (paramPrecision != spv::NoPrecision)
2950 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002951 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002952 };
2953
John Kessenich140f3df2015-06-26 16:58:36 -06002954 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2955 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002956 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002957 continue;
2958
2959 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002960 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002961 //
qining25262b32016-05-06 17:25:16 -04002962 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002963 // function. What it is an address of varies:
2964 //
John Kessenich4bf71552016-09-02 11:20:21 -06002965 // - "in" parameters not marked as "const" can be written to without modifying the calling
2966 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002967 //
2968 // - "const in" parameters can just be the r-value, as no writes need occur.
2969 //
John Kessenich4bf71552016-09-02 11:20:21 -06002970 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2971 // 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 -06002972
2973 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002974 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002975 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2976
John Kessenichfad62972017-07-18 02:35:46 -06002977 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2978 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002979
John Kessenichfad62972017-07-18 02:35:46 -06002980 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06002981 for (int p = 0; p < (int)parameters.size(); ++p) {
2982 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2983 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002984 // can we pass by reference?
2985 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002986 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002987 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002988 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002989 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002990 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002991 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2992 else
John Kessenich4bf71552016-09-02 11:20:21 -06002993 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06002994 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06002995 paramTypes.push_back(typeId);
2996 }
2997
2998 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002999 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3000 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003001 glslFunction->getName().c_str(), paramTypes,
3002 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003003 if (implicitThis)
3004 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003005
3006 // Track function to emit/call later
3007 functionMap[glslFunction->getName().c_str()] = function;
3008
3009 // Set the parameter id's
3010 for (int p = 0; p < (int)parameters.size(); ++p) {
3011 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3012 // give a name too
3013 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3014 }
3015 }
3016}
3017
3018// Process all the initializers, while skipping the functions and link objects
3019void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3020{
3021 builder.setBuildPoint(shaderEntry->getLastBlock());
3022 for (int i = 0; i < (int)initializers.size(); ++i) {
3023 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3024 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3025
3026 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003027 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003028 initializer->traverse(this);
3029 }
3030 }
3031}
3032
3033// Process all the functions, while skipping initializers.
3034void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3035{
3036 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3037 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003038 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003039 node->traverse(this);
3040 }
3041}
3042
3043void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3044{
qining25262b32016-05-06 17:25:16 -04003045 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003046 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003047 currentFunction = functionMap[node->getName().c_str()];
3048 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003049 builder.setBuildPoint(functionBlock);
3050}
3051
Rex Xu04db3f52015-09-16 11:44:02 +08003052void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003053{
Rex Xufc618912015-09-09 16:42:49 +08003054 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003055
3056 glslang::TSampler sampler = {};
3057 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003058 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003059 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3060 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3061 }
3062
John Kessenich140f3df2015-06-26 16:58:36 -06003063 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3064 builder.clearAccessChain();
3065 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003066
3067 // Special case l-value operands
3068 bool lvalue = false;
3069 switch (node.getOp()) {
3070 case glslang::EOpImageAtomicAdd:
3071 case glslang::EOpImageAtomicMin:
3072 case glslang::EOpImageAtomicMax:
3073 case glslang::EOpImageAtomicAnd:
3074 case glslang::EOpImageAtomicOr:
3075 case glslang::EOpImageAtomicXor:
3076 case glslang::EOpImageAtomicExchange:
3077 case glslang::EOpImageAtomicCompSwap:
3078 if (i == 0)
3079 lvalue = true;
3080 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003081 case glslang::EOpSparseImageLoad:
3082 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3083 lvalue = true;
3084 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003085 case glslang::EOpSparseTexture:
3086 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3087 lvalue = true;
3088 break;
3089 case glslang::EOpSparseTextureClamp:
3090 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3091 lvalue = true;
3092 break;
3093 case glslang::EOpSparseTextureLod:
3094 case glslang::EOpSparseTextureOffset:
3095 if (i == 3)
3096 lvalue = true;
3097 break;
3098 case glslang::EOpSparseTextureFetch:
3099 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3100 lvalue = true;
3101 break;
3102 case glslang::EOpSparseTextureFetchOffset:
3103 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3104 lvalue = true;
3105 break;
3106 case glslang::EOpSparseTextureLodOffset:
3107 case glslang::EOpSparseTextureGrad:
3108 case glslang::EOpSparseTextureOffsetClamp:
3109 if (i == 4)
3110 lvalue = true;
3111 break;
3112 case glslang::EOpSparseTextureGradOffset:
3113 case glslang::EOpSparseTextureGradClamp:
3114 if (i == 5)
3115 lvalue = true;
3116 break;
3117 case glslang::EOpSparseTextureGradOffsetClamp:
3118 if (i == 6)
3119 lvalue = true;
3120 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003121 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003122 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3123 lvalue = true;
3124 break;
3125 case glslang::EOpSparseTextureGatherOffset:
3126 case glslang::EOpSparseTextureGatherOffsets:
3127 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3128 lvalue = true;
3129 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003130#ifdef AMD_EXTENSIONS
3131 case glslang::EOpSparseTextureGatherLod:
3132 if (i == 3)
3133 lvalue = true;
3134 break;
3135 case glslang::EOpSparseTextureGatherLodOffset:
3136 case glslang::EOpSparseTextureGatherLodOffsets:
3137 if (i == 4)
3138 lvalue = true;
3139 break;
3140#endif
Rex Xufc618912015-09-09 16:42:49 +08003141 default:
3142 break;
3143 }
3144
Rex Xu6b86d492015-09-16 17:48:22 +08003145 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003146 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003147 else
John Kessenich32cfd492016-02-02 12:37:46 -07003148 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003149 }
3150}
3151
John Kessenichfc51d282015-08-19 13:34:18 -06003152void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003153{
John Kessenichfc51d282015-08-19 13:34:18 -06003154 builder.clearAccessChain();
3155 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003156 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003157}
John Kessenich140f3df2015-06-26 16:58:36 -06003158
John Kessenichfc51d282015-08-19 13:34:18 -06003159spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3160{
John Kesseniche485c7a2017-05-31 18:50:53 -06003161 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003162 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003163
3164 builder.setLine(node->getLoc().line);
3165
John Kessenich8c8505c2016-07-26 12:50:38 -06003166 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003167
John Kessenichfc51d282015-08-19 13:34:18 -06003168 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003169 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3170 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3171 std::vector<spv::Id> arguments;
3172 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003173 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003174 else
3175 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003176 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003177
3178 spv::Builder::TextureParameters params = { };
3179 params.sampler = arguments[0];
3180
Rex Xu04db3f52015-09-16 11:44:02 +08003181 glslang::TCrackedTextureOp cracked;
3182 node->crackTexture(sampler, cracked);
3183
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003184 const bool isUnsignedResult =
3185 node->getType().getBasicType() == glslang::EbtUint64 ||
3186 node->getType().getBasicType() == glslang::EbtUint;
3187
John Kessenichfc51d282015-08-19 13:34:18 -06003188 // Check for queries
3189 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003190 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3191 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003192 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003193
John Kessenichfc51d282015-08-19 13:34:18 -06003194 switch (node->getOp()) {
3195 case glslang::EOpImageQuerySize:
3196 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003197 if (arguments.size() > 1) {
3198 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003199 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003200 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003201 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003202 case glslang::EOpImageQuerySamples:
3203 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003204 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003205 case glslang::EOpTextureQueryLod:
3206 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003207 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003208 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003209 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003210 case glslang::EOpSparseTexelsResident:
3211 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003212 default:
3213 assert(0);
3214 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003215 }
John Kessenich140f3df2015-06-26 16:58:36 -06003216 }
3217
Rex Xufc618912015-09-09 16:42:49 +08003218 // Check for image functions other than queries
3219 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003220 std::vector<spv::Id> operands;
3221 auto opIt = arguments.begin();
3222 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003223
3224 // Handle subpass operations
3225 // TODO: GLSL should change to have the "MS" only on the type rather than the
3226 // built-in function.
3227 if (cracked.subpass) {
3228 // add on the (0,0) coordinate
3229 spv::Id zero = builder.makeIntConstant(0);
3230 std::vector<spv::Id> comps;
3231 comps.push_back(zero);
3232 comps.push_back(zero);
3233 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3234 if (sampler.ms) {
3235 operands.push_back(spv::ImageOperandsSampleMask);
3236 operands.push_back(*(opIt++));
3237 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003238 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003239 }
3240
John Kessenich56bab042015-09-16 10:54:31 -06003241 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003242 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003243 if (sampler.ms) {
3244 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003245 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003246 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003247 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3248 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003249 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003250 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003251 if (sampler.ms) {
3252 operands.push_back(*(opIt + 1));
3253 operands.push_back(spv::ImageOperandsSampleMask);
3254 operands.push_back(*opIt);
3255 } else
3256 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003257 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003258 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3259 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003260 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003261 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3262 builder.addCapability(spv::CapabilitySparseResidency);
3263 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3264 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3265
3266 if (sampler.ms) {
3267 operands.push_back(spv::ImageOperandsSampleMask);
3268 operands.push_back(*opIt++);
3269 }
3270
3271 // Create the return type that was a special structure
3272 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003273 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003274 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3275 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3276
3277 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3278
3279 // Decode the return type
3280 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3281 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003282 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003283 // Process image atomic operations
3284
3285 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3286 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003287 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003288
John Kessenich8c8505c2016-07-26 12:50:38 -06003289 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003290 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003291
3292 std::vector<spv::Id> operands;
3293 operands.push_back(pointer);
3294 for (; opIt != arguments.end(); ++opIt)
3295 operands.push_back(*opIt);
3296
John Kessenich8c8505c2016-07-26 12:50:38 -06003297 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003298 }
3299 }
3300
3301 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003302 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003303 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3304
John Kessenichfc51d282015-08-19 13:34:18 -06003305 // check for bias argument
3306 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003307#ifdef AMD_EXTENSIONS
3308 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3309#else
Rex Xu71519fe2015-11-11 15:35:47 +08003310 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003311#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003312 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003313#ifdef AMD_EXTENSIONS
3314 if (cracked.gather)
3315 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3316#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003317 if (cracked.offset)
3318 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003319#ifdef AMD_EXTENSIONS
3320 else if (cracked.offsets)
3321 ++nonBiasArgCount;
3322#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003323 if (cracked.grad)
3324 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003325 if (cracked.lodClamp)
3326 ++nonBiasArgCount;
3327 if (sparse)
3328 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003329
3330 if ((int)arguments.size() > nonBiasArgCount)
3331 bias = true;
3332 }
3333
John Kessenicha5c33d62016-06-02 23:45:21 -06003334 // See if the sampler param should really be just the SPV image part
3335 if (cracked.fetch) {
3336 // a fetch needs to have the image extracted first
3337 if (builder.isSampledImage(params.sampler))
3338 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3339 }
3340
Rex Xu225e0fc2016-11-17 17:47:59 +08003341#ifdef AMD_EXTENSIONS
3342 if (cracked.gather) {
3343 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3344 if (bias || cracked.lod ||
3345 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3346 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003347 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003348 }
3349 }
3350#endif
3351
John Kessenichfc51d282015-08-19 13:34:18 -06003352 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003353
John Kessenichfc51d282015-08-19 13:34:18 -06003354 params.coords = arguments[1];
3355 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003356 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003357
3358 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003359 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003360 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003361 ++extraArgs;
3362 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003363 params.Dref = arguments[2];
3364 ++extraArgs;
3365 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003366 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003367 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003368 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003369 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003370 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003371 dRefComp = builder.getNumComponents(params.coords) - 1;
3372 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003373 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3374 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003375
3376 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003377 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003378 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003379 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003380 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3381 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3382 noImplicitLod = true;
3383 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003384
3385 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003386 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003387 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003388 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003389 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003390
3391 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003392 if (cracked.grad) {
3393 params.gradX = arguments[2 + extraArgs];
3394 params.gradY = arguments[3 + extraArgs];
3395 extraArgs += 2;
3396 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003397
3398 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003399 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003400 params.offset = arguments[2 + extraArgs];
3401 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003402 } else if (cracked.offsets) {
3403 params.offsets = arguments[2 + extraArgs];
3404 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003405 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003406
3407 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003408 if (cracked.lodClamp) {
3409 params.lodClamp = arguments[2 + extraArgs];
3410 ++extraArgs;
3411 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003412
3413 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003414 if (sparse) {
3415 params.texelOut = arguments[2 + extraArgs];
3416 ++extraArgs;
3417 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003418
John Kessenich76d4dfc2016-06-16 12:43:23 -06003419 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003420 if (cracked.gather && ! sampler.shadow) {
3421 // default component is 0, if missing, otherwise an argument
3422 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003423 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003424 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003425 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003426 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003427 }
3428
3429 // bias
3430 if (bias) {
3431 params.bias = arguments[2 + extraArgs];
3432 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003433 }
John Kessenichfc51d282015-08-19 13:34:18 -06003434
John Kessenich65336482016-06-16 14:06:26 -06003435 // projective component (might not to move)
3436 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3437 // are divided by the last component of P."
3438 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3439 // unused components will appear after all used components."
3440 if (cracked.proj) {
3441 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3442 int projTargetComp;
3443 switch (sampler.dim) {
3444 case glslang::Esd1D: projTargetComp = 1; break;
3445 case glslang::Esd2D: projTargetComp = 2; break;
3446 case glslang::EsdRect: projTargetComp = 2; break;
3447 default: projTargetComp = projSourceComp; break;
3448 }
3449 // copy the projective coordinate if we have to
3450 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003451 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003452 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3453 projSourceComp);
3454 params.coords = builder.createCompositeInsert(projComp, params.coords,
3455 builder.getTypeId(params.coords), projTargetComp);
3456 }
3457 }
3458
John Kessenich8c8505c2016-07-26 12:50:38 -06003459 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003460}
3461
3462spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3463{
3464 // Grab the function's pointer from the previously created function
3465 spv::Function* function = functionMap[node->getName().c_str()];
3466 if (! function)
3467 return 0;
3468
3469 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3470 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3471
3472 // See comments in makeFunctions() for details about the semantics for parameter passing.
3473 //
3474 // These imply we need a four step process:
3475 // 1. Evaluate the arguments
3476 // 2. Allocate and make copies of in, out, and inout arguments
3477 // 3. Make the call
3478 // 4. Copy back the results
3479
3480 // 1. Evaluate the arguments
3481 std::vector<spv::Builder::AccessChain> lValues;
3482 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003483 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003484 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003485 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003486 // build l-value
3487 builder.clearAccessChain();
3488 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003489 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003490 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003491 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003492 // save l-value
3493 lValues.push_back(builder.getAccessChain());
3494 } else {
3495 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003496 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003497 }
3498 }
3499
3500 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3501 // copy the original into that space.
3502 //
3503 // Also, build up the list of actual arguments to pass in for the call
3504 int lValueCount = 0;
3505 int rValueCount = 0;
3506 std::vector<spv::Id> spvArgs;
3507 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003508 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003509 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003510 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003511 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3512 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003513 builder.setAccessChain(lValues[lValueCount]);
3514 arg = builder.accessChainGetLValue();
3515 ++lValueCount;
3516 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003517 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003518 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3519 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3520 // need to copy the input into output space
3521 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003522 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003523 builder.clearAccessChain();
3524 builder.setAccessChainLValue(arg);
3525 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003526 }
3527 ++lValueCount;
3528 } else {
3529 arg = rValues[rValueCount];
3530 ++rValueCount;
3531 }
3532 spvArgs.push_back(arg);
3533 }
3534
3535 // 3. Make the call.
3536 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003537 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003538
3539 // 4. Copy back out an "out" arguments.
3540 lValueCount = 0;
3541 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003542 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003543 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3544 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3545 spv::Id copy = builder.createLoad(spvArgs[a]);
3546 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003547 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003548 }
3549 ++lValueCount;
3550 }
3551 }
3552
3553 return result;
3554}
3555
3556// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003557spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3558 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003559 spv::Id typeId, spv::Id left, spv::Id right,
3560 glslang::TBasicType typeProxy, bool reduceComparison)
3561{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003562#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003563 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003564 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3565#else
Rex Xucabbb782017-03-24 13:41:14 +08003566 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003567 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003568#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003569 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003570
3571 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003572 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003573 bool comparison = false;
3574
3575 switch (op) {
3576 case glslang::EOpAdd:
3577 case glslang::EOpAddAssign:
3578 if (isFloat)
3579 binOp = spv::OpFAdd;
3580 else
3581 binOp = spv::OpIAdd;
3582 break;
3583 case glslang::EOpSub:
3584 case glslang::EOpSubAssign:
3585 if (isFloat)
3586 binOp = spv::OpFSub;
3587 else
3588 binOp = spv::OpISub;
3589 break;
3590 case glslang::EOpMul:
3591 case glslang::EOpMulAssign:
3592 if (isFloat)
3593 binOp = spv::OpFMul;
3594 else
3595 binOp = spv::OpIMul;
3596 break;
3597 case glslang::EOpVectorTimesScalar:
3598 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003599 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003600 if (builder.isVector(right))
3601 std::swap(left, right);
3602 assert(builder.isScalar(right));
3603 needMatchingVectors = false;
3604 binOp = spv::OpVectorTimesScalar;
3605 } else
3606 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003607 break;
3608 case glslang::EOpVectorTimesMatrix:
3609 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003610 binOp = spv::OpVectorTimesMatrix;
3611 break;
3612 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003613 binOp = spv::OpMatrixTimesVector;
3614 break;
3615 case glslang::EOpMatrixTimesScalar:
3616 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003617 binOp = spv::OpMatrixTimesScalar;
3618 break;
3619 case glslang::EOpMatrixTimesMatrix:
3620 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003621 binOp = spv::OpMatrixTimesMatrix;
3622 break;
3623 case glslang::EOpOuterProduct:
3624 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003625 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003626 break;
3627
3628 case glslang::EOpDiv:
3629 case glslang::EOpDivAssign:
3630 if (isFloat)
3631 binOp = spv::OpFDiv;
3632 else if (isUnsigned)
3633 binOp = spv::OpUDiv;
3634 else
3635 binOp = spv::OpSDiv;
3636 break;
3637 case glslang::EOpMod:
3638 case glslang::EOpModAssign:
3639 if (isFloat)
3640 binOp = spv::OpFMod;
3641 else if (isUnsigned)
3642 binOp = spv::OpUMod;
3643 else
3644 binOp = spv::OpSMod;
3645 break;
3646 case glslang::EOpRightShift:
3647 case glslang::EOpRightShiftAssign:
3648 if (isUnsigned)
3649 binOp = spv::OpShiftRightLogical;
3650 else
3651 binOp = spv::OpShiftRightArithmetic;
3652 break;
3653 case glslang::EOpLeftShift:
3654 case glslang::EOpLeftShiftAssign:
3655 binOp = spv::OpShiftLeftLogical;
3656 break;
3657 case glslang::EOpAnd:
3658 case glslang::EOpAndAssign:
3659 binOp = spv::OpBitwiseAnd;
3660 break;
3661 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003662 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003663 binOp = spv::OpLogicalAnd;
3664 break;
3665 case glslang::EOpInclusiveOr:
3666 case glslang::EOpInclusiveOrAssign:
3667 binOp = spv::OpBitwiseOr;
3668 break;
3669 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003670 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003671 binOp = spv::OpLogicalOr;
3672 break;
3673 case glslang::EOpExclusiveOr:
3674 case glslang::EOpExclusiveOrAssign:
3675 binOp = spv::OpBitwiseXor;
3676 break;
3677 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003678 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003679 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003680 break;
3681
3682 case glslang::EOpLessThan:
3683 case glslang::EOpGreaterThan:
3684 case glslang::EOpLessThanEqual:
3685 case glslang::EOpGreaterThanEqual:
3686 case glslang::EOpEqual:
3687 case glslang::EOpNotEqual:
3688 case glslang::EOpVectorEqual:
3689 case glslang::EOpVectorNotEqual:
3690 comparison = true;
3691 break;
3692 default:
3693 break;
3694 }
3695
John Kessenich7c1aa102015-10-15 13:29:11 -06003696 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003697 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003698 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003699 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003700 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003701
3702 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003703 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003704 builder.promoteScalar(precision, left, right);
3705
qining25262b32016-05-06 17:25:16 -04003706 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3707 addDecoration(result, noContraction);
3708 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003709 }
3710
3711 if (! comparison)
3712 return 0;
3713
John Kessenich7c1aa102015-10-15 13:29:11 -06003714 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003715
John Kessenich4583b612016-08-07 19:14:22 -06003716 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3717 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003718 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003719
3720 switch (op) {
3721 case glslang::EOpLessThan:
3722 if (isFloat)
3723 binOp = spv::OpFOrdLessThan;
3724 else if (isUnsigned)
3725 binOp = spv::OpULessThan;
3726 else
3727 binOp = spv::OpSLessThan;
3728 break;
3729 case glslang::EOpGreaterThan:
3730 if (isFloat)
3731 binOp = spv::OpFOrdGreaterThan;
3732 else if (isUnsigned)
3733 binOp = spv::OpUGreaterThan;
3734 else
3735 binOp = spv::OpSGreaterThan;
3736 break;
3737 case glslang::EOpLessThanEqual:
3738 if (isFloat)
3739 binOp = spv::OpFOrdLessThanEqual;
3740 else if (isUnsigned)
3741 binOp = spv::OpULessThanEqual;
3742 else
3743 binOp = spv::OpSLessThanEqual;
3744 break;
3745 case glslang::EOpGreaterThanEqual:
3746 if (isFloat)
3747 binOp = spv::OpFOrdGreaterThanEqual;
3748 else if (isUnsigned)
3749 binOp = spv::OpUGreaterThanEqual;
3750 else
3751 binOp = spv::OpSGreaterThanEqual;
3752 break;
3753 case glslang::EOpEqual:
3754 case glslang::EOpVectorEqual:
3755 if (isFloat)
3756 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003757 else if (isBool)
3758 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003759 else
3760 binOp = spv::OpIEqual;
3761 break;
3762 case glslang::EOpNotEqual:
3763 case glslang::EOpVectorNotEqual:
3764 if (isFloat)
3765 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003766 else if (isBool)
3767 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003768 else
3769 binOp = spv::OpINotEqual;
3770 break;
3771 default:
3772 break;
3773 }
3774
qining25262b32016-05-06 17:25:16 -04003775 if (binOp != spv::OpNop) {
3776 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3777 addDecoration(result, noContraction);
3778 return builder.setPrecision(result, precision);
3779 }
John Kessenich140f3df2015-06-26 16:58:36 -06003780
3781 return 0;
3782}
3783
John Kessenich04bb8a02015-12-12 12:28:14 -07003784//
3785// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3786// These can be any of:
3787//
3788// matrix * scalar
3789// scalar * matrix
3790// matrix * matrix linear algebraic
3791// matrix * vector
3792// vector * matrix
3793// matrix * matrix componentwise
3794// matrix op matrix op in {+, -, /}
3795// matrix op scalar op in {+, -, /}
3796// scalar op matrix op in {+, -, /}
3797//
qining25262b32016-05-06 17:25:16 -04003798spv::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 -07003799{
3800 bool firstClass = true;
3801
3802 // First, handle first-class matrix operations (* and matrix/scalar)
3803 switch (op) {
3804 case spv::OpFDiv:
3805 if (builder.isMatrix(left) && builder.isScalar(right)) {
3806 // turn matrix / scalar into a multiply...
3807 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3808 op = spv::OpMatrixTimesScalar;
3809 } else
3810 firstClass = false;
3811 break;
3812 case spv::OpMatrixTimesScalar:
3813 if (builder.isMatrix(right))
3814 std::swap(left, right);
3815 assert(builder.isScalar(right));
3816 break;
3817 case spv::OpVectorTimesMatrix:
3818 assert(builder.isVector(left));
3819 assert(builder.isMatrix(right));
3820 break;
3821 case spv::OpMatrixTimesVector:
3822 assert(builder.isMatrix(left));
3823 assert(builder.isVector(right));
3824 break;
3825 case spv::OpMatrixTimesMatrix:
3826 assert(builder.isMatrix(left));
3827 assert(builder.isMatrix(right));
3828 break;
3829 default:
3830 firstClass = false;
3831 break;
3832 }
3833
qining25262b32016-05-06 17:25:16 -04003834 if (firstClass) {
3835 spv::Id result = builder.createBinOp(op, typeId, left, right);
3836 addDecoration(result, noContraction);
3837 return builder.setPrecision(result, precision);
3838 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003839
LoopDawg592860c2016-06-09 08:57:35 -06003840 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003841 // The result type of all of them is the same type as the (a) matrix operand.
3842 // The algorithm is to:
3843 // - break the matrix(es) into vectors
3844 // - smear any scalar to a vector
3845 // - do vector operations
3846 // - make a matrix out the vector results
3847 switch (op) {
3848 case spv::OpFAdd:
3849 case spv::OpFSub:
3850 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003851 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003852 case spv::OpFMul:
3853 {
3854 // one time set up...
3855 bool leftMat = builder.isMatrix(left);
3856 bool rightMat = builder.isMatrix(right);
3857 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3858 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3859 spv::Id scalarType = builder.getScalarTypeId(typeId);
3860 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3861 std::vector<spv::Id> results;
3862 spv::Id smearVec = spv::NoResult;
3863 if (builder.isScalar(left))
3864 smearVec = builder.smearScalar(precision, left, vecType);
3865 else if (builder.isScalar(right))
3866 smearVec = builder.smearScalar(precision, right, vecType);
3867
3868 // do each vector op
3869 for (unsigned int c = 0; c < numCols; ++c) {
3870 std::vector<unsigned int> indexes;
3871 indexes.push_back(c);
3872 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3873 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003874 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3875 addDecoration(result, noContraction);
3876 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003877 }
3878
3879 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003880 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003881 }
3882 default:
3883 assert(0);
3884 return spv::NoResult;
3885 }
3886}
3887
qining25262b32016-05-06 17:25:16 -04003888spv::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 -06003889{
3890 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003891 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003892 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003893#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003894 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003895 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3896#else
Rex Xucabbb782017-03-24 13:41:14 +08003897 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003898 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003899#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003900
3901 switch (op) {
3902 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003903 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003904 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003905 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003906 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003907 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003908 unaryOp = spv::OpSNegate;
3909 break;
3910
3911 case glslang::EOpLogicalNot:
3912 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003913 unaryOp = spv::OpLogicalNot;
3914 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003915 case glslang::EOpBitwiseNot:
3916 unaryOp = spv::OpNot;
3917 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003918
John Kessenich140f3df2015-06-26 16:58:36 -06003919 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003920 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003921 break;
3922 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003923 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003924 break;
3925 case glslang::EOpTranspose:
3926 unaryOp = spv::OpTranspose;
3927 break;
3928
3929 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003930 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003931 break;
3932 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003933 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003934 break;
3935 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003936 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003937 break;
3938 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003939 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003940 break;
3941 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003942 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003943 break;
3944 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003945 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003946 break;
3947 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003948 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003949 break;
3950 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003951 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003952 break;
3953
3954 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003955 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003956 break;
3957 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003958 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003959 break;
3960 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003961 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003962 break;
3963 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003964 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003965 break;
3966 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003967 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003968 break;
3969 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003970 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003971 break;
3972
3973 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003974 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003975 break;
3976 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003977 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003978 break;
3979
3980 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003981 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003982 break;
3983 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003984 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003985 break;
3986 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003987 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003988 break;
3989 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003990 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003991 break;
3992 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003993 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003994 break;
3995 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003996 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003997 break;
3998
3999 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004000 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004001 break;
4002 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004003 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004004 break;
4005 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004006 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004007 break;
4008 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004009 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004010 break;
4011 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004012 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004013 break;
4014 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004015 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004016 break;
4017
4018 case glslang::EOpIsNan:
4019 unaryOp = spv::OpIsNan;
4020 break;
4021 case glslang::EOpIsInf:
4022 unaryOp = spv::OpIsInf;
4023 break;
LoopDawg592860c2016-06-09 08:57:35 -06004024 case glslang::EOpIsFinite:
4025 unaryOp = spv::OpIsFinite;
4026 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004027
Rex Xucbc426e2015-12-15 16:03:10 +08004028 case glslang::EOpFloatBitsToInt:
4029 case glslang::EOpFloatBitsToUint:
4030 case glslang::EOpIntBitsToFloat:
4031 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004032 case glslang::EOpDoubleBitsToInt64:
4033 case glslang::EOpDoubleBitsToUint64:
4034 case glslang::EOpInt64BitsToDouble:
4035 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004036#ifdef AMD_EXTENSIONS
4037 case glslang::EOpFloat16BitsToInt16:
4038 case glslang::EOpFloat16BitsToUint16:
4039 case glslang::EOpInt16BitsToFloat16:
4040 case glslang::EOpUint16BitsToFloat16:
4041#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004042 unaryOp = spv::OpBitcast;
4043 break;
4044
John Kessenich140f3df2015-06-26 16:58:36 -06004045 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004046 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004047 break;
4048 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004049 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004050 break;
4051 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004052 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004053 break;
4054 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004055 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004056 break;
4057 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004058 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004059 break;
4060 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004061 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004062 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004063 case glslang::EOpPackSnorm4x8:
4064 libCall = spv::GLSLstd450PackSnorm4x8;
4065 break;
4066 case glslang::EOpUnpackSnorm4x8:
4067 libCall = spv::GLSLstd450UnpackSnorm4x8;
4068 break;
4069 case glslang::EOpPackUnorm4x8:
4070 libCall = spv::GLSLstd450PackUnorm4x8;
4071 break;
4072 case glslang::EOpUnpackUnorm4x8:
4073 libCall = spv::GLSLstd450UnpackUnorm4x8;
4074 break;
4075 case glslang::EOpPackDouble2x32:
4076 libCall = spv::GLSLstd450PackDouble2x32;
4077 break;
4078 case glslang::EOpUnpackDouble2x32:
4079 libCall = spv::GLSLstd450UnpackDouble2x32;
4080 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004081
Rex Xu8ff43de2016-04-22 16:51:45 +08004082 case glslang::EOpPackInt2x32:
4083 case glslang::EOpUnpackInt2x32:
4084 case glslang::EOpPackUint2x32:
4085 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004086 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004087 break;
4088
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004089#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004090 case glslang::EOpPackInt2x16:
4091 case glslang::EOpUnpackInt2x16:
4092 case glslang::EOpPackUint2x16:
4093 case glslang::EOpUnpackUint2x16:
4094 case glslang::EOpPackInt4x16:
4095 case glslang::EOpUnpackInt4x16:
4096 case glslang::EOpPackUint4x16:
4097 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004098 case glslang::EOpPackFloat2x16:
4099 case glslang::EOpUnpackFloat2x16:
4100 unaryOp = spv::OpBitcast;
4101 break;
4102#endif
4103
John Kessenich140f3df2015-06-26 16:58:36 -06004104 case glslang::EOpDPdx:
4105 unaryOp = spv::OpDPdx;
4106 break;
4107 case glslang::EOpDPdy:
4108 unaryOp = spv::OpDPdy;
4109 break;
4110 case glslang::EOpFwidth:
4111 unaryOp = spv::OpFwidth;
4112 break;
4113 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004114 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004115 unaryOp = spv::OpDPdxFine;
4116 break;
4117 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004118 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004119 unaryOp = spv::OpDPdyFine;
4120 break;
4121 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004122 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004123 unaryOp = spv::OpFwidthFine;
4124 break;
4125 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004126 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004127 unaryOp = spv::OpDPdxCoarse;
4128 break;
4129 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004130 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004131 unaryOp = spv::OpDPdyCoarse;
4132 break;
4133 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004134 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004135 unaryOp = spv::OpFwidthCoarse;
4136 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004137 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004138 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004139 libCall = spv::GLSLstd450InterpolateAtCentroid;
4140 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004141 case glslang::EOpAny:
4142 unaryOp = spv::OpAny;
4143 break;
4144 case glslang::EOpAll:
4145 unaryOp = spv::OpAll;
4146 break;
4147
4148 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004149 if (isFloat)
4150 libCall = spv::GLSLstd450FAbs;
4151 else
4152 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004153 break;
4154 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004155 if (isFloat)
4156 libCall = spv::GLSLstd450FSign;
4157 else
4158 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004159 break;
4160
John Kessenichfc51d282015-08-19 13:34:18 -06004161 case glslang::EOpAtomicCounterIncrement:
4162 case glslang::EOpAtomicCounterDecrement:
4163 case glslang::EOpAtomicCounter:
4164 {
4165 // Handle all of the atomics in one place, in createAtomicOperation()
4166 std::vector<spv::Id> operands;
4167 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004168 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004169 }
4170
John Kessenichfc51d282015-08-19 13:34:18 -06004171 case glslang::EOpBitFieldReverse:
4172 unaryOp = spv::OpBitReverse;
4173 break;
4174 case glslang::EOpBitCount:
4175 unaryOp = spv::OpBitCount;
4176 break;
4177 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004178 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004179 break;
4180 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004181 if (isUnsigned)
4182 libCall = spv::GLSLstd450FindUMsb;
4183 else
4184 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004185 break;
4186
Rex Xu574ab042016-04-14 16:53:07 +08004187 case glslang::EOpBallot:
4188 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004189 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004190 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004191 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004192#ifdef AMD_EXTENSIONS
4193 case glslang::EOpMinInvocations:
4194 case glslang::EOpMaxInvocations:
4195 case glslang::EOpAddInvocations:
4196 case glslang::EOpMinInvocationsNonUniform:
4197 case glslang::EOpMaxInvocationsNonUniform:
4198 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004199 case glslang::EOpMinInvocationsInclusiveScan:
4200 case glslang::EOpMaxInvocationsInclusiveScan:
4201 case glslang::EOpAddInvocationsInclusiveScan:
4202 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4203 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4204 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4205 case glslang::EOpMinInvocationsExclusiveScan:
4206 case glslang::EOpMaxInvocationsExclusiveScan:
4207 case glslang::EOpAddInvocationsExclusiveScan:
4208 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4209 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4210 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004211#endif
Rex Xu51596642016-09-21 18:56:12 +08004212 {
4213 std::vector<spv::Id> operands;
4214 operands.push_back(operand);
4215 return createInvocationsOperation(op, typeId, operands, typeProxy);
4216 }
Rex Xu9d93a232016-05-05 12:30:44 +08004217
4218#ifdef AMD_EXTENSIONS
4219 case glslang::EOpMbcnt:
4220 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4221 libCall = spv::MbcntAMD;
4222 break;
4223
4224 case glslang::EOpCubeFaceIndex:
4225 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4226 libCall = spv::CubeFaceIndexAMD;
4227 break;
4228
4229 case glslang::EOpCubeFaceCoord:
4230 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4231 libCall = spv::CubeFaceCoordAMD;
4232 break;
4233#endif
Rex Xu338b1852016-05-05 20:38:33 +08004234
John Kessenich140f3df2015-06-26 16:58:36 -06004235 default:
4236 return 0;
4237 }
4238
4239 spv::Id id;
4240 if (libCall >= 0) {
4241 std::vector<spv::Id> args;
4242 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004243 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004244 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004245 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004246 }
John Kessenich140f3df2015-06-26 16:58:36 -06004247
qining25262b32016-05-06 17:25:16 -04004248 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004249 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004250}
4251
John Kessenich7a53f762016-01-20 11:19:27 -07004252// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004253spv::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 -07004254{
4255 // Handle unary operations vector by vector.
4256 // The result type is the same type as the original type.
4257 // The algorithm is to:
4258 // - break the matrix into vectors
4259 // - apply the operation to each vector
4260 // - make a matrix out the vector results
4261
4262 // get the types sorted out
4263 int numCols = builder.getNumColumns(operand);
4264 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004265 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4266 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004267 std::vector<spv::Id> results;
4268
4269 // do each vector op
4270 for (int c = 0; c < numCols; ++c) {
4271 std::vector<unsigned int> indexes;
4272 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004273 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4274 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4275 addDecoration(destVec, noContraction);
4276 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004277 }
4278
4279 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004280 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004281}
4282
Rex Xu73e3ce72016-04-27 18:48:17 +08004283spv::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 -06004284{
4285 spv::Op convOp = spv::OpNop;
4286 spv::Id zero = 0;
4287 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004288 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004289
4290 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4291
4292 switch (op) {
4293 case glslang::EOpConvIntToBool:
4294 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004295 case glslang::EOpConvInt64ToBool:
4296 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004297#ifdef AMD_EXTENSIONS
4298 case glslang::EOpConvInt16ToBool:
4299 case glslang::EOpConvUint16ToBool:
4300#endif
4301 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4302 zero = builder.makeUint64Constant(0);
4303#ifdef AMD_EXTENSIONS
4304 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4305 zero = builder.makeUint16Constant(0);
4306#endif
4307 else
4308 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004309 zero = makeSmearedConstant(zero, vectorSize);
4310 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4311
4312 case glslang::EOpConvFloatToBool:
4313 zero = builder.makeFloatConstant(0.0F);
4314 zero = makeSmearedConstant(zero, vectorSize);
4315 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4316
4317 case glslang::EOpConvDoubleToBool:
4318 zero = builder.makeDoubleConstant(0.0);
4319 zero = makeSmearedConstant(zero, vectorSize);
4320 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4321
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004322#ifdef AMD_EXTENSIONS
4323 case glslang::EOpConvFloat16ToBool:
4324 zero = builder.makeFloat16Constant(0.0F);
4325 zero = makeSmearedConstant(zero, vectorSize);
4326 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4327#endif
4328
John Kessenich140f3df2015-06-26 16:58:36 -06004329 case glslang::EOpConvBoolToFloat:
4330 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004331 zero = builder.makeFloatConstant(0.0F);
4332 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004333 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004334
John Kessenich140f3df2015-06-26 16:58:36 -06004335 case glslang::EOpConvBoolToDouble:
4336 convOp = spv::OpSelect;
4337 zero = builder.makeDoubleConstant(0.0);
4338 one = builder.makeDoubleConstant(1.0);
4339 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004340
4341#ifdef AMD_EXTENSIONS
4342 case glslang::EOpConvBoolToFloat16:
4343 convOp = spv::OpSelect;
4344 zero = builder.makeFloat16Constant(0.0F);
4345 one = builder.makeFloat16Constant(1.0F);
4346 break;
4347#endif
4348
John Kessenich140f3df2015-06-26 16:58:36 -06004349 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004350 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004351#ifdef AMD_EXTENSIONS
4352 case glslang::EOpConvBoolToInt16:
4353#endif
4354 if (op == glslang::EOpConvBoolToInt64)
4355 zero = builder.makeInt64Constant(0);
4356#ifdef AMD_EXTENSIONS
4357 else if (op == glslang::EOpConvBoolToInt16)
4358 zero = builder.makeInt16Constant(0);
4359#endif
4360 else
4361 zero = builder.makeIntConstant(0);
4362
4363 if (op == glslang::EOpConvBoolToInt64)
4364 one = builder.makeInt64Constant(1);
4365#ifdef AMD_EXTENSIONS
4366 else if (op == glslang::EOpConvBoolToInt16)
4367 one = builder.makeInt16Constant(1);
4368#endif
4369 else
4370 one = builder.makeIntConstant(1);
4371
John Kessenich140f3df2015-06-26 16:58:36 -06004372 convOp = spv::OpSelect;
4373 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004374
John Kessenich140f3df2015-06-26 16:58:36 -06004375 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004376 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004377#ifdef AMD_EXTENSIONS
4378 case glslang::EOpConvBoolToUint16:
4379#endif
4380 if (op == glslang::EOpConvBoolToUint64)
4381 zero = builder.makeUint64Constant(0);
4382#ifdef AMD_EXTENSIONS
4383 else if (op == glslang::EOpConvBoolToUint16)
4384 zero = builder.makeUint16Constant(0);
4385#endif
4386 else
4387 zero = builder.makeUintConstant(0);
4388
4389 if (op == glslang::EOpConvBoolToUint64)
4390 one = builder.makeUint64Constant(1);
4391#ifdef AMD_EXTENSIONS
4392 else if (op == glslang::EOpConvBoolToUint16)
4393 one = builder.makeUint16Constant(1);
4394#endif
4395 else
4396 one = builder.makeUintConstant(1);
4397
John Kessenich140f3df2015-06-26 16:58:36 -06004398 convOp = spv::OpSelect;
4399 break;
4400
4401 case glslang::EOpConvIntToFloat:
4402 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004403 case glslang::EOpConvInt64ToFloat:
4404 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004405#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004406 case glslang::EOpConvInt16ToFloat:
4407 case glslang::EOpConvInt16ToDouble:
4408 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004409 case glslang::EOpConvIntToFloat16:
4410 case glslang::EOpConvInt64ToFloat16:
4411#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004412 convOp = spv::OpConvertSToF;
4413 break;
4414
4415 case glslang::EOpConvUintToFloat:
4416 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004417 case glslang::EOpConvUint64ToFloat:
4418 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004419#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004420 case glslang::EOpConvUint16ToFloat:
4421 case glslang::EOpConvUint16ToDouble:
4422 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004423 case glslang::EOpConvUintToFloat16:
4424 case glslang::EOpConvUint64ToFloat16:
4425#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004426 convOp = spv::OpConvertUToF;
4427 break;
4428
4429 case glslang::EOpConvDoubleToFloat:
4430 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004431#ifdef AMD_EXTENSIONS
4432 case glslang::EOpConvDoubleToFloat16:
4433 case glslang::EOpConvFloat16ToDouble:
4434 case glslang::EOpConvFloatToFloat16:
4435 case glslang::EOpConvFloat16ToFloat:
4436#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004437 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004438 if (builder.isMatrixType(destType))
4439 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004440 break;
4441
4442 case glslang::EOpConvFloatToInt:
4443 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004444 case glslang::EOpConvFloatToInt64:
4445 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004446#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004447 case glslang::EOpConvFloatToInt16:
4448 case glslang::EOpConvDoubleToInt16:
4449 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004450 case glslang::EOpConvFloat16ToInt:
4451 case glslang::EOpConvFloat16ToInt64:
4452#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004453 convOp = spv::OpConvertFToS;
4454 break;
4455
4456 case glslang::EOpConvUintToInt:
4457 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004458 case glslang::EOpConvUint64ToInt64:
4459 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004460#ifdef AMD_EXTENSIONS
4461 case glslang::EOpConvUint16ToInt16:
4462 case glslang::EOpConvInt16ToUint16:
4463#endif
qininge24aa5e2016-04-07 15:40:27 -04004464 if (builder.isInSpecConstCodeGenMode()) {
4465 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004466 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4467 zero = builder.makeUint64Constant(0);
4468#ifdef AMD_EXTENSIONS
4469 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4470 zero = builder.makeUint16Constant(0);
4471#endif
4472 else
4473 zero = builder.makeUintConstant(0);
4474
qining189b2032016-04-12 23:16:20 -04004475 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004476 // Use OpIAdd, instead of OpBitcast to do the conversion when
4477 // generating for OpSpecConstantOp instruction.
4478 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4479 }
4480 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004481 convOp = spv::OpBitcast;
4482 break;
4483
4484 case glslang::EOpConvFloatToUint:
4485 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004486 case glslang::EOpConvFloatToUint64:
4487 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004488#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004489 case glslang::EOpConvFloatToUint16:
4490 case glslang::EOpConvDoubleToUint16:
4491 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004492 case glslang::EOpConvFloat16ToUint:
4493 case glslang::EOpConvFloat16ToUint64:
4494#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004495 convOp = spv::OpConvertFToU;
4496 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004497
4498 case glslang::EOpConvIntToInt64:
4499 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004500#ifdef AMD_EXTENSIONS
4501 case glslang::EOpConvIntToInt16:
4502 case glslang::EOpConvInt16ToInt:
4503 case glslang::EOpConvInt64ToInt16:
4504 case glslang::EOpConvInt16ToInt64:
4505#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004506 convOp = spv::OpSConvert;
4507 break;
4508
4509 case glslang::EOpConvUintToUint64:
4510 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004511#ifdef AMD_EXTENSIONS
4512 case glslang::EOpConvUintToUint16:
4513 case glslang::EOpConvUint16ToUint:
4514 case glslang::EOpConvUint64ToUint16:
4515 case glslang::EOpConvUint16ToUint64:
4516#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004517 convOp = spv::OpUConvert;
4518 break;
4519
4520 case glslang::EOpConvIntToUint64:
4521 case glslang::EOpConvInt64ToUint:
4522 case glslang::EOpConvUint64ToInt:
4523 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004524#ifdef AMD_EXTENSIONS
4525 case glslang::EOpConvInt16ToUint:
4526 case glslang::EOpConvUintToInt16:
4527 case glslang::EOpConvInt16ToUint64:
4528 case glslang::EOpConvUint64ToInt16:
4529 case glslang::EOpConvUint16ToInt:
4530 case glslang::EOpConvIntToUint16:
4531 case glslang::EOpConvUint16ToInt64:
4532 case glslang::EOpConvInt64ToUint16:
4533#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004534 // OpSConvert/OpUConvert + OpBitCast
4535 switch (op) {
4536 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004537#ifdef AMD_EXTENSIONS
4538 case glslang::EOpConvInt16ToUint64:
4539#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004540 convOp = spv::OpSConvert;
4541 type = builder.makeIntType(64);
4542 break;
4543 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004544#ifdef AMD_EXTENSIONS
4545 case glslang::EOpConvInt16ToUint:
4546#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004547 convOp = spv::OpSConvert;
4548 type = builder.makeIntType(32);
4549 break;
4550 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004551#ifdef AMD_EXTENSIONS
4552 case glslang::EOpConvUint16ToInt:
4553#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004554 convOp = spv::OpUConvert;
4555 type = builder.makeUintType(32);
4556 break;
4557 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004558#ifdef AMD_EXTENSIONS
4559 case glslang::EOpConvUint16ToInt64:
4560#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004561 convOp = spv::OpUConvert;
4562 type = builder.makeUintType(64);
4563 break;
Rex Xucabbb782017-03-24 13:41:14 +08004564#ifdef AMD_EXTENSIONS
4565 case glslang::EOpConvUintToInt16:
4566 case glslang::EOpConvUint64ToInt16:
4567 convOp = spv::OpUConvert;
4568 type = builder.makeUintType(16);
4569 break;
4570 case glslang::EOpConvIntToUint16:
4571 case glslang::EOpConvInt64ToUint16:
4572 convOp = spv::OpSConvert;
4573 type = builder.makeIntType(16);
4574 break;
4575#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004576 default:
4577 assert(0);
4578 break;
4579 }
4580
4581 if (vectorSize > 0)
4582 type = builder.makeVectorType(type, vectorSize);
4583
4584 operand = builder.createUnaryOp(convOp, type, operand);
4585
4586 if (builder.isInSpecConstCodeGenMode()) {
4587 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004588#ifdef AMD_EXTENSIONS
4589 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4590 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4591 zero = builder.makeUint64Constant(0);
4592 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4593 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4594 zero = builder.makeUint16Constant(0);
4595 else
4596 zero = builder.makeUintConstant(0);
4597#else
4598 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4599 zero = builder.makeUint64Constant(0);
4600 else
4601 zero = builder.makeUintConstant(0);
4602#endif
4603
Rex Xu8ff43de2016-04-22 16:51:45 +08004604 zero = makeSmearedConstant(zero, vectorSize);
4605 // Use OpIAdd, instead of OpBitcast to do the conversion when
4606 // generating for OpSpecConstantOp instruction.
4607 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4608 }
4609 // For normal run-time conversion instruction, use OpBitcast.
4610 convOp = spv::OpBitcast;
4611 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004612 default:
4613 break;
4614 }
4615
4616 spv::Id result = 0;
4617 if (convOp == spv::OpNop)
4618 return result;
4619
4620 if (convOp == spv::OpSelect) {
4621 zero = makeSmearedConstant(zero, vectorSize);
4622 one = makeSmearedConstant(one, vectorSize);
4623 result = builder.createTriOp(convOp, destType, operand, one, zero);
4624 } else
4625 result = builder.createUnaryOp(convOp, destType, operand);
4626
John Kessenich32cfd492016-02-02 12:37:46 -07004627 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004628}
4629
4630spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4631{
4632 if (vectorSize == 0)
4633 return constant;
4634
4635 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4636 std::vector<spv::Id> components;
4637 for (int c = 0; c < vectorSize; ++c)
4638 components.push_back(constant);
4639 return builder.makeCompositeConstant(vectorTypeId, components);
4640}
4641
John Kessenich426394d2015-07-23 10:22:48 -06004642// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004643spv::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 -06004644{
4645 spv::Op opCode = spv::OpNop;
4646
4647 switch (op) {
4648 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004649 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004650 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004651 opCode = spv::OpAtomicIAdd;
4652 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004653 case glslang::EOpAtomicCounterSubtract:
4654 opCode = spv::OpAtomicISub;
4655 break;
John Kessenich426394d2015-07-23 10:22:48 -06004656 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004657 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004658 case glslang::EOpAtomicCounterMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004659 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004660 break;
4661 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004662 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004663 case glslang::EOpAtomicCounterMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004664 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004665 break;
4666 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004667 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004668 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004669 opCode = spv::OpAtomicAnd;
4670 break;
4671 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004672 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004673 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004674 opCode = spv::OpAtomicOr;
4675 break;
4676 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004677 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004678 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004679 opCode = spv::OpAtomicXor;
4680 break;
4681 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004682 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004683 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004684 opCode = spv::OpAtomicExchange;
4685 break;
4686 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004687 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004688 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004689 opCode = spv::OpAtomicCompareExchange;
4690 break;
4691 case glslang::EOpAtomicCounterIncrement:
4692 opCode = spv::OpAtomicIIncrement;
4693 break;
4694 case glslang::EOpAtomicCounterDecrement:
4695 opCode = spv::OpAtomicIDecrement;
4696 break;
4697 case glslang::EOpAtomicCounter:
4698 opCode = spv::OpAtomicLoad;
4699 break;
4700 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004701 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004702 break;
4703 }
4704
4705 // Sort out the operands
4706 // - mapping from glslang -> SPV
4707 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004708 // - compare-exchange swaps the value and comparator
4709 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004710 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4711 auto opIt = operands.begin(); // walk the glslang operands
4712 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004713 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4714 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4715 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004716 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4717 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004718 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004719 spvAtomicOperands.push_back(*(opIt + 1));
4720 spvAtomicOperands.push_back(*opIt);
4721 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004722 }
John Kessenich426394d2015-07-23 10:22:48 -06004723
John Kessenich3e60a6f2015-09-14 22:45:16 -06004724 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004725 for (; opIt != operands.end(); ++opIt)
4726 spvAtomicOperands.push_back(*opIt);
4727
4728 return builder.createOp(opCode, typeId, spvAtomicOperands);
4729}
4730
John Kessenich91cef522016-05-05 16:45:40 -06004731// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004732spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004733{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004734#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004735 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004736 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004737#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004738
Rex Xu51596642016-09-21 18:56:12 +08004739 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004740 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004741 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4742
chaocf200da82016-12-20 12:44:35 -08004743 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4744 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004745 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4746 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004747 } else if (op == glslang::EOpAnyInvocation ||
4748 op == glslang::EOpAllInvocations ||
4749 op == glslang::EOpAllInvocationsEqual) {
4750 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4751 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004752 } else {
4753 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004754#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004755 if (op == glslang::EOpMinInvocationsNonUniform ||
4756 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004757 op == glslang::EOpAddInvocationsNonUniform ||
4758 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4759 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4760 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4761 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4762 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4763 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004764 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004765#endif
Rex Xu51596642016-09-21 18:56:12 +08004766
4767 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004768#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004769 switch (op) {
4770 case glslang::EOpMinInvocations:
4771 case glslang::EOpMaxInvocations:
4772 case glslang::EOpAddInvocations:
4773 case glslang::EOpMinInvocationsNonUniform:
4774 case glslang::EOpMaxInvocationsNonUniform:
4775 case glslang::EOpAddInvocationsNonUniform:
4776 groupOperation = spv::GroupOperationReduce;
4777 spvGroupOperands.push_back(groupOperation);
4778 break;
4779 case glslang::EOpMinInvocationsInclusiveScan:
4780 case glslang::EOpMaxInvocationsInclusiveScan:
4781 case glslang::EOpAddInvocationsInclusiveScan:
4782 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4783 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4784 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4785 groupOperation = spv::GroupOperationInclusiveScan;
4786 spvGroupOperands.push_back(groupOperation);
4787 break;
4788 case glslang::EOpMinInvocationsExclusiveScan:
4789 case glslang::EOpMaxInvocationsExclusiveScan:
4790 case glslang::EOpAddInvocationsExclusiveScan:
4791 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4792 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4793 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4794 groupOperation = spv::GroupOperationExclusiveScan;
4795 spvGroupOperands.push_back(groupOperation);
4796 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004797 default:
4798 break;
Rex Xu430ef402016-10-14 17:22:23 +08004799 }
Rex Xu9d93a232016-05-05 12:30:44 +08004800#endif
Rex Xu51596642016-09-21 18:56:12 +08004801 }
4802
4803 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4804 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004805
4806 switch (op) {
4807 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004808 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004809 break;
John Kessenich91cef522016-05-05 16:45:40 -06004810 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004811 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004812 break;
John Kessenich91cef522016-05-05 16:45:40 -06004813 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004814 opCode = spv::OpSubgroupAllEqualKHR;
4815 break;
Rex Xu51596642016-09-21 18:56:12 +08004816 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004817 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004818 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004819 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004820 break;
4821 case glslang::EOpReadFirstInvocation:
4822 opCode = spv::OpSubgroupFirstInvocationKHR;
4823 break;
4824 case glslang::EOpBallot:
4825 {
4826 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4827 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4828 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4829 //
4830 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4831 //
4832 spv::Id uintType = builder.makeUintType(32);
4833 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4834 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4835
4836 std::vector<spv::Id> components;
4837 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4838 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4839
4840 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4841 return builder.createUnaryOp(spv::OpBitcast, typeId,
4842 builder.createCompositeConstruct(uvec2Type, components));
4843 }
4844
Rex Xu9d93a232016-05-05 12:30:44 +08004845#ifdef AMD_EXTENSIONS
4846 case glslang::EOpMinInvocations:
4847 case glslang::EOpMaxInvocations:
4848 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004849 case glslang::EOpMinInvocationsInclusiveScan:
4850 case glslang::EOpMaxInvocationsInclusiveScan:
4851 case glslang::EOpAddInvocationsInclusiveScan:
4852 case glslang::EOpMinInvocationsExclusiveScan:
4853 case glslang::EOpMaxInvocationsExclusiveScan:
4854 case glslang::EOpAddInvocationsExclusiveScan:
4855 if (op == glslang::EOpMinInvocations ||
4856 op == glslang::EOpMinInvocationsInclusiveScan ||
4857 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004858 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004859 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004860 else {
4861 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004862 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004863 else
Rex Xu51596642016-09-21 18:56:12 +08004864 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004865 }
Rex Xu430ef402016-10-14 17:22:23 +08004866 } else if (op == glslang::EOpMaxInvocations ||
4867 op == glslang::EOpMaxInvocationsInclusiveScan ||
4868 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004869 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004870 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004871 else {
4872 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004873 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004874 else
Rex Xu51596642016-09-21 18:56:12 +08004875 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004876 }
4877 } else {
4878 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004879 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004880 else
Rex Xu51596642016-09-21 18:56:12 +08004881 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004882 }
4883
Rex Xu2bbbe062016-08-23 15:41:05 +08004884 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004885 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004886
4887 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004888 case glslang::EOpMinInvocationsNonUniform:
4889 case glslang::EOpMaxInvocationsNonUniform:
4890 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004891 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4892 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4893 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4894 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4895 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4896 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4897 if (op == glslang::EOpMinInvocationsNonUniform ||
4898 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4899 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004900 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004901 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004902 else {
4903 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004904 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004905 else
Rex Xu51596642016-09-21 18:56:12 +08004906 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004907 }
4908 }
Rex Xu430ef402016-10-14 17:22:23 +08004909 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4910 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4911 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004912 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004913 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004914 else {
4915 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004916 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004917 else
Rex Xu51596642016-09-21 18:56:12 +08004918 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004919 }
4920 }
4921 else {
4922 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004923 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004924 else
Rex Xu51596642016-09-21 18:56:12 +08004925 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004926 }
4927
Rex Xu2bbbe062016-08-23 15:41:05 +08004928 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004929 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004930
4931 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004932#endif
John Kessenich91cef522016-05-05 16:45:40 -06004933 default:
4934 logger->missingFunctionality("invocation operation");
4935 return spv::NoResult;
4936 }
Rex Xu51596642016-09-21 18:56:12 +08004937
4938 assert(opCode != spv::OpNop);
4939 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004940}
4941
Rex Xu2bbbe062016-08-23 15:41:05 +08004942// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004943spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004944{
Rex Xub7072052016-09-26 15:53:40 +08004945#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004946 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4947 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004948 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004949 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004950 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4951 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4952 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004953#else
4954 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4955 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004956 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4957 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004958#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004959
4960 // Handle group invocation operations scalar by scalar.
4961 // The result type is the same type as the original type.
4962 // The algorithm is to:
4963 // - break the vector into scalars
4964 // - apply the operation to each scalar
4965 // - make a vector out the scalar results
4966
4967 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004968 int numComponents = builder.getNumComponents(operands[0]);
4969 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004970 std::vector<spv::Id> results;
4971
4972 // do each scalar op
4973 for (int comp = 0; comp < numComponents; ++comp) {
4974 std::vector<unsigned int> indexes;
4975 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004976 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004977 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004978 if (op == spv::OpSubgroupReadInvocationKHR) {
4979 spvGroupOperands.push_back(scalar);
4980 spvGroupOperands.push_back(operands[1]);
4981 } else if (op == spv::OpGroupBroadcast) {
4982 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004983 spvGroupOperands.push_back(scalar);
4984 spvGroupOperands.push_back(operands[1]);
4985 } else {
chaocf200da82016-12-20 12:44:35 -08004986 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004987 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004988 spvGroupOperands.push_back(scalar);
4989 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004990
Rex Xub7072052016-09-26 15:53:40 +08004991 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004992 }
4993
4994 // put the pieces together
4995 return builder.createCompositeConstruct(typeId, results);
4996}
Rex Xu2bbbe062016-08-23 15:41:05 +08004997
John Kessenich5e4b1242015-08-06 22:53:06 -06004998spv::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 -06004999{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005000#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005001 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005002 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5003#else
Rex Xucabbb782017-03-24 13:41:14 +08005004 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005005 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005006#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005007
John Kessenich140f3df2015-06-26 16:58:36 -06005008 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005009 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005010 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005011 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005012 spv::Id typeId0 = 0;
5013 if (consumedOperands > 0)
5014 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005015 spv::Id typeId1 = 0;
5016 if (consumedOperands > 1)
5017 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005018 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005019
5020 switch (op) {
5021 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005022 if (isFloat)
5023 libCall = spv::GLSLstd450FMin;
5024 else if (isUnsigned)
5025 libCall = spv::GLSLstd450UMin;
5026 else
5027 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005028 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005029 break;
5030 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005031 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005032 break;
5033 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005034 if (isFloat)
5035 libCall = spv::GLSLstd450FMax;
5036 else if (isUnsigned)
5037 libCall = spv::GLSLstd450UMax;
5038 else
5039 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005040 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005041 break;
5042 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005043 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005044 break;
5045 case glslang::EOpDot:
5046 opCode = spv::OpDot;
5047 break;
5048 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005049 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005050 break;
5051
5052 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005053 if (isFloat)
5054 libCall = spv::GLSLstd450FClamp;
5055 else if (isUnsigned)
5056 libCall = spv::GLSLstd450UClamp;
5057 else
5058 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005059 builder.promoteScalar(precision, operands.front(), operands[1]);
5060 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005061 break;
5062 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005063 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5064 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005065 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005066 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005067 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005068 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005069 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005070 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005071 break;
5072 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005073 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005074 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005075 break;
5076 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005077 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005078 builder.promoteScalar(precision, operands[0], operands[2]);
5079 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005080 break;
5081
5082 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005083 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005084 break;
5085 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005086 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005087 break;
5088 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005089 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005090 break;
5091 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005092 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005093 break;
5094 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005095 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005096 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005097 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005098 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005099 libCall = spv::GLSLstd450InterpolateAtSample;
5100 break;
5101 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005102 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005103 libCall = spv::GLSLstd450InterpolateAtOffset;
5104 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005105 case glslang::EOpAddCarry:
5106 opCode = spv::OpIAddCarry;
5107 typeId = builder.makeStructResultType(typeId0, typeId0);
5108 consumedOperands = 2;
5109 break;
5110 case glslang::EOpSubBorrow:
5111 opCode = spv::OpISubBorrow;
5112 typeId = builder.makeStructResultType(typeId0, typeId0);
5113 consumedOperands = 2;
5114 break;
5115 case glslang::EOpUMulExtended:
5116 opCode = spv::OpUMulExtended;
5117 typeId = builder.makeStructResultType(typeId0, typeId0);
5118 consumedOperands = 2;
5119 break;
5120 case glslang::EOpIMulExtended:
5121 opCode = spv::OpSMulExtended;
5122 typeId = builder.makeStructResultType(typeId0, typeId0);
5123 consumedOperands = 2;
5124 break;
5125 case glslang::EOpBitfieldExtract:
5126 if (isUnsigned)
5127 opCode = spv::OpBitFieldUExtract;
5128 else
5129 opCode = spv::OpBitFieldSExtract;
5130 break;
5131 case glslang::EOpBitfieldInsert:
5132 opCode = spv::OpBitFieldInsert;
5133 break;
5134
5135 case glslang::EOpFma:
5136 libCall = spv::GLSLstd450Fma;
5137 break;
5138 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005139 {
5140 libCall = spv::GLSLstd450FrexpStruct;
5141 assert(builder.isPointerType(typeId1));
5142 typeId1 = builder.getContainedTypeId(typeId1);
5143#ifdef AMD_EXTENSIONS
5144 int width = builder.getScalarTypeWidth(typeId1);
5145#else
5146 int width = 32;
5147#endif
5148 if (builder.getNumComponents(operands[0]) == 1)
5149 frexpIntType = builder.makeIntegerType(width, true);
5150 else
5151 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5152 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5153 consumedOperands = 1;
5154 }
John Kessenich55e7d112015-11-15 21:33:39 -07005155 break;
5156 case glslang::EOpLdexp:
5157 libCall = spv::GLSLstd450Ldexp;
5158 break;
5159
Rex Xu574ab042016-04-14 16:53:07 +08005160 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005161 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005162
Rex Xu9d93a232016-05-05 12:30:44 +08005163#ifdef AMD_EXTENSIONS
5164 case glslang::EOpSwizzleInvocations:
5165 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5166 libCall = spv::SwizzleInvocationsAMD;
5167 break;
5168 case glslang::EOpSwizzleInvocationsMasked:
5169 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5170 libCall = spv::SwizzleInvocationsMaskedAMD;
5171 break;
5172 case glslang::EOpWriteInvocation:
5173 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5174 libCall = spv::WriteInvocationAMD;
5175 break;
5176
5177 case glslang::EOpMin3:
5178 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5179 if (isFloat)
5180 libCall = spv::FMin3AMD;
5181 else {
5182 if (isUnsigned)
5183 libCall = spv::UMin3AMD;
5184 else
5185 libCall = spv::SMin3AMD;
5186 }
5187 break;
5188 case glslang::EOpMax3:
5189 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5190 if (isFloat)
5191 libCall = spv::FMax3AMD;
5192 else {
5193 if (isUnsigned)
5194 libCall = spv::UMax3AMD;
5195 else
5196 libCall = spv::SMax3AMD;
5197 }
5198 break;
5199 case glslang::EOpMid3:
5200 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5201 if (isFloat)
5202 libCall = spv::FMid3AMD;
5203 else {
5204 if (isUnsigned)
5205 libCall = spv::UMid3AMD;
5206 else
5207 libCall = spv::SMid3AMD;
5208 }
5209 break;
5210
5211 case glslang::EOpInterpolateAtVertex:
5212 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5213 libCall = spv::InterpolateAtVertexAMD;
5214 break;
5215#endif
5216
John Kessenich140f3df2015-06-26 16:58:36 -06005217 default:
5218 return 0;
5219 }
5220
5221 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005222 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005223 // Use an extended instruction from the standard library.
5224 // Construct the call arguments, without modifying the original operands vector.
5225 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5226 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005227 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005228 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005229 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005230 case 0:
5231 // should all be handled by visitAggregate and createNoArgOperation
5232 assert(0);
5233 return 0;
5234 case 1:
5235 // should all be handled by createUnaryOperation
5236 assert(0);
5237 return 0;
5238 case 2:
5239 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5240 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005241 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005242 // anything 3 or over doesn't have l-value operands, so all should be consumed
5243 assert(consumedOperands == operands.size());
5244 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005245 break;
5246 }
5247 }
5248
John Kessenich55e7d112015-11-15 21:33:39 -07005249 // Decode the return types that were structures
5250 switch (op) {
5251 case glslang::EOpAddCarry:
5252 case glslang::EOpSubBorrow:
5253 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5254 id = builder.createCompositeExtract(id, typeId0, 0);
5255 break;
5256 case glslang::EOpUMulExtended:
5257 case glslang::EOpIMulExtended:
5258 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5259 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5260 break;
5261 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005262 {
5263 assert(operands.size() == 2);
5264 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5265 // "exp" is floating-point type (from HLSL intrinsic)
5266 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5267 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5268 builder.createStore(member1, operands[1]);
5269 } else
5270 // "exp" is integer type (from GLSL built-in function)
5271 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5272 id = builder.createCompositeExtract(id, typeId0, 0);
5273 }
John Kessenich55e7d112015-11-15 21:33:39 -07005274 break;
5275 default:
5276 break;
5277 }
5278
John Kessenich32cfd492016-02-02 12:37:46 -07005279 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005280}
5281
Rex Xu9d93a232016-05-05 12:30:44 +08005282// Intrinsics with no arguments (or no return value, and no precision).
5283spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005284{
5285 // TODO: get the barrier operands correct
5286
5287 switch (op) {
5288 case glslang::EOpEmitVertex:
5289 builder.createNoResultOp(spv::OpEmitVertex);
5290 return 0;
5291 case glslang::EOpEndPrimitive:
5292 builder.createNoResultOp(spv::OpEndPrimitive);
5293 return 0;
5294 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005295 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005296 return 0;
5297 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005298 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005299 return 0;
5300 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005301 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005302 return 0;
5303 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005304 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005305 return 0;
5306 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005307 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005308 return 0;
5309 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005310 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005311 return 0;
5312 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005313 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005314 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005315 case glslang::EOpAllMemoryBarrierWithGroupSync:
5316 // Control barrier with non-"None" semantic is also a memory barrier.
5317 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5318 return 0;
5319 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5320 // Control barrier with non-"None" semantic is also a memory barrier.
5321 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5322 return 0;
5323 case glslang::EOpWorkgroupMemoryBarrier:
5324 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5325 return 0;
5326 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5327 // Control barrier with non-"None" semantic is also a memory barrier.
5328 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5329 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005330#ifdef AMD_EXTENSIONS
5331 case glslang::EOpTime:
5332 {
5333 std::vector<spv::Id> args; // Dummy arguments
5334 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5335 return builder.setPrecision(id, precision);
5336 }
5337#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005338 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005339 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005340 return 0;
5341 }
5342}
5343
5344spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5345{
John Kessenich2f273362015-07-18 22:34:27 -06005346 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005347 spv::Id id;
5348 if (symbolValues.end() != iter) {
5349 id = iter->second;
5350 return id;
5351 }
5352
5353 // it was not found, create it
5354 id = createSpvVariable(symbol);
5355 symbolValues[symbol->getId()] = id;
5356
Rex Xuc884b4a2016-06-29 15:03:44 +08005357 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005358 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005359 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005360 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005361 if (symbol->getType().getQualifier().hasSpecConstantId())
5362 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005363 if (symbol->getQualifier().hasIndex())
5364 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5365 if (symbol->getQualifier().hasComponent())
5366 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5367 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005368 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005369 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005370 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005371 if (symbol->getQualifier().hasXfbBuffer())
5372 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5373 if (symbol->getQualifier().hasXfbOffset())
5374 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5375 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005376 // atomic counters use this:
5377 if (symbol->getQualifier().hasOffset())
5378 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005379 }
5380
scygan2c864272016-05-18 18:09:17 +02005381 if (symbol->getQualifier().hasLocation())
5382 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005383 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005384 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005385 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005386 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005387 }
John Kessenich140f3df2015-06-26 16:58:36 -06005388 if (symbol->getQualifier().hasSet())
5389 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005390 else if (IsDescriptorResource(symbol->getType())) {
5391 // default to 0
5392 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5393 }
John Kessenich140f3df2015-06-26 16:58:36 -06005394 if (symbol->getQualifier().hasBinding())
5395 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005396 if (symbol->getQualifier().hasAttachment())
5397 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005398 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005399 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005400 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005401 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005402 if (symbol->getQualifier().hasXfbBuffer())
5403 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5404 }
5405
Rex Xu1da878f2016-02-21 20:59:01 +08005406 if (symbol->getType().isImage()) {
5407 std::vector<spv::Decoration> memory;
5408 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5409 for (unsigned int i = 0; i < memory.size(); ++i)
5410 addDecoration(id, memory[i]);
5411 }
5412
John Kessenich140f3df2015-06-26 16:58:36 -06005413 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005414 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005415 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005416 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005417
John Kessenichecba76f2017-01-06 00:34:48 -07005418#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005419 if (builtIn == spv::BuiltInSampleMask) {
5420 spv::Decoration decoration;
5421 // GL_NV_sample_mask_override_coverage extension
5422 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005423 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005424 else
5425 decoration = (spv::Decoration)spv::DecorationMax;
5426 addDecoration(id, decoration);
5427 if (decoration != spv::DecorationMax) {
5428 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5429 }
5430 }
chaoc771d89f2017-01-13 01:10:53 -08005431 else if (builtIn == spv::BuiltInLayer) {
5432 // SPV_NV_viewport_array2 extension
5433 if (symbol->getQualifier().layoutViewportRelative)
5434 {
5435 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5436 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5437 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5438 }
5439 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5440 {
5441 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5442 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5443 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5444 }
5445 }
5446
chaoc6e5acae2016-12-20 13:28:52 -08005447 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005448 addDecoration(id, spv::DecorationPassthroughNV);
5449 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005450 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5451 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005452#endif
5453
John Kessenich140f3df2015-06-26 16:58:36 -06005454 return id;
5455}
5456
John Kessenich55e7d112015-11-15 21:33:39 -07005457// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005458void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5459{
John Kessenich4016e382016-07-15 11:53:56 -06005460 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005461 builder.addDecoration(id, dec);
5462}
5463
John Kessenich55e7d112015-11-15 21:33:39 -07005464// If 'dec' is valid, add a one-operand decoration to an object
5465void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5466{
John Kessenich4016e382016-07-15 11:53:56 -06005467 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005468 builder.addDecoration(id, dec, value);
5469}
5470
5471// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005472void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5473{
John Kessenich4016e382016-07-15 11:53:56 -06005474 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005475 builder.addMemberDecoration(id, (unsigned)member, dec);
5476}
5477
John Kessenich92187592016-02-01 13:45:25 -07005478// If 'dec' is valid, add a one-operand decoration to a struct member
5479void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5480{
John Kessenich4016e382016-07-15 11:53:56 -06005481 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005482 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5483}
5484
John Kessenich55e7d112015-11-15 21:33:39 -07005485// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005486// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005487//
5488// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5489//
5490// Recursively walk the nodes. The nodes form a tree whose leaves are
5491// regular constants, which themselves are trees that createSpvConstant()
5492// recursively walks. So, this function walks the "top" of the tree:
5493// - emit specialization constant-building instructions for specConstant
5494// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005495spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005496{
John Kessenich7cc0e282016-03-20 00:46:02 -06005497 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005498
qining4f4bb812016-04-03 23:55:17 -04005499 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005500 if (! node.getQualifier().specConstant) {
5501 // hand off to the non-spec-constant path
5502 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5503 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005504 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005505 nextConst, false);
5506 }
5507
5508 // We now know we have a specialization constant to build
5509
John Kessenichd94c0032016-05-30 19:29:40 -06005510 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005511 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5512 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5513 std::vector<spv::Id> dimConstId;
5514 for (int dim = 0; dim < 3; ++dim) {
5515 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5516 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5517 if (specConst)
5518 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5519 }
5520 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5521 }
5522
5523 // An AST node labelled as specialization constant should be a symbol node.
5524 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5525 if (auto* sn = node.getAsSymbolNode()) {
5526 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005527 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5528 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5529 // will set the builder into spec constant op instruction generating mode.
5530 sub_tree->traverse(this);
5531 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005532 } else if (auto* const_union_array = &sn->getConstArray()){
5533 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005534 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5535 builder.addName(id, sn->getName().c_str());
5536 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005537 }
5538 }
qining4f4bb812016-04-03 23:55:17 -04005539
5540 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5541 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005542 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005543 exit(1);
5544 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005545}
5546
John Kessenich140f3df2015-06-26 16:58:36 -06005547// Use 'consts' as the flattened glslang source of scalar constants to recursively
5548// build the aggregate SPIR-V constant.
5549//
5550// If there are not enough elements present in 'consts', 0 will be substituted;
5551// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5552//
qining08408382016-03-21 09:51:37 -04005553spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005554{
5555 // vector of constants for SPIR-V
5556 std::vector<spv::Id> spvConsts;
5557
5558 // Type is used for struct and array constants
5559 spv::Id typeId = convertGlslangToSpvType(glslangType);
5560
5561 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005562 glslang::TType elementType(glslangType, 0);
5563 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005564 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005565 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005566 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005567 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005568 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005569 } else if (glslangType.getStruct()) {
5570 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5571 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005572 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005573 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005574 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5575 bool zero = nextConst >= consts.size();
5576 switch (glslangType.getBasicType()) {
5577 case glslang::EbtInt:
5578 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5579 break;
5580 case glslang::EbtUint:
5581 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5582 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005583 case glslang::EbtInt64:
5584 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5585 break;
5586 case glslang::EbtUint64:
5587 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5588 break;
Rex Xucabbb782017-03-24 13:41:14 +08005589#ifdef AMD_EXTENSIONS
5590 case glslang::EbtInt16:
5591 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5592 break;
5593 case glslang::EbtUint16:
5594 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5595 break;
5596#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005597 case glslang::EbtFloat:
5598 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5599 break;
5600 case glslang::EbtDouble:
5601 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5602 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005603#ifdef AMD_EXTENSIONS
5604 case glslang::EbtFloat16:
5605 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5606 break;
5607#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005608 case glslang::EbtBool:
5609 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5610 break;
5611 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005612 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005613 break;
5614 }
5615 ++nextConst;
5616 }
5617 } else {
5618 // we have a non-aggregate (scalar) constant
5619 bool zero = nextConst >= consts.size();
5620 spv::Id scalar = 0;
5621 switch (glslangType.getBasicType()) {
5622 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005623 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005624 break;
5625 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005626 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005627 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005628 case glslang::EbtInt64:
5629 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5630 break;
5631 case glslang::EbtUint64:
5632 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5633 break;
Rex Xucabbb782017-03-24 13:41:14 +08005634#ifdef AMD_EXTENSIONS
5635 case glslang::EbtInt16:
5636 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5637 break;
5638 case glslang::EbtUint16:
5639 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5640 break;
5641#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005642 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005643 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005644 break;
5645 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005646 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005647 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005648#ifdef AMD_EXTENSIONS
5649 case glslang::EbtFloat16:
5650 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5651 break;
5652#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005653 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005654 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005655 break;
5656 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005657 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005658 break;
5659 }
5660 ++nextConst;
5661 return scalar;
5662 }
5663
5664 return builder.makeCompositeConstant(typeId, spvConsts);
5665}
5666
John Kessenich7c1aa102015-10-15 13:29:11 -06005667// Return true if the node is a constant or symbol whose reading has no
5668// non-trivial observable cost or effect.
5669bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5670{
5671 // don't know what this is
5672 if (node == nullptr)
5673 return false;
5674
5675 // a constant is safe
5676 if (node->getAsConstantUnion() != nullptr)
5677 return true;
5678
5679 // not a symbol means non-trivial
5680 if (node->getAsSymbolNode() == nullptr)
5681 return false;
5682
5683 // a symbol, depends on what's being read
5684 switch (node->getType().getQualifier().storage) {
5685 case glslang::EvqTemporary:
5686 case glslang::EvqGlobal:
5687 case glslang::EvqIn:
5688 case glslang::EvqInOut:
5689 case glslang::EvqConst:
5690 case glslang::EvqConstReadOnly:
5691 case glslang::EvqUniform:
5692 return true;
5693 default:
5694 return false;
5695 }
qining25262b32016-05-06 17:25:16 -04005696}
John Kessenich7c1aa102015-10-15 13:29:11 -06005697
5698// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005699// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005700// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005701// Return true if trivial.
5702bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5703{
5704 if (node == nullptr)
5705 return false;
5706
John Kessenich84cc15f2017-05-24 16:44:47 -06005707 // count non scalars as trivial, as well as anything coming from HLSL
5708 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005709 return true;
5710
John Kessenich7c1aa102015-10-15 13:29:11 -06005711 // symbols and constants are trivial
5712 if (isTrivialLeaf(node))
5713 return true;
5714
5715 // otherwise, it needs to be a simple operation or one or two leaf nodes
5716
5717 // not a simple operation
5718 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5719 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5720 if (binaryNode == nullptr && unaryNode == nullptr)
5721 return false;
5722
5723 // not on leaf nodes
5724 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5725 return false;
5726
5727 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5728 return false;
5729 }
5730
5731 switch (node->getAsOperator()->getOp()) {
5732 case glslang::EOpLogicalNot:
5733 case glslang::EOpConvIntToBool:
5734 case glslang::EOpConvUintToBool:
5735 case glslang::EOpConvFloatToBool:
5736 case glslang::EOpConvDoubleToBool:
5737 case glslang::EOpEqual:
5738 case glslang::EOpNotEqual:
5739 case glslang::EOpLessThan:
5740 case glslang::EOpGreaterThan:
5741 case glslang::EOpLessThanEqual:
5742 case glslang::EOpGreaterThanEqual:
5743 case glslang::EOpIndexDirect:
5744 case glslang::EOpIndexDirectStruct:
5745 case glslang::EOpLogicalXor:
5746 case glslang::EOpAny:
5747 case glslang::EOpAll:
5748 return true;
5749 default:
5750 return false;
5751 }
5752}
5753
5754// Emit short-circuiting code, where 'right' is never evaluated unless
5755// the left side is true (for &&) or false (for ||).
5756spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5757{
5758 spv::Id boolTypeId = builder.makeBoolType();
5759
5760 // emit left operand
5761 builder.clearAccessChain();
5762 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005763 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005764
5765 // Operands to accumulate OpPhi operands
5766 std::vector<spv::Id> phiOperands;
5767 // accumulate left operand's phi information
5768 phiOperands.push_back(leftId);
5769 phiOperands.push_back(builder.getBuildPoint()->getId());
5770
5771 // Make the two kinds of operation symmetric with a "!"
5772 // || => emit "if (! left) result = right"
5773 // && => emit "if ( left) result = right"
5774 //
5775 // TODO: this runtime "not" for || could be avoided by adding functionality
5776 // to 'builder' to have an "else" without an "then"
5777 if (op == glslang::EOpLogicalOr)
5778 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5779
5780 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005781 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005782
5783 // emit right operand as the "then" part of the "if"
5784 builder.clearAccessChain();
5785 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005786 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005787
5788 // accumulate left operand's phi information
5789 phiOperands.push_back(rightId);
5790 phiOperands.push_back(builder.getBuildPoint()->getId());
5791
5792 // finish the "if"
5793 ifBuilder.makeEndIf();
5794
5795 // phi together the two results
5796 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5797}
5798
Rex Xu9d93a232016-05-05 12:30:44 +08005799// Return type Id of the imported set of extended instructions corresponds to the name.
5800// Import this set if it has not been imported yet.
5801spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5802{
5803 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5804 return extBuiltinMap[name];
5805 else {
Rex Xu51596642016-09-21 18:56:12 +08005806 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005807 spv::Id extBuiltins = builder.import(name);
5808 extBuiltinMap[name] = extBuiltins;
5809 return extBuiltins;
5810 }
5811}
5812
John Kessenich140f3df2015-06-26 16:58:36 -06005813}; // end anonymous namespace
5814
5815namespace glslang {
5816
John Kessenich68d78fd2015-07-12 19:28:10 -06005817void GetSpirvVersion(std::string& version)
5818{
John Kessenich9e55f632015-07-15 10:03:39 -06005819 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005820 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005821 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005822 version = buf;
5823}
5824
John Kessenich140f3df2015-06-26 16:58:36 -06005825// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005826void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005827{
5828 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005829 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005830 if (out.fail())
5831 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005832 for (int i = 0; i < (int)spirv.size(); ++i) {
5833 unsigned int word = spirv[i];
5834 out.write((const char*)&word, 4);
5835 }
5836 out.close();
5837}
5838
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005839// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005840void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005841{
5842 std::ofstream out;
5843 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005844 if (out.fail())
5845 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005846 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005847 if (varName != nullptr) {
5848 out << "\t #pragma once" << std::endl;
5849 out << "const uint32_t " << varName << "[] = {" << std::endl;
5850 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005851 const int WORDS_PER_LINE = 8;
5852 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5853 out << "\t";
5854 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5855 const unsigned int word = spirv[i + j];
5856 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5857 if (i + j + 1 < (int)spirv.size()) {
5858 out << ",";
5859 }
5860 }
5861 out << std::endl;
5862 }
Flavio15017db2017-02-15 14:29:33 -08005863 if (varName != nullptr) {
5864 out << "};";
5865 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005866 out.close();
5867}
5868
John Kessenich140f3df2015-06-26 16:58:36 -06005869//
5870// Set up the glslang traversal
5871//
John Kessenich121853f2017-05-31 17:11:16 -06005872void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005873{
Lei Zhang17535f72016-05-04 15:55:59 -04005874 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005875 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005876}
5877
John Kessenich121853f2017-05-31 17:11:16 -06005878void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5879 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005880{
John Kessenich140f3df2015-06-26 16:58:36 -06005881 TIntermNode* root = intermediate.getTreeRoot();
5882
5883 if (root == 0)
5884 return;
5885
John Kessenich121853f2017-05-31 17:11:16 -06005886 glslang::SpvOptions defaultOptions;
5887 if (options == nullptr)
5888 options = &defaultOptions;
5889
John Kessenich140f3df2015-06-26 16:58:36 -06005890 glslang::GetThreadPoolAllocator().push();
5891
John Kessenich121853f2017-05-31 17:11:16 -06005892 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005893 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005894 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005895 it.dumpSpv(spirv);
5896
5897 glslang::GetThreadPoolAllocator().pop();
5898}
5899
5900}; // end namespace glslang