blob: a82867a4a880a0dad5640c2be4106d6e46689695 [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);
Rex Xu5e317ff2017-03-16 23:02:39 +0800458 if (glslangIntermediate->getStage() == EShLangVertex ||
459 glslangIntermediate->getStage() == EShLangTessControl ||
460 glslangIntermediate->getStage() == EShLangTessEvaluation) {
461
John Kessenichb41bff62017-08-11 13:07:17 -0600462 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
463 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800464 }
Rex Xu5e317ff2017-03-16 23:02:39 +0800465 }
John Kessenich92187592016-02-01 13:45:25 -0700466 return spv::BuiltInViewportIndex;
467
John Kessenich5e801132016-02-15 11:09:46 -0700468 case glslang::EbvSampleId:
469 builder.addCapability(spv::CapabilitySampleRateShading);
470 return spv::BuiltInSampleId;
471
472 case glslang::EbvSamplePosition:
473 builder.addCapability(spv::CapabilitySampleRateShading);
474 return spv::BuiltInSamplePosition;
475
476 case glslang::EbvSampleMask:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleMask;
479
John Kessenich78a45572016-07-08 14:05:15 -0600480 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800481 if (!memberDeclaration) {
482 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800483 if (glslangIntermediate->getStage() == EShLangVertex ||
484 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800485 glslangIntermediate->getStage() == EShLangTessEvaluation) {
486
John Kessenichb41bff62017-08-11 13:07:17 -0600487 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
488 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
chaoc771d89f2017-01-13 01:10:53 -0800489 }
Rex Xu5e317ff2017-03-16 23:02:39 +0800490 }
491
John Kessenich78a45572016-07-08 14:05:15 -0600492 return spv::BuiltInLayer;
493
John Kessenich140f3df2015-06-26 16:58:36 -0600494 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600495 case glslang::EbvVertexId: return spv::BuiltInVertexId;
496 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700497 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
498 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800499
John Kessenichda581a22015-10-14 14:10:30 -0600500 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800501 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
502 builder.addCapability(spv::CapabilityDrawParameters);
503 return spv::BuiltInBaseVertex;
504
John Kessenichda581a22015-10-14 14:10:30 -0600505 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800506 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
507 builder.addCapability(spv::CapabilityDrawParameters);
508 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200509
John Kessenichda581a22015-10-14 14:10:30 -0600510 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800511 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
512 builder.addCapability(spv::CapabilityDrawParameters);
513 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200514
515 case glslang::EbvPrimitiveId:
516 if (glslangIntermediate->getStage() == EShLangFragment)
517 builder.addCapability(spv::CapabilityGeometry);
518 return spv::BuiltInPrimitiveId;
519
Rex Xu37cdcee2017-06-29 17:46:34 +0800520 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800521 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
522 builder.addCapability(spv::CapabilityStencilExportEXT);
523 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800524
John Kessenich140f3df2015-06-26 16:58:36 -0600525 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
527 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
528 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
529 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
530 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
531 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
532 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600533 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
534 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
535 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
536 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
537 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
538 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
539 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
540 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800541
Rex Xu574ab042016-04-14 16:53:07 +0800542 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800543 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800544 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
545 return spv::BuiltInSubgroupSize;
546
Rex Xu574ab042016-04-14 16:53:07 +0800547 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800548 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800549 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
550 return spv::BuiltInSubgroupLocalInvocationId;
551
Rex Xu574ab042016-04-14 16:53:07 +0800552 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800553 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
554 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
555 return spv::BuiltInSubgroupEqMaskKHR;
556
Rex Xu574ab042016-04-14 16:53:07 +0800557 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800558 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
559 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
560 return spv::BuiltInSubgroupGeMaskKHR;
561
Rex Xu574ab042016-04-14 16:53:07 +0800562 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800563 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
564 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
565 return spv::BuiltInSubgroupGtMaskKHR;
566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupLeMaskKHR;
571
Rex Xu574ab042016-04-14 16:53:07 +0800572 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
574 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
575 return spv::BuiltInSubgroupLtMaskKHR;
576
Rex Xu9d93a232016-05-05 12:30:44 +0800577#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800578 case glslang::EbvBaryCoordNoPersp:
579 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
580 return spv::BuiltInBaryCoordNoPerspAMD;
581
582 case glslang::EbvBaryCoordNoPerspCentroid:
583 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
584 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
585
586 case glslang::EbvBaryCoordNoPerspSample:
587 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
588 return spv::BuiltInBaryCoordNoPerspSampleAMD;
589
590 case glslang::EbvBaryCoordSmooth:
591 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
592 return spv::BuiltInBaryCoordSmoothAMD;
593
594 case glslang::EbvBaryCoordSmoothCentroid:
595 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
596 return spv::BuiltInBaryCoordSmoothCentroidAMD;
597
598 case glslang::EbvBaryCoordSmoothSample:
599 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
600 return spv::BuiltInBaryCoordSmoothSampleAMD;
601
602 case glslang::EbvBaryCoordPullModel:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800605#endif
chaoc771d89f2017-01-13 01:10:53 -0800606
John Kessenich6c8aaac2017-02-27 01:20:51 -0700607 case glslang::EbvDeviceIndex:
608 builder.addExtension(spv::E_SPV_KHR_device_group);
609 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700610 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700611
612 case glslang::EbvViewIndex:
613 builder.addExtension(spv::E_SPV_KHR_multiview);
614 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700615 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700616
chaoc771d89f2017-01-13 01:10:53 -0800617#ifdef NV_EXTENSIONS
618 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800619 if (!memberDeclaration) {
620 builder.addExtension(spv::E_SPV_NV_viewport_array2);
621 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
622 }
chaoc771d89f2017-01-13 01:10:53 -0800623 return spv::BuiltInViewportMaskNV;
624 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800625 if (!memberDeclaration) {
626 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
627 builder.addCapability(spv::CapabilityShaderStereoViewNV);
628 }
chaoc771d89f2017-01-13 01:10:53 -0800629 return spv::BuiltInSecondaryPositionNV;
630 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800631 if (!memberDeclaration) {
632 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
633 builder.addCapability(spv::CapabilityShaderStereoViewNV);
634 }
chaoc771d89f2017-01-13 01:10:53 -0800635 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800636 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800637 if (!memberDeclaration) {
638 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
639 builder.addCapability(spv::CapabilityPerViewAttributesNV);
640 }
chaocdf3956c2017-02-14 14:52:34 -0800641 return spv::BuiltInPositionPerViewNV;
642 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800643 if (!memberDeclaration) {
644 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
645 builder.addCapability(spv::CapabilityPerViewAttributesNV);
646 }
chaocdf3956c2017-02-14 14:52:34 -0800647 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800648#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800649 default:
650 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600651 }
652}
653
Rex Xufc618912015-09-09 16:42:49 +0800654// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700655spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800656{
657 assert(type.getBasicType() == glslang::EbtSampler);
658
John Kessenich5d0fa972016-02-15 11:57:00 -0700659 // Check for capabilities
660 switch (type.getQualifier().layoutFormat) {
661 case glslang::ElfRg32f:
662 case glslang::ElfRg16f:
663 case glslang::ElfR11fG11fB10f:
664 case glslang::ElfR16f:
665 case glslang::ElfRgba16:
666 case glslang::ElfRgb10A2:
667 case glslang::ElfRg16:
668 case glslang::ElfRg8:
669 case glslang::ElfR16:
670 case glslang::ElfR8:
671 case glslang::ElfRgba16Snorm:
672 case glslang::ElfRg16Snorm:
673 case glslang::ElfRg8Snorm:
674 case glslang::ElfR16Snorm:
675 case glslang::ElfR8Snorm:
676
677 case glslang::ElfRg32i:
678 case glslang::ElfRg16i:
679 case glslang::ElfRg8i:
680 case glslang::ElfR16i:
681 case glslang::ElfR8i:
682
683 case glslang::ElfRgb10a2ui:
684 case glslang::ElfRg32ui:
685 case glslang::ElfRg16ui:
686 case glslang::ElfRg8ui:
687 case glslang::ElfR16ui:
688 case glslang::ElfR8ui:
689 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
690 break;
691
692 default:
693 break;
694 }
695
696 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800697 switch (type.getQualifier().layoutFormat) {
698 case glslang::ElfNone: return spv::ImageFormatUnknown;
699 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
700 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
701 case glslang::ElfR32f: return spv::ImageFormatR32f;
702 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
703 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
704 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
705 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
706 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
707 case glslang::ElfR16f: return spv::ImageFormatR16f;
708 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
709 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
710 case glslang::ElfRg16: return spv::ImageFormatRg16;
711 case glslang::ElfRg8: return spv::ImageFormatRg8;
712 case glslang::ElfR16: return spv::ImageFormatR16;
713 case glslang::ElfR8: return spv::ImageFormatR8;
714 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
715 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
716 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
717 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
718 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
719 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
720 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
721 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
722 case glslang::ElfR32i: return spv::ImageFormatR32i;
723 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
724 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
725 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
726 case glslang::ElfR16i: return spv::ImageFormatR16i;
727 case glslang::ElfR8i: return spv::ImageFormatR8i;
728 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
729 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
730 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
731 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
732 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
733 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
734 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
735 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
736 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
737 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600738 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800739 }
740}
741
Rex Xu57e65922017-07-04 23:23:40 +0800742spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
743{
744 switch (selectionControl) {
745 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
746 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
747 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
748 default: return spv::SelectionControlMaskNone;
749 }
750}
751
steve-lunargf1709e72017-05-02 20:14:50 -0600752spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
753{
754 switch (loopControl) {
755 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
756 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
757 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
758 // TODO: DependencyInfinite
759 // TODO: DependencyLength
760 default: return spv::LoopControlMaskNone;
761 }
762}
763
John Kessenicha5c5fb62017-05-05 05:09:58 -0600764// Translate glslang type to SPIR-V storage class.
765spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
766{
767 if (type.getQualifier().isPipeInput())
768 return spv::StorageClassInput;
769 else if (type.getQualifier().isPipeOutput())
770 return spv::StorageClassOutput;
771 else if (type.getBasicType() == glslang::EbtAtomicUint)
772 return spv::StorageClassAtomicCounter;
773 else if (type.containsOpaque())
774 return spv::StorageClassUniformConstant;
775 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
776 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
777 return spv::StorageClassStorageBuffer;
778 } else if (type.getQualifier().isUniformOrBuffer()) {
779 if (type.getQualifier().layoutPushConstant)
780 return spv::StorageClassPushConstant;
781 if (type.getBasicType() == glslang::EbtBlock)
782 return spv::StorageClassUniform;
783 else
784 return spv::StorageClassUniformConstant;
785 } else {
786 switch (type.getQualifier().storage) {
787 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
788 case glslang::EvqGlobal: return spv::StorageClassPrivate;
789 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
790 case glslang::EvqTemporary: return spv::StorageClassFunction;
791 default:
792 assert(0);
793 return spv::StorageClassFunction;
794 }
795 }
796}
797
qining25262b32016-05-06 17:25:16 -0400798// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700799// descriptor set.
800bool IsDescriptorResource(const glslang::TType& type)
801{
John Kessenichf7497e22016-03-08 21:36:22 -0700802 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700803 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700804 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700805
806 // non block...
807 // basically samplerXXX/subpass/sampler/texture are all included
808 // if they are the global-scope-class, not the function parameter
809 // (or local, if they ever exist) class.
810 if (type.getBasicType() == glslang::EbtSampler)
811 return type.getQualifier().isUniformOrBuffer();
812
813 // None of the above.
814 return false;
815}
816
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
818{
819 if (child.layoutMatrix == glslang::ElmNone)
820 child.layoutMatrix = parent.layoutMatrix;
821
822 if (parent.invariant)
823 child.invariant = true;
824 if (parent.nopersp)
825 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800826#ifdef AMD_EXTENSIONS
827 if (parent.explicitInterp)
828 child.explicitInterp = true;
829#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700830 if (parent.flat)
831 child.flat = true;
832 if (parent.centroid)
833 child.centroid = true;
834 if (parent.patch)
835 child.patch = true;
836 if (parent.sample)
837 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800838 if (parent.coherent)
839 child.coherent = true;
840 if (parent.volatil)
841 child.volatil = true;
842 if (parent.restrict)
843 child.restrict = true;
844 if (parent.readonly)
845 child.readonly = true;
846 if (parent.writeonly)
847 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700848}
849
John Kessenichf2b7f332016-09-01 17:05:23 -0600850bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851{
John Kessenich7b9fa252016-01-21 18:56:57 -0700852 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600853 // - struct members might inherit from a struct declaration
854 // (note that non-block structs don't explicitly inherit,
855 // only implicitly, meaning no decoration involved)
856 // - affect decorations on the struct members
857 // (note smooth does not, and expecting something like volatile
858 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700859 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600860 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700861}
862
John Kessenich140f3df2015-06-26 16:58:36 -0600863//
864// Implement the TGlslangToSpvTraverser class.
865//
866
John Kessenich121853f2017-05-31 17:11:16 -0600867TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
868 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
869 : TIntermTraverser(true, false, true),
870 options(options),
871 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600872 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400873 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700874 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600875 glslangIntermediate(glslangIntermediate)
876{
877 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
878
879 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600880 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
881 glslangIntermediate->getVersion());
882
John Kessenich121853f2017-05-31 17:11:16 -0600883 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600884 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600885 builder.setSourceFile(glslangIntermediate->getSourceFile());
886
887 // Set the source shader's text. If for SPV version 1.0, include
888 // a preamble in comments stating the OpModuleProcessed instructions.
889 // Otherwise, emit those as actual instructions.
890 std::string text;
891 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
892 for (int p = 0; p < (int)processes.size(); ++p) {
893 if (glslangIntermediate->getSpv().spv < 0x00010100) {
894 text.append("// OpModuleProcessed ");
895 text.append(processes[p]);
896 text.append("\n");
897 } else
898 builder.addModuleProcessed(processes[p]);
899 }
900 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
901 text.append("#line 1\n");
902 text.append(glslangIntermediate->getSourceText());
903 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600904 }
John Kessenich140f3df2015-06-26 16:58:36 -0600905 stdBuiltins = builder.import("GLSL.std.450");
906 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600907 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
908 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600909
910 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600911 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
912 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600913 builder.addSourceExtension(it->c_str());
914
915 // Add the top-level modes for this shader.
916
John Kessenich92187592016-02-01 13:45:25 -0700917 if (glslangIntermediate->getXfbMode()) {
918 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600919 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700920 }
John Kessenich140f3df2015-06-26 16:58:36 -0600921
922 unsigned int mode;
923 switch (glslangIntermediate->getStage()) {
924 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600925 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600926 break;
927
steve-lunarge7412492017-03-23 11:56:07 -0600928 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600929 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600930 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600931
steve-lunarge7412492017-03-23 11:56:07 -0600932 glslang::TLayoutGeometry primitive;
933
934 if (glslangIntermediate->getStage() == EShLangTessControl) {
935 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
936 primitive = glslangIntermediate->getOutputPrimitive();
937 } else {
938 primitive = glslangIntermediate->getInputPrimitive();
939 }
940
941 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700942 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
943 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
944 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600945 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600946 }
John Kessenich4016e382016-07-15 11:53:56 -0600947 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600948 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
949
John Kesseniche6903322015-10-13 16:29:02 -0600950 switch (glslangIntermediate->getVertexSpacing()) {
951 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
952 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
953 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600954 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600955 }
John Kessenich4016e382016-07-15 11:53:56 -0600956 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600957 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
958
959 switch (glslangIntermediate->getVertexOrder()) {
960 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
961 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600962 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600963 }
John Kessenich4016e382016-07-15 11:53:56 -0600964 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600965 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
966
967 if (glslangIntermediate->getPointMode())
968 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600969 break;
970
971 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600972 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600973 switch (glslangIntermediate->getInputPrimitive()) {
974 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
975 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
976 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700977 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600978 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600979 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600980 }
John Kessenich4016e382016-07-15 11:53:56 -0600981 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600982 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600983
John Kessenich140f3df2015-06-26 16:58:36 -0600984 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
985
986 switch (glslangIntermediate->getOutputPrimitive()) {
987 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
988 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
989 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600990 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600991 }
John Kessenich4016e382016-07-15 11:53:56 -0600992 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600993 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
994 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
995 break;
996
997 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600998 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600999 if (glslangIntermediate->getPixelCenterInteger())
1000 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001001
John Kessenich140f3df2015-06-26 16:58:36 -06001002 if (glslangIntermediate->getOriginUpperLeft())
1003 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001004 else
1005 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001006
1007 if (glslangIntermediate->getEarlyFragmentTests())
1008 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1009
chaocc1204522017-06-30 17:14:30 -07001010 if (glslangIntermediate->getPostDepthCoverage()) {
1011 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1012 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1013 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1014 }
1015
John Kesseniche6903322015-10-13 16:29:02 -06001016 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001017 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1018 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001019 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001020 }
John Kessenich4016e382016-07-15 11:53:56 -06001021 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001022 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1023
1024 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1025 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001026 break;
1027
1028 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001029 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001030 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1031 glslangIntermediate->getLocalSize(1),
1032 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001033 break;
1034
1035 default:
1036 break;
1037 }
John Kessenich140f3df2015-06-26 16:58:36 -06001038}
1039
John Kessenichfca82622016-11-26 13:23:20 -07001040// Finish creating SPV, after the traversal is complete.
1041void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001042{
John Kessenich517fe7a2016-11-26 13:31:47 -07001043 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001044 builder.setBuildPoint(shaderEntry->getLastBlock());
1045 builder.leaveFunction();
1046 }
1047
John Kessenich7ba63412015-12-20 17:37:07 -07001048 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001049 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1050 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001051
qiningda397332016-03-09 19:54:03 -05001052 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001053}
1054
John Kessenichfca82622016-11-26 13:23:20 -07001055// Write the SPV into 'out'.
1056void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001057{
John Kessenichfca82622016-11-26 13:23:20 -07001058 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001059}
1060
1061//
1062// Implement the traversal functions.
1063//
1064// Return true from interior nodes to have the external traversal
1065// continue on to children. Return false if children were
1066// already processed.
1067//
1068
1069//
qining25262b32016-05-06 17:25:16 -04001070// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001071// - uniform/input reads
1072// - output writes
1073// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1074// - something simple that degenerates into the last bullet
1075//
1076void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1077{
qining75d1d802016-04-06 14:42:01 -04001078 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1079 if (symbol->getType().getQualifier().isSpecConstant())
1080 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1081
John Kessenich140f3df2015-06-26 16:58:36 -06001082 // getSymbolId() will set up all the IO decorations on the first call.
1083 // Formal function parameters were mapped during makeFunctions().
1084 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001085
1086 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1087 if (builder.isPointer(id)) {
1088 spv::StorageClass sc = builder.getStorageClass(id);
1089 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1090 iOSet.insert(id);
1091 }
1092
1093 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001094 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001095 // Prepare to generate code for the access
1096
1097 // L-value chains will be computed left to right. We're on the symbol now,
1098 // which is the left-most part of the access chain, so now is "clear" time,
1099 // followed by setting the base.
1100 builder.clearAccessChain();
1101
1102 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001103 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001104 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001105 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001106 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001107 // These are also pure R-values.
1108 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001109 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001110 builder.setAccessChainRValue(id);
1111 else
1112 builder.setAccessChainLValue(id);
1113 }
1114}
1115
1116bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1117{
John Kesseniche485c7a2017-05-31 18:50:53 -06001118 builder.setLine(node->getLoc().line);
1119
qining40887662016-04-03 22:20:42 -04001120 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1121 if (node->getType().getQualifier().isSpecConstant())
1122 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1123
John Kessenich140f3df2015-06-26 16:58:36 -06001124 // First, handle special cases
1125 switch (node->getOp()) {
1126 case glslang::EOpAssign:
1127 case glslang::EOpAddAssign:
1128 case glslang::EOpSubAssign:
1129 case glslang::EOpMulAssign:
1130 case glslang::EOpVectorTimesMatrixAssign:
1131 case glslang::EOpVectorTimesScalarAssign:
1132 case glslang::EOpMatrixTimesScalarAssign:
1133 case glslang::EOpMatrixTimesMatrixAssign:
1134 case glslang::EOpDivAssign:
1135 case glslang::EOpModAssign:
1136 case glslang::EOpAndAssign:
1137 case glslang::EOpInclusiveOrAssign:
1138 case glslang::EOpExclusiveOrAssign:
1139 case glslang::EOpLeftShiftAssign:
1140 case glslang::EOpRightShiftAssign:
1141 // A bin-op assign "a += b" means the same thing as "a = a + b"
1142 // where a is evaluated before b. For a simple assignment, GLSL
1143 // says to evaluate the left before the right. So, always, left
1144 // node then right node.
1145 {
1146 // get the left l-value, save it away
1147 builder.clearAccessChain();
1148 node->getLeft()->traverse(this);
1149 spv::Builder::AccessChain lValue = builder.getAccessChain();
1150
1151 // evaluate the right
1152 builder.clearAccessChain();
1153 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001154 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001155
1156 if (node->getOp() != glslang::EOpAssign) {
1157 // the left is also an r-value
1158 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001159 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001160
1161 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001162 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001163 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001164 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1165 node->getType().getBasicType());
1166
1167 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001168 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001169 }
1170
1171 // store the result
1172 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001173 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001174
1175 // assignments are expressions having an rValue after they are evaluated...
1176 builder.clearAccessChain();
1177 builder.setAccessChainRValue(rValue);
1178 }
1179 return false;
1180 case glslang::EOpIndexDirect:
1181 case glslang::EOpIndexDirectStruct:
1182 {
1183 // Get the left part of the access chain.
1184 node->getLeft()->traverse(this);
1185
1186 // Add the next element in the chain
1187
David Netoa901ffe2016-06-08 14:11:40 +01001188 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001189 if (! node->getLeft()->getType().isArray() &&
1190 node->getLeft()->getType().isVector() &&
1191 node->getOp() == glslang::EOpIndexDirect) {
1192 // This is essentially a hard-coded vector swizzle of size 1,
1193 // so short circuit the access-chain stuff with a swizzle.
1194 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001195 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001196 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001197 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001198 int spvIndex = glslangIndex;
1199 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1200 node->getOp() == glslang::EOpIndexDirectStruct)
1201 {
1202 // This may be, e.g., an anonymous block-member selection, which generally need
1203 // index remapping due to hidden members in anonymous blocks.
1204 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1205 assert(remapper.size() > 0);
1206 spvIndex = remapper[glslangIndex];
1207 }
John Kessenichebb50532016-05-16 19:22:05 -06001208
David Netoa901ffe2016-06-08 14:11:40 +01001209 // normal case for indexing array or structure or block
1210 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1211
1212 // Add capabilities here for accessing PointSize and clip/cull distance.
1213 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001214 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001215 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001216 }
1217 }
1218 return false;
1219 case glslang::EOpIndexIndirect:
1220 {
1221 // Structure or array or vector indirection.
1222 // Will use native SPIR-V access-chain for struct and array indirection;
1223 // matrices are arrays of vectors, so will also work for a matrix.
1224 // Will use the access chain's 'component' for variable index into a vector.
1225
1226 // This adapter is building access chains left to right.
1227 // Set up the access chain to the left.
1228 node->getLeft()->traverse(this);
1229
1230 // save it so that computing the right side doesn't trash it
1231 spv::Builder::AccessChain partial = builder.getAccessChain();
1232
1233 // compute the next index in the chain
1234 builder.clearAccessChain();
1235 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001236 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001237
1238 // restore the saved access chain
1239 builder.setAccessChain(partial);
1240
1241 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001242 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001243 else
John Kessenichfa668da2015-09-13 14:46:30 -06001244 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001245 }
1246 return false;
1247 case glslang::EOpVectorSwizzle:
1248 {
1249 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001250 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001251 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001252 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001253 }
1254 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001255 case glslang::EOpMatrixSwizzle:
1256 logger->missingFunctionality("matrix swizzle");
1257 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001258 case glslang::EOpLogicalOr:
1259 case glslang::EOpLogicalAnd:
1260 {
1261
1262 // These may require short circuiting, but can sometimes be done as straight
1263 // binary operations. The right operand must be short circuited if it has
1264 // side effects, and should probably be if it is complex.
1265 if (isTrivial(node->getRight()->getAsTyped()))
1266 break; // handle below as a normal binary operation
1267 // otherwise, we need to do dynamic short circuiting on the right operand
1268 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1269 builder.clearAccessChain();
1270 builder.setAccessChainRValue(result);
1271 }
1272 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001273 default:
1274 break;
1275 }
1276
1277 // Assume generic binary op...
1278
John Kessenich32cfd492016-02-02 12:37:46 -07001279 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001280 builder.clearAccessChain();
1281 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001282 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001283
John Kessenich32cfd492016-02-02 12:37:46 -07001284 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001285 builder.clearAccessChain();
1286 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001287 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001288
John Kessenich32cfd492016-02-02 12:37:46 -07001289 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001290 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001291 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001292 convertGlslangToSpvType(node->getType()), left, right,
1293 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001294
John Kessenich50e57562015-12-21 21:21:11 -07001295 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001296 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001297 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001298 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001299 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001300 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001301 return false;
1302 }
John Kessenich140f3df2015-06-26 16:58:36 -06001303}
1304
1305bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1306{
John Kesseniche485c7a2017-05-31 18:50:53 -06001307 builder.setLine(node->getLoc().line);
1308
qining40887662016-04-03 22:20:42 -04001309 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1310 if (node->getType().getQualifier().isSpecConstant())
1311 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1312
John Kessenichfc51d282015-08-19 13:34:18 -06001313 spv::Id result = spv::NoResult;
1314
1315 // try texturing first
1316 result = createImageTextureFunctionCall(node);
1317 if (result != spv::NoResult) {
1318 builder.clearAccessChain();
1319 builder.setAccessChainRValue(result);
1320
1321 return false; // done with this node
1322 }
1323
1324 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001325
1326 if (node->getOp() == glslang::EOpArrayLength) {
1327 // Quite special; won't want to evaluate the operand.
1328
1329 // Normal .length() would have been constant folded by the front-end.
1330 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001331 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001332 assert(node->getOperand()->getType().isRuntimeSizedArray());
1333 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1334 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001335 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1336 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001337
1338 builder.clearAccessChain();
1339 builder.setAccessChainRValue(length);
1340
1341 return false;
1342 }
1343
John Kessenichfc51d282015-08-19 13:34:18 -06001344 // Start by evaluating the operand
1345
John Kessenich8c8505c2016-07-26 12:50:38 -06001346 // Does it need a swizzle inversion? If so, evaluation is inverted;
1347 // operate first on the swizzle base, then apply the swizzle.
1348 spv::Id invertedType = spv::NoType;
1349 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1350 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1351 invertedType = getInvertedSwizzleType(*node->getOperand());
1352
John Kessenich140f3df2015-06-26 16:58:36 -06001353 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001354 if (invertedType != spv::NoType)
1355 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1356 else
1357 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001358
Rex Xufc618912015-09-09 16:42:49 +08001359 spv::Id operand = spv::NoResult;
1360
1361 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1362 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001363 node->getOp() == glslang::EOpAtomicCounter ||
1364 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001365 operand = builder.accessChainGetLValue(); // Special case l-value operands
1366 else
John Kessenich32cfd492016-02-02 12:37:46 -07001367 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001368
John Kessenichf6640762016-08-01 19:44:00 -06001369 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001370 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001371
1372 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001373 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001374 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001375
1376 // if not, then possibly an operation
1377 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001378 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001379
1380 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001381 if (invertedType)
1382 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1383
John Kessenich140f3df2015-06-26 16:58:36 -06001384 builder.clearAccessChain();
1385 builder.setAccessChainRValue(result);
1386
1387 return false; // done with this node
1388 }
1389
1390 // it must be a special case, check...
1391 switch (node->getOp()) {
1392 case glslang::EOpPostIncrement:
1393 case glslang::EOpPostDecrement:
1394 case glslang::EOpPreIncrement:
1395 case glslang::EOpPreDecrement:
1396 {
1397 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001398 spv::Id one = 0;
1399 if (node->getBasicType() == glslang::EbtFloat)
1400 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001401 else if (node->getBasicType() == glslang::EbtDouble)
1402 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001403#ifdef AMD_EXTENSIONS
1404 else if (node->getBasicType() == glslang::EbtFloat16)
1405 one = builder.makeFloat16Constant(1.0F);
1406#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001407 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1408 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001409#ifdef AMD_EXTENSIONS
1410 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1411 one = builder.makeInt16Constant(1);
1412#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001413 else
1414 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001415 glslang::TOperator op;
1416 if (node->getOp() == glslang::EOpPreIncrement ||
1417 node->getOp() == glslang::EOpPostIncrement)
1418 op = glslang::EOpAdd;
1419 else
1420 op = glslang::EOpSub;
1421
John Kessenichf6640762016-08-01 19:44:00 -06001422 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001423 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001424 convertGlslangToSpvType(node->getType()), operand, one,
1425 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001426 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001427
1428 // The result of operation is always stored, but conditionally the
1429 // consumed result. The consumed result is always an r-value.
1430 builder.accessChainStore(result);
1431 builder.clearAccessChain();
1432 if (node->getOp() == glslang::EOpPreIncrement ||
1433 node->getOp() == glslang::EOpPreDecrement)
1434 builder.setAccessChainRValue(result);
1435 else
1436 builder.setAccessChainRValue(operand);
1437 }
1438
1439 return false;
1440
1441 case glslang::EOpEmitStreamVertex:
1442 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1443 return false;
1444 case glslang::EOpEndStreamPrimitive:
1445 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1446 return false;
1447
1448 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001449 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001450 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001451 }
John Kessenich140f3df2015-06-26 16:58:36 -06001452}
1453
1454bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1455{
qining27e04a02016-04-14 16:40:20 -04001456 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1457 if (node->getType().getQualifier().isSpecConstant())
1458 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1459
John Kessenichfc51d282015-08-19 13:34:18 -06001460 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001461 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1462 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001463
1464 // try texturing
1465 result = createImageTextureFunctionCall(node);
1466 if (result != spv::NoResult) {
1467 builder.clearAccessChain();
1468 builder.setAccessChainRValue(result);
1469
1470 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001471#ifdef AMD_EXTENSIONS
1472 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1473#else
John Kessenich56bab042015-09-16 10:54:31 -06001474 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001475#endif
Rex Xufc618912015-09-09 16:42:49 +08001476 // "imageStore" is a special case, which has no result
1477 return false;
1478 }
John Kessenichfc51d282015-08-19 13:34:18 -06001479
John Kessenich140f3df2015-06-26 16:58:36 -06001480 glslang::TOperator binOp = glslang::EOpNull;
1481 bool reduceComparison = true;
1482 bool isMatrix = false;
1483 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001484 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001485
1486 assert(node->getOp());
1487
John Kessenichf6640762016-08-01 19:44:00 -06001488 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001489
1490 switch (node->getOp()) {
1491 case glslang::EOpSequence:
1492 {
1493 if (preVisit)
1494 ++sequenceDepth;
1495 else
1496 --sequenceDepth;
1497
1498 if (sequenceDepth == 1) {
1499 // If this is the parent node of all the functions, we want to see them
1500 // early, so all call points have actual SPIR-V functions to reference.
1501 // In all cases, still let the traverser visit the children for us.
1502 makeFunctions(node->getAsAggregate()->getSequence());
1503
John Kessenich6fccb3c2016-09-19 16:01:41 -06001504 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001505 // anything else gets there, so visit out of order, doing them all now.
1506 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1507
John Kessenich6a60c2f2016-12-08 21:01:59 -07001508 // 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 -06001509 // so do them manually.
1510 visitFunctions(node->getAsAggregate()->getSequence());
1511
1512 return false;
1513 }
1514
1515 return true;
1516 }
1517 case glslang::EOpLinkerObjects:
1518 {
1519 if (visit == glslang::EvPreVisit)
1520 linkageOnly = true;
1521 else
1522 linkageOnly = false;
1523
1524 return true;
1525 }
1526 case glslang::EOpComma:
1527 {
1528 // processing from left to right naturally leaves the right-most
1529 // lying around in the access chain
1530 glslang::TIntermSequence& glslangOperands = node->getSequence();
1531 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1532 glslangOperands[i]->traverse(this);
1533
1534 return false;
1535 }
1536 case glslang::EOpFunction:
1537 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001538 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001539 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001540 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001541 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001542 } else {
1543 handleFunctionEntry(node);
1544 }
1545 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001546 if (inEntryPoint)
1547 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001548 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001549 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001550 }
1551
1552 return true;
1553 case glslang::EOpParameters:
1554 // Parameters will have been consumed by EOpFunction processing, but not
1555 // the body, so we still visited the function node's children, making this
1556 // child redundant.
1557 return false;
1558 case glslang::EOpFunctionCall:
1559 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001560 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 if (node->isUserDefined())
1562 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001563 // 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 -07001564 if (result) {
1565 builder.clearAccessChain();
1566 builder.setAccessChainRValue(result);
1567 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001568 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001569
1570 return false;
1571 }
1572 case glslang::EOpConstructMat2x2:
1573 case glslang::EOpConstructMat2x3:
1574 case glslang::EOpConstructMat2x4:
1575 case glslang::EOpConstructMat3x2:
1576 case glslang::EOpConstructMat3x3:
1577 case glslang::EOpConstructMat3x4:
1578 case glslang::EOpConstructMat4x2:
1579 case glslang::EOpConstructMat4x3:
1580 case glslang::EOpConstructMat4x4:
1581 case glslang::EOpConstructDMat2x2:
1582 case glslang::EOpConstructDMat2x3:
1583 case glslang::EOpConstructDMat2x4:
1584 case glslang::EOpConstructDMat3x2:
1585 case glslang::EOpConstructDMat3x3:
1586 case glslang::EOpConstructDMat3x4:
1587 case glslang::EOpConstructDMat4x2:
1588 case glslang::EOpConstructDMat4x3:
1589 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001590 case glslang::EOpConstructIMat2x2:
1591 case glslang::EOpConstructIMat2x3:
1592 case glslang::EOpConstructIMat2x4:
1593 case glslang::EOpConstructIMat3x2:
1594 case glslang::EOpConstructIMat3x3:
1595 case glslang::EOpConstructIMat3x4:
1596 case glslang::EOpConstructIMat4x2:
1597 case glslang::EOpConstructIMat4x3:
1598 case glslang::EOpConstructIMat4x4:
1599 case glslang::EOpConstructUMat2x2:
1600 case glslang::EOpConstructUMat2x3:
1601 case glslang::EOpConstructUMat2x4:
1602 case glslang::EOpConstructUMat3x2:
1603 case glslang::EOpConstructUMat3x3:
1604 case glslang::EOpConstructUMat3x4:
1605 case glslang::EOpConstructUMat4x2:
1606 case glslang::EOpConstructUMat4x3:
1607 case glslang::EOpConstructUMat4x4:
1608 case glslang::EOpConstructBMat2x2:
1609 case glslang::EOpConstructBMat2x3:
1610 case glslang::EOpConstructBMat2x4:
1611 case glslang::EOpConstructBMat3x2:
1612 case glslang::EOpConstructBMat3x3:
1613 case glslang::EOpConstructBMat3x4:
1614 case glslang::EOpConstructBMat4x2:
1615 case glslang::EOpConstructBMat4x3:
1616 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001617#ifdef AMD_EXTENSIONS
1618 case glslang::EOpConstructF16Mat2x2:
1619 case glslang::EOpConstructF16Mat2x3:
1620 case glslang::EOpConstructF16Mat2x4:
1621 case glslang::EOpConstructF16Mat3x2:
1622 case glslang::EOpConstructF16Mat3x3:
1623 case glslang::EOpConstructF16Mat3x4:
1624 case glslang::EOpConstructF16Mat4x2:
1625 case glslang::EOpConstructF16Mat4x3:
1626 case glslang::EOpConstructF16Mat4x4:
1627#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001628 isMatrix = true;
1629 // fall through
1630 case glslang::EOpConstructFloat:
1631 case glslang::EOpConstructVec2:
1632 case glslang::EOpConstructVec3:
1633 case glslang::EOpConstructVec4:
1634 case glslang::EOpConstructDouble:
1635 case glslang::EOpConstructDVec2:
1636 case glslang::EOpConstructDVec3:
1637 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001638#ifdef AMD_EXTENSIONS
1639 case glslang::EOpConstructFloat16:
1640 case glslang::EOpConstructF16Vec2:
1641 case glslang::EOpConstructF16Vec3:
1642 case glslang::EOpConstructF16Vec4:
1643#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001644 case glslang::EOpConstructBool:
1645 case glslang::EOpConstructBVec2:
1646 case glslang::EOpConstructBVec3:
1647 case glslang::EOpConstructBVec4:
1648 case glslang::EOpConstructInt:
1649 case glslang::EOpConstructIVec2:
1650 case glslang::EOpConstructIVec3:
1651 case glslang::EOpConstructIVec4:
1652 case glslang::EOpConstructUint:
1653 case glslang::EOpConstructUVec2:
1654 case glslang::EOpConstructUVec3:
1655 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001656 case glslang::EOpConstructInt64:
1657 case glslang::EOpConstructI64Vec2:
1658 case glslang::EOpConstructI64Vec3:
1659 case glslang::EOpConstructI64Vec4:
1660 case glslang::EOpConstructUint64:
1661 case glslang::EOpConstructU64Vec2:
1662 case glslang::EOpConstructU64Vec3:
1663 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001664#ifdef AMD_EXTENSIONS
1665 case glslang::EOpConstructInt16:
1666 case glslang::EOpConstructI16Vec2:
1667 case glslang::EOpConstructI16Vec3:
1668 case glslang::EOpConstructI16Vec4:
1669 case glslang::EOpConstructUint16:
1670 case glslang::EOpConstructU16Vec2:
1671 case glslang::EOpConstructU16Vec3:
1672 case glslang::EOpConstructU16Vec4:
1673#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001674 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001675 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001676 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001677 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001678 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001679 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001680 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001681 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001682 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001683 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001684 std::vector<spv::Id> constituents;
1685 for (int c = 0; c < (int)arguments.size(); ++c)
1686 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001687 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001688 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001689 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001690 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001691 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001692
1693 builder.clearAccessChain();
1694 builder.setAccessChainRValue(constructed);
1695
1696 return false;
1697 }
1698
1699 // These six are component-wise compares with component-wise results.
1700 // Forward on to createBinaryOperation(), requesting a vector result.
1701 case glslang::EOpLessThan:
1702 case glslang::EOpGreaterThan:
1703 case glslang::EOpLessThanEqual:
1704 case glslang::EOpGreaterThanEqual:
1705 case glslang::EOpVectorEqual:
1706 case glslang::EOpVectorNotEqual:
1707 {
1708 // Map the operation to a binary
1709 binOp = node->getOp();
1710 reduceComparison = false;
1711 switch (node->getOp()) {
1712 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1713 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1714 default: binOp = node->getOp(); break;
1715 }
1716
1717 break;
1718 }
1719 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001720 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001721 binOp = glslang::EOpMul;
1722 break;
1723 case glslang::EOpOuterProduct:
1724 // two vectors multiplied to make a matrix
1725 binOp = glslang::EOpOuterProduct;
1726 break;
1727 case glslang::EOpDot:
1728 {
qining25262b32016-05-06 17:25:16 -04001729 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001730 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001731 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001732 binOp = glslang::EOpMul;
1733 break;
1734 }
1735 case glslang::EOpMod:
1736 // when an aggregate, this is the floating-point mod built-in function,
1737 // which can be emitted by the one in createBinaryOperation()
1738 binOp = glslang::EOpMod;
1739 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001740 case glslang::EOpEmitVertex:
1741 case glslang::EOpEndPrimitive:
1742 case glslang::EOpBarrier:
1743 case glslang::EOpMemoryBarrier:
1744 case glslang::EOpMemoryBarrierAtomicCounter:
1745 case glslang::EOpMemoryBarrierBuffer:
1746 case glslang::EOpMemoryBarrierImage:
1747 case glslang::EOpMemoryBarrierShared:
1748 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001749 case glslang::EOpAllMemoryBarrierWithGroupSync:
1750 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1751 case glslang::EOpWorkgroupMemoryBarrier:
1752 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001753 noReturnValue = true;
1754 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1755 break;
1756
John Kessenich426394d2015-07-23 10:22:48 -06001757 case glslang::EOpAtomicAdd:
1758 case glslang::EOpAtomicMin:
1759 case glslang::EOpAtomicMax:
1760 case glslang::EOpAtomicAnd:
1761 case glslang::EOpAtomicOr:
1762 case glslang::EOpAtomicXor:
1763 case glslang::EOpAtomicExchange:
1764 case glslang::EOpAtomicCompSwap:
1765 atomic = true;
1766 break;
1767
John Kessenich0d0c6d32017-07-23 16:08:26 -06001768 case glslang::EOpAtomicCounterAdd:
1769 case glslang::EOpAtomicCounterSubtract:
1770 case glslang::EOpAtomicCounterMin:
1771 case glslang::EOpAtomicCounterMax:
1772 case glslang::EOpAtomicCounterAnd:
1773 case glslang::EOpAtomicCounterOr:
1774 case glslang::EOpAtomicCounterXor:
1775 case glslang::EOpAtomicCounterExchange:
1776 case glslang::EOpAtomicCounterCompSwap:
1777 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1778 builder.addCapability(spv::CapabilityAtomicStorageOps);
1779 atomic = true;
1780 break;
1781
John Kessenich140f3df2015-06-26 16:58:36 -06001782 default:
1783 break;
1784 }
1785
1786 //
1787 // See if it maps to a regular operation.
1788 //
John Kessenich140f3df2015-06-26 16:58:36 -06001789 if (binOp != glslang::EOpNull) {
1790 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1791 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1792 assert(left && right);
1793
1794 builder.clearAccessChain();
1795 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001796 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001797
1798 builder.clearAccessChain();
1799 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001800 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001801
John Kesseniche485c7a2017-05-31 18:50:53 -06001802 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001803 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001804 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001805 left->getType().getBasicType(), reduceComparison);
1806
1807 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001808 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001809 builder.clearAccessChain();
1810 builder.setAccessChainRValue(result);
1811
1812 return false;
1813 }
1814
John Kessenich426394d2015-07-23 10:22:48 -06001815 //
1816 // Create the list of operands.
1817 //
John Kessenich140f3df2015-06-26 16:58:36 -06001818 glslang::TIntermSequence& glslangOperands = node->getSequence();
1819 std::vector<spv::Id> operands;
1820 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001821 // special case l-value operands; there are just a few
1822 bool lvalue = false;
1823 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001824 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001825 case glslang::EOpModf:
1826 if (arg == 1)
1827 lvalue = true;
1828 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001829 case glslang::EOpInterpolateAtSample:
1830 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001831#ifdef AMD_EXTENSIONS
1832 case glslang::EOpInterpolateAtVertex:
1833#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001834 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001835 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001836
1837 // Does it need a swizzle inversion? If so, evaluation is inverted;
1838 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001839 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001840 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1841 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1842 }
Rex Xu7a26c172015-12-08 17:12:09 +08001843 break;
Rex Xud4782c12015-09-06 16:30:11 +08001844 case glslang::EOpAtomicAdd:
1845 case glslang::EOpAtomicMin:
1846 case glslang::EOpAtomicMax:
1847 case glslang::EOpAtomicAnd:
1848 case glslang::EOpAtomicOr:
1849 case glslang::EOpAtomicXor:
1850 case glslang::EOpAtomicExchange:
1851 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001852 case glslang::EOpAtomicCounterAdd:
1853 case glslang::EOpAtomicCounterSubtract:
1854 case glslang::EOpAtomicCounterMin:
1855 case glslang::EOpAtomicCounterMax:
1856 case glslang::EOpAtomicCounterAnd:
1857 case glslang::EOpAtomicCounterOr:
1858 case glslang::EOpAtomicCounterXor:
1859 case glslang::EOpAtomicCounterExchange:
1860 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001861 if (arg == 0)
1862 lvalue = true;
1863 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001864 case glslang::EOpAddCarry:
1865 case glslang::EOpSubBorrow:
1866 if (arg == 2)
1867 lvalue = true;
1868 break;
1869 case glslang::EOpUMulExtended:
1870 case glslang::EOpIMulExtended:
1871 if (arg >= 2)
1872 lvalue = true;
1873 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001874 default:
1875 break;
1876 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001877 builder.clearAccessChain();
1878 if (invertedType != spv::NoType && arg == 0)
1879 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1880 else
1881 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001882 if (lvalue)
1883 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001884 else {
1885 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001886 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001887 }
John Kessenich140f3df2015-06-26 16:58:36 -06001888 }
John Kessenich426394d2015-07-23 10:22:48 -06001889
John Kesseniche485c7a2017-05-31 18:50:53 -06001890 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001891 if (atomic) {
1892 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001893 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001894 } else {
1895 // Pass through to generic operations.
1896 switch (glslangOperands.size()) {
1897 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001898 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001899 break;
1900 case 1:
qining25262b32016-05-06 17:25:16 -04001901 result = createUnaryOperation(
1902 node->getOp(), precision,
1903 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001904 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001905 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001906 break;
1907 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001908 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001909 break;
1910 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001911 if (invertedType)
1912 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001913 }
1914
1915 if (noReturnValue)
1916 return false;
1917
1918 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001919 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001920 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001921 } else {
1922 builder.clearAccessChain();
1923 builder.setAccessChainRValue(result);
1924 return false;
1925 }
1926}
1927
John Kessenich433e9ff2017-01-26 20:31:11 -07001928// This path handles both if-then-else and ?:
1929// The if-then-else has a node type of void, while
1930// ?: has either a void or a non-void node type
1931//
1932// Leaving the result, when not void:
1933// GLSL only has r-values as the result of a :?, but
1934// if we have an l-value, that can be more efficient if it will
1935// become the base of a complex r-value expression, because the
1936// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001937bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1938{
John Kessenich433e9ff2017-01-26 20:31:11 -07001939 // See if it simple and safe to generate OpSelect instead of using control flow.
1940 // Crucially, side effects must be avoided, and there are performance trade-offs.
1941 // Return true if good idea (and safe) for OpSelect, false otherwise.
1942 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001943 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1944 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001945 return false;
1946
1947 if (node->getTrueBlock() == nullptr ||
1948 node->getFalseBlock() == nullptr)
1949 return false;
1950
1951 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1952 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1953
1954 // return true if a single operand to ? : is okay for OpSelect
1955 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001956 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001957 };
1958
1959 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1960 operandOkay(node->getFalseBlock()->getAsTyped());
1961 };
1962
1963 // Emit OpSelect for this selection.
1964 const auto handleAsOpSelect = [&]() {
1965 node->getCondition()->traverse(this);
1966 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1967 node->getTrueBlock()->traverse(this);
1968 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1969 node->getFalseBlock()->traverse(this);
1970 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1971
John Kesseniche485c7a2017-05-31 18:50:53 -06001972 builder.setLine(node->getLoc().line);
1973
John Kesseniche434ad92017-03-30 10:09:28 -06001974 // smear condition to vector, if necessary (AST is always scalar)
1975 if (builder.isVector(trueValue))
1976 condition = builder.smearScalar(spv::NoPrecision, condition,
1977 builder.makeVectorType(builder.makeBoolType(),
1978 builder.getNumComponents(trueValue)));
1979
1980 spv::Id select = builder.createTriOp(spv::OpSelect,
1981 convertGlslangToSpvType(node->getType()), condition,
1982 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001983 builder.clearAccessChain();
1984 builder.setAccessChainRValue(select);
1985 };
1986
1987 // Try for OpSelect
1988
1989 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001990 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1991 if (node->getType().getQualifier().isSpecConstant())
1992 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1993
John Kessenich433e9ff2017-01-26 20:31:11 -07001994 handleAsOpSelect();
1995 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001996 }
1997
Rex Xu57e65922017-07-04 23:23:40 +08001998 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07001999 // Don't handle results as temporaries, because there will be two names
2000 // and better to leave SSA to later passes.
2001 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2002 ? spv::NoResult
2003 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2004
John Kessenich140f3df2015-06-26 16:58:36 -06002005 // emit the condition before doing anything with selection
2006 node->getCondition()->traverse(this);
2007
Rex Xu57e65922017-07-04 23:23:40 +08002008 // Selection control:
2009 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2010
John Kessenich140f3df2015-06-26 16:58:36 -06002011 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002012 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002013
John Kessenich433e9ff2017-01-26 20:31:11 -07002014 // emit the "then" statement
2015 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002016 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002017 if (result != spv::NoResult)
2018 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002019 }
2020
John Kessenich433e9ff2017-01-26 20:31:11 -07002021 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002022 ifBuilder.makeBeginElse();
2023 // emit the "else" statement
2024 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002025 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002026 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002027 }
2028
John Kessenich433e9ff2017-01-26 20:31:11 -07002029 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002030 ifBuilder.makeEndIf();
2031
John Kessenich433e9ff2017-01-26 20:31:11 -07002032 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002033 // GLSL only has r-values as the result of a :?, but
2034 // if we have an l-value, that can be more efficient if it will
2035 // become the base of a complex r-value expression, because the
2036 // next layer copies r-values into memory to use the access-chain mechanism
2037 builder.clearAccessChain();
2038 builder.setAccessChainLValue(result);
2039 }
2040
2041 return false;
2042}
2043
2044bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2045{
2046 // emit and get the condition before doing anything with switch
2047 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002048 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002049
Rex Xu57e65922017-07-04 23:23:40 +08002050 // Selection control:
2051 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2052
John Kessenich140f3df2015-06-26 16:58:36 -06002053 // browse the children to sort out code segments
2054 int defaultSegment = -1;
2055 std::vector<TIntermNode*> codeSegments;
2056 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2057 std::vector<int> caseValues;
2058 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2059 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2060 TIntermNode* child = *c;
2061 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002062 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002063 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002064 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002065 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2066 } else
2067 codeSegments.push_back(child);
2068 }
2069
qining25262b32016-05-06 17:25:16 -04002070 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002071 // statements between the last case and the end of the switch statement
2072 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2073 (int)codeSegments.size() == defaultSegment)
2074 codeSegments.push_back(nullptr);
2075
2076 // make the switch statement
2077 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002078 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002079
2080 // emit all the code in the segments
2081 breakForLoop.push(false);
2082 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2083 builder.nextSwitchSegment(segmentBlocks, s);
2084 if (codeSegments[s])
2085 codeSegments[s]->traverse(this);
2086 else
2087 builder.addSwitchBreak();
2088 }
2089 breakForLoop.pop();
2090
2091 builder.endSwitch(segmentBlocks);
2092
2093 return false;
2094}
2095
2096void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2097{
2098 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002099 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002100
2101 builder.clearAccessChain();
2102 builder.setAccessChainRValue(constant);
2103}
2104
2105bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2106{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002107 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002108 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002109
2110 // Loop control:
2111 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2112
2113 // TODO: dependency length
2114
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002115 // Spec requires back edges to target header blocks, and every header block
2116 // must dominate its merge block. Make a header block first to ensure these
2117 // conditions are met. By definition, it will contain OpLoopMerge, followed
2118 // by a block-ending branch. But we don't want to put any other body/test
2119 // instructions in it, since the body/test may have arbitrary instructions,
2120 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002121 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002122 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002123 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002124 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002125 spv::Block& test = builder.makeNewBlock();
2126 builder.createBranch(&test);
2127
2128 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002129 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002130 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002131 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2132
2133 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002134 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002135 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002136 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002137 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002138 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002139
2140 builder.setBuildPoint(&blocks.continue_target);
2141 if (node->getTerminal())
2142 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002143 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002144 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002145 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002146 builder.createBranch(&blocks.body);
2147
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002148 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002149 builder.setBuildPoint(&blocks.body);
2150 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002151 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002152 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002153 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002154
2155 builder.setBuildPoint(&blocks.continue_target);
2156 if (node->getTerminal())
2157 node->getTerminal()->traverse(this);
2158 if (node->getTest()) {
2159 node->getTest()->traverse(this);
2160 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002161 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002162 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002163 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002164 // TODO: unless there was a break/return/discard instruction
2165 // somewhere in the body, this is an infinite loop, so we should
2166 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002167 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002168 }
John Kessenich140f3df2015-06-26 16:58:36 -06002169 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002170 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002171 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002172 return false;
2173}
2174
2175bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2176{
2177 if (node->getExpression())
2178 node->getExpression()->traverse(this);
2179
John Kesseniche485c7a2017-05-31 18:50:53 -06002180 builder.setLine(node->getLoc().line);
2181
John Kessenich140f3df2015-06-26 16:58:36 -06002182 switch (node->getFlowOp()) {
2183 case glslang::EOpKill:
2184 builder.makeDiscard();
2185 break;
2186 case glslang::EOpBreak:
2187 if (breakForLoop.top())
2188 builder.createLoopExit();
2189 else
2190 builder.addSwitchBreak();
2191 break;
2192 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002193 builder.createLoopContinue();
2194 break;
2195 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002196 if (node->getExpression()) {
2197 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2198 spv::Id returnId = accessChainLoad(glslangReturnType);
2199 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2200 builder.clearAccessChain();
2201 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2202 builder.setAccessChainLValue(copyId);
2203 multiTypeStore(glslangReturnType, returnId);
2204 returnId = builder.createLoad(copyId);
2205 }
2206 builder.makeReturn(false, returnId);
2207 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002208 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002209
2210 builder.clearAccessChain();
2211 break;
2212
2213 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002214 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002215 break;
2216 }
2217
2218 return false;
2219}
2220
2221spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2222{
qining25262b32016-05-06 17:25:16 -04002223 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002224 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002225 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002226 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002227 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002228 }
2229
2230 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002231 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002232 spv::Id spvType = convertGlslangToSpvType(node->getType());
2233
Rex Xuf89ad982017-04-07 23:22:33 +08002234#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002235 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2236 node->getType().containsBasicType(glslang::EbtInt16) ||
2237 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002238 if (contains16BitType) {
2239 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2240 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2241 builder.addCapability(spv::CapabilityStorageInputOutput16);
2242 } else if (storageClass == spv::StorageClassPushConstant) {
2243 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2244 builder.addCapability(spv::CapabilityStoragePushConstant16);
2245 } else if (storageClass == spv::StorageClassUniform) {
2246 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2247 builder.addCapability(spv::CapabilityStorageUniform16);
2248 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2249 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2250 }
2251 }
2252#endif
2253
John Kessenich140f3df2015-06-26 16:58:36 -06002254 const char* name = node->getName().c_str();
2255 if (glslang::IsAnonymous(name))
2256 name = "";
2257
2258 return builder.createVariable(storageClass, spvType, name);
2259}
2260
2261// Return type Id of the sampled type.
2262spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2263{
2264 switch (sampler.type) {
2265 case glslang::EbtFloat: return builder.makeFloatType(32);
2266 case glslang::EbtInt: return builder.makeIntType(32);
2267 case glslang::EbtUint: return builder.makeUintType(32);
2268 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002269 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002270 return builder.makeFloatType(32);
2271 }
2272}
2273
John Kessenich8c8505c2016-07-26 12:50:38 -06002274// If node is a swizzle operation, return the type that should be used if
2275// the swizzle base is first consumed by another operation, before the swizzle
2276// is applied.
2277spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2278{
John Kessenichecba76f2017-01-06 00:34:48 -07002279 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002280 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2281 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2282 else
2283 return spv::NoType;
2284}
2285
2286// When inverting a swizzle with a parent op, this function
2287// will apply the swizzle operation to a completed parent operation.
2288spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2289{
2290 std::vector<unsigned> swizzle;
2291 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2292 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2293}
2294
John Kessenich8c8505c2016-07-26 12:50:38 -06002295// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2296void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2297{
2298 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2299 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2300 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2301}
2302
John Kessenich3ac051e2015-12-20 11:29:16 -07002303// Convert from a glslang type to an SPV type, by calling into a
2304// recursive version of this function. This establishes the inherited
2305// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002306spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2307{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002308 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002309}
2310
2311// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002312// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002313// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002314spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002315{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002316 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002317
2318 switch (type.getBasicType()) {
2319 case glslang::EbtVoid:
2320 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002321 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002322 break;
2323 case glslang::EbtFloat:
2324 spvType = builder.makeFloatType(32);
2325 break;
2326 case glslang::EbtDouble:
2327 spvType = builder.makeFloatType(64);
2328 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002329#ifdef AMD_EXTENSIONS
2330 case glslang::EbtFloat16:
2331 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002332 spvType = builder.makeFloatType(16);
2333 break;
2334#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002335 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002336 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2337 // a 32-bit int where non-0 means true.
2338 if (explicitLayout != glslang::ElpNone)
2339 spvType = builder.makeUintType(32);
2340 else
2341 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002342 break;
2343 case glslang::EbtInt:
2344 spvType = builder.makeIntType(32);
2345 break;
2346 case glslang::EbtUint:
2347 spvType = builder.makeUintType(32);
2348 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002349 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002350 spvType = builder.makeIntType(64);
2351 break;
2352 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002353 spvType = builder.makeUintType(64);
2354 break;
Rex Xucabbb782017-03-24 13:41:14 +08002355#ifdef AMD_EXTENSIONS
2356 case glslang::EbtInt16:
2357 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2358 spvType = builder.makeIntType(16);
2359 break;
2360 case glslang::EbtUint16:
2361 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2362 spvType = builder.makeUintType(16);
2363 break;
2364#endif
John Kessenich426394d2015-07-23 10:22:48 -06002365 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002366 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002367 spvType = builder.makeUintType(32);
2368 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002369 case glslang::EbtSampler:
2370 {
2371 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002372 if (sampler.sampler) {
2373 // pure sampler
2374 spvType = builder.makeSamplerType();
2375 } else {
2376 // an image is present, make its type
2377 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2378 sampler.image ? 2 : 1, TranslateImageFormat(type));
2379 if (sampler.combined) {
2380 // already has both image and sampler, make the combined type
2381 spvType = builder.makeSampledImageType(spvType);
2382 }
John Kessenich55e7d112015-11-15 21:33:39 -07002383 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002384 }
John Kessenich140f3df2015-06-26 16:58:36 -06002385 break;
2386 case glslang::EbtStruct:
2387 case glslang::EbtBlock:
2388 {
2389 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002390 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002391
2392 // Try to share structs for different layouts, but not yet for other
2393 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002394 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002395 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002396 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002397 break;
2398
2399 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002400 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002401 memberRemapper[glslangMembers].resize(glslangMembers->size());
2402 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002403 }
2404 break;
2405 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002406 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002407 break;
2408 }
2409
2410 if (type.isMatrix())
2411 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2412 else {
2413 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2414 if (type.getVectorSize() > 1)
2415 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2416 }
2417
2418 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002419 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2420
John Kessenichc9a80832015-09-12 12:17:44 -06002421 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002422 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002423 // We need to decorate array strides for types needing explicit layout, except blocks.
2424 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002425 // Use a dummy glslang type for querying internal strides of
2426 // arrays of arrays, but using just a one-dimensional array.
2427 glslang::TType simpleArrayType(type, 0); // deference type of the array
2428 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2429 simpleArrayType.getArraySizes().dereference();
2430
2431 // Will compute the higher-order strides here, rather than making a whole
2432 // pile of types and doing repetitive recursion on their contents.
2433 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2434 }
John Kessenichf8842e52016-01-04 19:22:56 -07002435
2436 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002437 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002438 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002439 if (stride > 0)
2440 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002441 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002442 }
2443 } else {
2444 // single-dimensional array, and don't yet have stride
2445
John Kessenichf8842e52016-01-04 19:22:56 -07002446 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002447 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2448 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002449 }
John Kessenich31ed4832015-09-09 17:51:38 -06002450
John Kessenichc9a80832015-09-12 12:17:44 -06002451 // Do the outer dimension, which might not be known for a runtime-sized array
2452 if (type.isRuntimeSizedArray()) {
2453 spvType = builder.makeRuntimeArray(spvType);
2454 } else {
2455 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002456 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002457 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002458 if (stride > 0)
2459 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002460 }
2461
2462 return spvType;
2463}
2464
John Kessenich0e737842017-03-24 18:38:16 -06002465// TODO: this functionality should exist at a higher level, in creating the AST
2466//
2467// Identify interface members that don't have their required extension turned on.
2468//
2469bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2470{
2471 auto& extensions = glslangIntermediate->getRequestedExtensions();
2472
Rex Xubcf291a2017-03-29 23:01:36 +08002473 if (member.getFieldName() == "gl_ViewportMask" &&
2474 extensions.find("GL_NV_viewport_array2") == extensions.end())
2475 return true;
2476 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2477 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2478 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002479 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2480 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2481 return true;
2482 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2483 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2484 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002485 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2486 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2487 return true;
John Kessenichd6be6da2017-08-17 23:49:39 -06002488 if ((member.getFieldName() == "gl_ViewportIndex" || member.getFieldName() == "gl_Layer") &&
2489 extensions.find(glslang::E_GL_ARB_shader_viewport_layer_array) == extensions.end() &&
John Kessenich786e8792017-08-19 15:54:49 -06002490 extensions.find("GL_NV_viewport_array2") == extensions.end())
John Kessenichd6be6da2017-08-17 23:49:39 -06002491 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002492
2493 return false;
2494};
2495
John Kessenich6090df02016-06-30 21:18:02 -06002496// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2497// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2498// Mutually recursive with convertGlslangToSpvType().
2499spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2500 const glslang::TTypeList* glslangMembers,
2501 glslang::TLayoutPacking explicitLayout,
2502 const glslang::TQualifier& qualifier)
2503{
2504 // Create a vector of struct types for SPIR-V to consume
2505 std::vector<spv::Id> spvMembers;
2506 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 -06002507 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2508 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2509 if (glslangMember.hiddenMember()) {
2510 ++memberDelta;
2511 if (type.getBasicType() == glslang::EbtBlock)
2512 memberRemapper[glslangMembers][i] = -1;
2513 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002514 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002515 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002516 if (filterMember(glslangMember))
2517 continue;
2518 }
John Kessenich6090df02016-06-30 21:18:02 -06002519 // modify just this child's view of the qualifier
2520 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2521 InheritQualifiers(memberQualifier, qualifier);
2522
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002523 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002524 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002525 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002526
2527 // recurse
2528 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2529 }
2530 }
2531
2532 // Make the SPIR-V type
2533 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002534 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002535 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2536
2537 // Decorate it
2538 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2539
2540 return spvType;
2541}
2542
2543void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2544 const glslang::TTypeList* glslangMembers,
2545 glslang::TLayoutPacking explicitLayout,
2546 const glslang::TQualifier& qualifier,
2547 spv::Id spvType)
2548{
2549 // Name and decorate the non-hidden members
2550 int offset = -1;
2551 int locationOffset = 0; // for use within the members of this struct
2552 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2553 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2554 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002555 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002556 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002557 if (filterMember(glslangMember))
2558 continue;
2559 }
John Kessenich6090df02016-06-30 21:18:02 -06002560
2561 // modify just this child's view of the qualifier
2562 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2563 InheritQualifiers(memberQualifier, qualifier);
2564
2565 // using -1 above to indicate a hidden member
2566 if (member >= 0) {
2567 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2568 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2569 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2570 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002571 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2572 type.getQualifier().storage == glslang::EvqVaryingOut) {
2573 if (type.getBasicType() == glslang::EbtBlock ||
2574 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002575 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2576 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2577 }
2578 }
2579 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2580
Rex Xu286ca432017-07-27 14:33:16 +08002581 if (type.getBasicType() == glslang::EbtBlock &&
2582 qualifier.storage == glslang::EvqBuffer) {
2583 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002584 std::vector<spv::Decoration> memory;
2585 TranslateMemoryDecoration(memberQualifier, memory);
2586 for (unsigned int i = 0; i < memory.size(); ++i)
2587 addMemberDecoration(spvType, member, memory[i]);
2588 }
2589
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002590 // Location assignment was already completed correctly by the front end,
2591 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002592 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002593 // ill-specified and decisions have been made to not allow this.
2594 if (! type.isArray() && memberQualifier.hasLocation())
2595 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002596
John Kessenich2f47bc92016-06-30 21:47:35 -06002597 if (qualifier.hasLocation()) // track for upcoming inheritance
2598 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2599
John Kessenich6090df02016-06-30 21:18:02 -06002600 // component, XFB, others
2601 if (glslangMember.getQualifier().hasComponent())
2602 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2603 if (glslangMember.getQualifier().hasXfbOffset())
2604 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2605 else if (explicitLayout != glslang::ElpNone) {
2606 // figure out what to do with offset, which is accumulating
2607 int nextOffset;
2608 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2609 if (offset >= 0)
2610 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2611 offset = nextOffset;
2612 }
2613
2614 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2615 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2616
2617 // built-in variable decorations
2618 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002619 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002620 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002621
2622#ifdef NV_EXTENSIONS
2623 if (builtIn == spv::BuiltInLayer) {
2624 // SPV_NV_viewport_array2 extension
2625 if (glslangMember.getQualifier().layoutViewportRelative){
2626 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2627 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2628 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2629 }
2630 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2631 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2632 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2633 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2634 }
2635 }
chaocdf3956c2017-02-14 14:52:34 -08002636 if (glslangMember.getQualifier().layoutPassthrough) {
2637 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2638 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2639 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2640 }
chaoc771d89f2017-01-13 01:10:53 -08002641#endif
John Kessenich6090df02016-06-30 21:18:02 -06002642 }
2643 }
2644
2645 // Decorate the structure
2646 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002647 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002648 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2649 builder.addCapability(spv::CapabilityGeometryStreams);
2650 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2651 }
2652 if (glslangIntermediate->getXfbMode()) {
2653 builder.addCapability(spv::CapabilityTransformFeedback);
2654 if (type.getQualifier().hasXfbStride())
2655 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2656 if (type.getQualifier().hasXfbBuffer())
2657 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2658 }
2659}
2660
John Kessenich6c292d32016-02-15 20:58:50 -07002661// Turn the expression forming the array size into an id.
2662// This is not quite trivial, because of specialization constants.
2663// Sometimes, a raw constant is turned into an Id, and sometimes
2664// a specialization constant expression is.
2665spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2666{
2667 // First, see if this is sized with a node, meaning a specialization constant:
2668 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2669 if (specNode != nullptr) {
2670 builder.clearAccessChain();
2671 specNode->traverse(this);
2672 return accessChainLoad(specNode->getAsTyped()->getType());
2673 }
qining25262b32016-05-06 17:25:16 -04002674
John Kessenich6c292d32016-02-15 20:58:50 -07002675 // Otherwise, need a compile-time (front end) size, get it:
2676 int size = arraySizes.getDimSize(dim);
2677 assert(size > 0);
2678 return builder.makeUintConstant(size);
2679}
2680
John Kessenich103bef92016-02-08 21:38:15 -07002681// Wrap the builder's accessChainLoad to:
2682// - localize handling of RelaxedPrecision
2683// - use the SPIR-V inferred type instead of another conversion of the glslang type
2684// (avoids unnecessary work and possible type punning for structures)
2685// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002686spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2687{
John Kessenich103bef92016-02-08 21:38:15 -07002688 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2689 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2690
2691 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002692 if (type.getBasicType() == glslang::EbtBool) {
2693 if (builder.isScalarType(nominalTypeId)) {
2694 // Conversion for bool
2695 spv::Id boolType = builder.makeBoolType();
2696 if (nominalTypeId != boolType)
2697 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2698 } else if (builder.isVectorType(nominalTypeId)) {
2699 // Conversion for bvec
2700 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2701 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2702 if (nominalTypeId != bvecType)
2703 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2704 }
2705 }
John Kessenich103bef92016-02-08 21:38:15 -07002706
2707 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002708}
2709
Rex Xu27253232016-02-23 17:51:09 +08002710// Wrap the builder's accessChainStore to:
2711// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002712//
2713// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002714void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2715{
2716 // Need to convert to abstract types when necessary
2717 if (type.getBasicType() == glslang::EbtBool) {
2718 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2719
2720 if (builder.isScalarType(nominalTypeId)) {
2721 // Conversion for bool
2722 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002723 if (nominalTypeId != boolType) {
2724 // keep these outside arguments, for determinant order-of-evaluation
2725 spv::Id one = builder.makeUintConstant(1);
2726 spv::Id zero = builder.makeUintConstant(0);
2727 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2728 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002729 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002730 } else if (builder.isVectorType(nominalTypeId)) {
2731 // Conversion for bvec
2732 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2733 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002734 if (nominalTypeId != bvecType) {
2735 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002736 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2737 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2738 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002739 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002740 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2741 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002742 }
2743 }
2744
2745 builder.accessChainStore(rvalue);
2746}
2747
John Kessenich4bf71552016-09-02 11:20:21 -06002748// For storing when types match at the glslang level, but not might match at the
2749// SPIR-V level.
2750//
2751// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002752// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002753// as in a member-decorated way.
2754//
2755// NOTE: This function can handle any store request; if it's not special it
2756// simplifies to a simple OpStore.
2757//
2758// Implicitly uses the existing builder.accessChain as the storage target.
2759void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2760{
John Kessenichb3e24e42016-09-11 12:33:43 -06002761 // we only do the complex path here if it's an aggregate
2762 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002763 accessChainStore(type, rValue);
2764 return;
2765 }
2766
John Kessenichb3e24e42016-09-11 12:33:43 -06002767 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002768 spv::Id rType = builder.getTypeId(rValue);
2769 spv::Id lValue = builder.accessChainGetLValue();
2770 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2771 if (lType == rType) {
2772 accessChainStore(type, rValue);
2773 return;
2774 }
2775
John Kessenichb3e24e42016-09-11 12:33:43 -06002776 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002777 // where the two types were the same type in GLSL. This requires member
2778 // by member copy, recursively.
2779
John Kessenichb3e24e42016-09-11 12:33:43 -06002780 // If an array, copy element by element.
2781 if (type.isArray()) {
2782 glslang::TType glslangElementType(type, 0);
2783 spv::Id elementRType = builder.getContainedTypeId(rType);
2784 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2785 // get the source member
2786 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002787
John Kessenichb3e24e42016-09-11 12:33:43 -06002788 // set up the target storage
2789 builder.clearAccessChain();
2790 builder.setAccessChainLValue(lValue);
2791 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002792
John Kessenichb3e24e42016-09-11 12:33:43 -06002793 // store the member
2794 multiTypeStore(glslangElementType, elementRValue);
2795 }
2796 } else {
2797 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002798
John Kessenichb3e24e42016-09-11 12:33:43 -06002799 // loop over structure members
2800 const glslang::TTypeList& members = *type.getStruct();
2801 for (int m = 0; m < (int)members.size(); ++m) {
2802 const glslang::TType& glslangMemberType = *members[m].type;
2803
2804 // get the source member
2805 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2806 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2807
2808 // set up the target storage
2809 builder.clearAccessChain();
2810 builder.setAccessChainLValue(lValue);
2811 builder.accessChainPush(builder.makeIntConstant(m));
2812
2813 // store the member
2814 multiTypeStore(glslangMemberType, memberRValue);
2815 }
John Kessenich4bf71552016-09-02 11:20:21 -06002816 }
2817}
2818
John Kessenichf85e8062015-12-19 13:57:10 -07002819// Decide whether or not this type should be
2820// decorated with offsets and strides, and if so
2821// whether std140 or std430 rules should be applied.
2822glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002823{
John Kessenichf85e8062015-12-19 13:57:10 -07002824 // has to be a block
2825 if (type.getBasicType() != glslang::EbtBlock)
2826 return glslang::ElpNone;
2827
2828 // has to be a uniform or buffer block
2829 if (type.getQualifier().storage != glslang::EvqUniform &&
2830 type.getQualifier().storage != glslang::EvqBuffer)
2831 return glslang::ElpNone;
2832
2833 // return the layout to use
2834 switch (type.getQualifier().layoutPacking) {
2835 case glslang::ElpStd140:
2836 case glslang::ElpStd430:
2837 return type.getQualifier().layoutPacking;
2838 default:
2839 return glslang::ElpNone;
2840 }
John Kessenich31ed4832015-09-09 17:51:38 -06002841}
2842
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002843// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002844int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002845{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002846 int size;
John Kessenich49987892015-12-29 17:11:44 -07002847 int stride;
2848 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002849
2850 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002851}
2852
John Kessenich49987892015-12-29 17:11:44 -07002853// 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 -07002854// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002855int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002856{
John Kessenich49987892015-12-29 17:11:44 -07002857 glslang::TType elementType;
2858 elementType.shallowCopy(matrixType);
2859 elementType.clearArraySizes();
2860
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002861 int size;
John Kessenich49987892015-12-29 17:11:44 -07002862 int stride;
2863 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2864
2865 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002866}
2867
John Kessenich5e4b1242015-08-06 22:53:06 -06002868// Given a member type of a struct, realign the current offset for it, and compute
2869// the next (not yet aligned) offset for the next member, which will get aligned
2870// on the next call.
2871// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2872// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2873// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002874void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002875 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002876{
2877 // this will get a positive value when deemed necessary
2878 nextOffset = -1;
2879
John Kessenich5e4b1242015-08-06 22:53:06 -06002880 // override anything in currentOffset with user-set offset
2881 if (memberType.getQualifier().hasOffset())
2882 currentOffset = memberType.getQualifier().layoutOffset;
2883
2884 // It could be that current linker usage in glslang updated all the layoutOffset,
2885 // in which case the following code does not matter. But, that's not quite right
2886 // once cross-compilation unit GLSL validation is done, as the original user
2887 // settings are needed in layoutOffset, and then the following will come into play.
2888
John Kessenichf85e8062015-12-19 13:57:10 -07002889 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002890 if (! memberType.getQualifier().hasOffset())
2891 currentOffset = -1;
2892
2893 return;
2894 }
2895
John Kessenichf85e8062015-12-19 13:57:10 -07002896 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002897 if (currentOffset < 0)
2898 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002899
John Kessenich5e4b1242015-08-06 22:53:06 -06002900 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2901 // but possibly not yet correctly aligned.
2902
2903 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002904 int dummyStride;
2905 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002906
2907 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002908 // TODO: make this consistent in early phases of code:
2909 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2910 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2911 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002912 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002913 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002914 int dummySize;
2915 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2916 if (componentAlignment <= 4)
2917 memberAlignment = componentAlignment;
2918 }
2919
2920 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002921 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002922
2923 // Bump up to vec4 if there is a bad straddle
2924 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2925 glslang::RoundToPow2(currentOffset, 16);
2926
John Kessenich5e4b1242015-08-06 22:53:06 -06002927 nextOffset = currentOffset + memberSize;
2928}
2929
David Netoa901ffe2016-06-08 14:11:40 +01002930void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002931{
David Netoa901ffe2016-06-08 14:11:40 +01002932 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2933 switch (glslangBuiltIn)
2934 {
2935 case glslang::EbvClipDistance:
2936 case glslang::EbvCullDistance:
2937 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002938#ifdef NV_EXTENSIONS
2939 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002940 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002941 case glslang::EbvViewportMaskNV:
2942 case glslang::EbvSecondaryPositionNV:
2943 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002944 case glslang::EbvPositionPerViewNV:
2945 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002946#endif
David Netoa901ffe2016-06-08 14:11:40 +01002947 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2948 // Alternately, we could just call this for any glslang built-in, since the
2949 // capability already guards against duplicates.
2950 TranslateBuiltInDecoration(glslangBuiltIn, false);
2951 break;
2952 default:
2953 // Capabilities were already generated when the struct was declared.
2954 break;
2955 }
John Kessenichebb50532016-05-16 19:22:05 -06002956}
2957
John Kessenich6fccb3c2016-09-19 16:01:41 -06002958bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002959{
John Kessenicheee9d532016-09-19 18:09:30 -06002960 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002961}
2962
2963// Make all the functions, skeletally, without actually visiting their bodies.
2964void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2965{
John Kessenichfad62972017-07-18 02:35:46 -06002966 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2967 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2968 if (paramPrecision != spv::NoPrecision)
2969 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002970 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002971 };
2972
John Kessenich140f3df2015-06-26 16:58:36 -06002973 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2974 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002975 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002976 continue;
2977
2978 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002979 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002980 //
qining25262b32016-05-06 17:25:16 -04002981 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002982 // function. What it is an address of varies:
2983 //
John Kessenich4bf71552016-09-02 11:20:21 -06002984 // - "in" parameters not marked as "const" can be written to without modifying the calling
2985 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002986 //
2987 // - "const in" parameters can just be the r-value, as no writes need occur.
2988 //
John Kessenich4bf71552016-09-02 11:20:21 -06002989 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2990 // 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 -06002991
2992 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002993 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002994 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2995
John Kessenichfad62972017-07-18 02:35:46 -06002996 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2997 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002998
John Kessenichfad62972017-07-18 02:35:46 -06002999 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003000 for (int p = 0; p < (int)parameters.size(); ++p) {
3001 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3002 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06003003 // can we pass by reference?
3004 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06003005 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06003006 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06003007 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06003008 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07003009 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003010 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3011 else
John Kessenich4bf71552016-09-02 11:20:21 -06003012 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003013 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003014 paramTypes.push_back(typeId);
3015 }
3016
3017 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003018 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3019 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003020 glslFunction->getName().c_str(), paramTypes,
3021 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003022 if (implicitThis)
3023 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003024
3025 // Track function to emit/call later
3026 functionMap[glslFunction->getName().c_str()] = function;
3027
3028 // Set the parameter id's
3029 for (int p = 0; p < (int)parameters.size(); ++p) {
3030 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3031 // give a name too
3032 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3033 }
3034 }
3035}
3036
3037// Process all the initializers, while skipping the functions and link objects
3038void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3039{
3040 builder.setBuildPoint(shaderEntry->getLastBlock());
3041 for (int i = 0; i < (int)initializers.size(); ++i) {
3042 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3043 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3044
3045 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003046 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003047 initializer->traverse(this);
3048 }
3049 }
3050}
3051
3052// Process all the functions, while skipping initializers.
3053void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3054{
3055 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3056 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003057 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003058 node->traverse(this);
3059 }
3060}
3061
3062void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3063{
qining25262b32016-05-06 17:25:16 -04003064 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003065 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003066 currentFunction = functionMap[node->getName().c_str()];
3067 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003068 builder.setBuildPoint(functionBlock);
3069}
3070
Rex Xu04db3f52015-09-16 11:44:02 +08003071void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003072{
Rex Xufc618912015-09-09 16:42:49 +08003073 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003074
3075 glslang::TSampler sampler = {};
3076 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003077 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003078 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3079 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3080 }
3081
John Kessenich140f3df2015-06-26 16:58:36 -06003082 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3083 builder.clearAccessChain();
3084 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003085
3086 // Special case l-value operands
3087 bool lvalue = false;
3088 switch (node.getOp()) {
3089 case glslang::EOpImageAtomicAdd:
3090 case glslang::EOpImageAtomicMin:
3091 case glslang::EOpImageAtomicMax:
3092 case glslang::EOpImageAtomicAnd:
3093 case glslang::EOpImageAtomicOr:
3094 case glslang::EOpImageAtomicXor:
3095 case glslang::EOpImageAtomicExchange:
3096 case glslang::EOpImageAtomicCompSwap:
3097 if (i == 0)
3098 lvalue = true;
3099 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003100 case glslang::EOpSparseImageLoad:
3101 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3102 lvalue = true;
3103 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003104 case glslang::EOpSparseTexture:
3105 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3106 lvalue = true;
3107 break;
3108 case glslang::EOpSparseTextureClamp:
3109 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3110 lvalue = true;
3111 break;
3112 case glslang::EOpSparseTextureLod:
3113 case glslang::EOpSparseTextureOffset:
3114 if (i == 3)
3115 lvalue = true;
3116 break;
3117 case glslang::EOpSparseTextureFetch:
3118 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3119 lvalue = true;
3120 break;
3121 case glslang::EOpSparseTextureFetchOffset:
3122 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3123 lvalue = true;
3124 break;
3125 case glslang::EOpSparseTextureLodOffset:
3126 case glslang::EOpSparseTextureGrad:
3127 case glslang::EOpSparseTextureOffsetClamp:
3128 if (i == 4)
3129 lvalue = true;
3130 break;
3131 case glslang::EOpSparseTextureGradOffset:
3132 case glslang::EOpSparseTextureGradClamp:
3133 if (i == 5)
3134 lvalue = true;
3135 break;
3136 case glslang::EOpSparseTextureGradOffsetClamp:
3137 if (i == 6)
3138 lvalue = true;
3139 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003140 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003141 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3142 lvalue = true;
3143 break;
3144 case glslang::EOpSparseTextureGatherOffset:
3145 case glslang::EOpSparseTextureGatherOffsets:
3146 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3147 lvalue = true;
3148 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003149#ifdef AMD_EXTENSIONS
3150 case glslang::EOpSparseTextureGatherLod:
3151 if (i == 3)
3152 lvalue = true;
3153 break;
3154 case glslang::EOpSparseTextureGatherLodOffset:
3155 case glslang::EOpSparseTextureGatherLodOffsets:
3156 if (i == 4)
3157 lvalue = true;
3158 break;
Rex Xu129799a2017-07-05 17:23:28 +08003159 case glslang::EOpSparseImageLoadLod:
3160 if (i == 3)
3161 lvalue = true;
3162 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003163#endif
Rex Xufc618912015-09-09 16:42:49 +08003164 default:
3165 break;
3166 }
3167
Rex Xu6b86d492015-09-16 17:48:22 +08003168 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003169 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003170 else
John Kessenich32cfd492016-02-02 12:37:46 -07003171 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003172 }
3173}
3174
John Kessenichfc51d282015-08-19 13:34:18 -06003175void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003176{
John Kessenichfc51d282015-08-19 13:34:18 -06003177 builder.clearAccessChain();
3178 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003179 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003180}
John Kessenich140f3df2015-06-26 16:58:36 -06003181
John Kessenichfc51d282015-08-19 13:34:18 -06003182spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3183{
John Kesseniche485c7a2017-05-31 18:50:53 -06003184 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003185 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003186
3187 builder.setLine(node->getLoc().line);
3188
John Kessenich8c8505c2016-07-26 12:50:38 -06003189 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003190
John Kessenichfc51d282015-08-19 13:34:18 -06003191 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003192 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3193 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3194 std::vector<spv::Id> arguments;
3195 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003196 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003197 else
3198 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003199 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003200
3201 spv::Builder::TextureParameters params = { };
3202 params.sampler = arguments[0];
3203
Rex Xu04db3f52015-09-16 11:44:02 +08003204 glslang::TCrackedTextureOp cracked;
3205 node->crackTexture(sampler, cracked);
3206
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003207 const bool isUnsignedResult =
3208 node->getType().getBasicType() == glslang::EbtUint64 ||
3209 node->getType().getBasicType() == glslang::EbtUint;
3210
John Kessenichfc51d282015-08-19 13:34:18 -06003211 // Check for queries
3212 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003213 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3214 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003215 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003216
John Kessenichfc51d282015-08-19 13:34:18 -06003217 switch (node->getOp()) {
3218 case glslang::EOpImageQuerySize:
3219 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003220 if (arguments.size() > 1) {
3221 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003222 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003223 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003224 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003225 case glslang::EOpImageQuerySamples:
3226 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003227 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003228 case glslang::EOpTextureQueryLod:
3229 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003230 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003231 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003232 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003233 case glslang::EOpSparseTexelsResident:
3234 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003235 default:
3236 assert(0);
3237 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003238 }
John Kessenich140f3df2015-06-26 16:58:36 -06003239 }
3240
Rex Xufc618912015-09-09 16:42:49 +08003241 // Check for image functions other than queries
3242 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003243 std::vector<spv::Id> operands;
3244 auto opIt = arguments.begin();
3245 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003246
3247 // Handle subpass operations
3248 // TODO: GLSL should change to have the "MS" only on the type rather than the
3249 // built-in function.
3250 if (cracked.subpass) {
3251 // add on the (0,0) coordinate
3252 spv::Id zero = builder.makeIntConstant(0);
3253 std::vector<spv::Id> comps;
3254 comps.push_back(zero);
3255 comps.push_back(zero);
3256 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3257 if (sampler.ms) {
3258 operands.push_back(spv::ImageOperandsSampleMask);
3259 operands.push_back(*(opIt++));
3260 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003261 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003262 }
3263
John Kessenich56bab042015-09-16 10:54:31 -06003264 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003265#ifdef AMD_EXTENSIONS
3266 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3267#else
John Kessenich56bab042015-09-16 10:54:31 -06003268 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003269#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003270 if (sampler.ms) {
3271 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003272 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003273#ifdef AMD_EXTENSIONS
3274 } else if (cracked.lod) {
3275 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3276 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3277
3278 operands.push_back(spv::ImageOperandsLodMask);
3279 operands.push_back(*opIt);
3280#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003281 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003282 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3283 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003284 return builder.createOp(spv::OpImageRead, resultType(), operands);
Rex Xu129799a2017-07-05 17:23:28 +08003285#ifdef AMD_EXTENSIONS
3286 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3287#else
John Kessenich56bab042015-09-16 10:54:31 -06003288 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003289#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003290 if (sampler.ms) {
3291 operands.push_back(*(opIt + 1));
3292 operands.push_back(spv::ImageOperandsSampleMask);
3293 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003294#ifdef AMD_EXTENSIONS
3295 } else if (cracked.lod) {
3296 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3297 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3298
3299 operands.push_back(*(opIt + 1));
3300 operands.push_back(spv::ImageOperandsLodMask);
3301 operands.push_back(*opIt);
3302#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003303 } else
3304 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003305 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003306 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3307 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003308 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003309#ifdef AMD_EXTENSIONS
3310 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3311#else
Rex Xu5eafa472016-02-19 22:24:03 +08003312 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003313#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003314 builder.addCapability(spv::CapabilitySparseResidency);
3315 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3316 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3317
3318 if (sampler.ms) {
3319 operands.push_back(spv::ImageOperandsSampleMask);
3320 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003321#ifdef AMD_EXTENSIONS
3322 } else if (cracked.lod) {
3323 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3324 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3325
3326 operands.push_back(spv::ImageOperandsLodMask);
3327 operands.push_back(*opIt++);
3328#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003329 }
3330
3331 // Create the return type that was a special structure
3332 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003333 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003334 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3335 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3336
3337 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3338
3339 // Decode the return type
3340 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3341 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003342 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003343 // Process image atomic operations
3344
3345 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3346 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003347 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003348
John Kessenich8c8505c2016-07-26 12:50:38 -06003349 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003350 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003351
3352 std::vector<spv::Id> operands;
3353 operands.push_back(pointer);
3354 for (; opIt != arguments.end(); ++opIt)
3355 operands.push_back(*opIt);
3356
John Kessenich8c8505c2016-07-26 12:50:38 -06003357 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003358 }
3359 }
3360
3361 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003362 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003363 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3364
John Kessenichfc51d282015-08-19 13:34:18 -06003365 // check for bias argument
3366 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003367#ifdef AMD_EXTENSIONS
3368 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3369#else
Rex Xu71519fe2015-11-11 15:35:47 +08003370 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003371#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003372 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003373#ifdef AMD_EXTENSIONS
3374 if (cracked.gather)
3375 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3376#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003377 if (cracked.offset)
3378 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003379#ifdef AMD_EXTENSIONS
3380 else if (cracked.offsets)
3381 ++nonBiasArgCount;
3382#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003383 if (cracked.grad)
3384 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003385 if (cracked.lodClamp)
3386 ++nonBiasArgCount;
3387 if (sparse)
3388 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003389
3390 if ((int)arguments.size() > nonBiasArgCount)
3391 bias = true;
3392 }
3393
John Kessenicha5c33d62016-06-02 23:45:21 -06003394 // See if the sampler param should really be just the SPV image part
3395 if (cracked.fetch) {
3396 // a fetch needs to have the image extracted first
3397 if (builder.isSampledImage(params.sampler))
3398 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3399 }
3400
Rex Xu225e0fc2016-11-17 17:47:59 +08003401#ifdef AMD_EXTENSIONS
3402 if (cracked.gather) {
3403 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3404 if (bias || cracked.lod ||
3405 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3406 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003407 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003408 }
3409 }
3410#endif
3411
John Kessenichfc51d282015-08-19 13:34:18 -06003412 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003413
John Kessenichfc51d282015-08-19 13:34:18 -06003414 params.coords = arguments[1];
3415 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003416 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003417
3418 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003419 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003420 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003421 ++extraArgs;
3422 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003423 params.Dref = arguments[2];
3424 ++extraArgs;
3425 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003426 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003427 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003428 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003429 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003430 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003431 dRefComp = builder.getNumComponents(params.coords) - 1;
3432 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003433 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3434 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003435
3436 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003437 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003438 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003439 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003440 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3441 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3442 noImplicitLod = true;
3443 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003444
3445 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003446 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003447 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003448 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003449 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003450
3451 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003452 if (cracked.grad) {
3453 params.gradX = arguments[2 + extraArgs];
3454 params.gradY = arguments[3 + extraArgs];
3455 extraArgs += 2;
3456 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003457
3458 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003459 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003460 params.offset = arguments[2 + extraArgs];
3461 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003462 } else if (cracked.offsets) {
3463 params.offsets = arguments[2 + extraArgs];
3464 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003465 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003466
3467 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003468 if (cracked.lodClamp) {
3469 params.lodClamp = arguments[2 + extraArgs];
3470 ++extraArgs;
3471 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003472
3473 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003474 if (sparse) {
3475 params.texelOut = arguments[2 + extraArgs];
3476 ++extraArgs;
3477 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003478
John Kessenich76d4dfc2016-06-16 12:43:23 -06003479 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003480 if (cracked.gather && ! sampler.shadow) {
3481 // default component is 0, if missing, otherwise an argument
3482 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003483 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003484 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003485 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003486 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003487 }
3488
3489 // bias
3490 if (bias) {
3491 params.bias = arguments[2 + extraArgs];
3492 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003493 }
John Kessenichfc51d282015-08-19 13:34:18 -06003494
John Kessenich65336482016-06-16 14:06:26 -06003495 // projective component (might not to move)
3496 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3497 // are divided by the last component of P."
3498 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3499 // unused components will appear after all used components."
3500 if (cracked.proj) {
3501 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3502 int projTargetComp;
3503 switch (sampler.dim) {
3504 case glslang::Esd1D: projTargetComp = 1; break;
3505 case glslang::Esd2D: projTargetComp = 2; break;
3506 case glslang::EsdRect: projTargetComp = 2; break;
3507 default: projTargetComp = projSourceComp; break;
3508 }
3509 // copy the projective coordinate if we have to
3510 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003511 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003512 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3513 projSourceComp);
3514 params.coords = builder.createCompositeInsert(projComp, params.coords,
3515 builder.getTypeId(params.coords), projTargetComp);
3516 }
3517 }
3518
John Kessenich8c8505c2016-07-26 12:50:38 -06003519 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003520}
3521
3522spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3523{
3524 // Grab the function's pointer from the previously created function
3525 spv::Function* function = functionMap[node->getName().c_str()];
3526 if (! function)
3527 return 0;
3528
3529 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3530 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3531
LoopDawg76117922017-09-06 14:59:06 -06003532 // Encapsulate lvalue logic, used in two places below, for safety.
3533 const auto isLValue = [](int qualifier, const glslang::TType& paramType) -> bool {
3534 return qualifier != glslang::EvqConstReadOnly || paramType.containsOpaque();
3535 };
3536
John Kessenich140f3df2015-06-26 16:58:36 -06003537 // See comments in makeFunctions() for details about the semantics for parameter passing.
3538 //
3539 // These imply we need a four step process:
3540 // 1. Evaluate the arguments
3541 // 2. Allocate and make copies of in, out, and inout arguments
3542 // 3. Make the call
3543 // 4. Copy back the results
3544
3545 // 1. Evaluate the arguments
3546 std::vector<spv::Builder::AccessChain> lValues;
3547 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003548 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003549 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003550 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003551 // build l-value
3552 builder.clearAccessChain();
3553 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003554 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003555 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
LoopDawg76117922017-09-06 14:59:06 -06003556 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003557 // save l-value
3558 lValues.push_back(builder.getAccessChain());
3559 } else {
3560 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003561 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003562 }
3563 }
3564
3565 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3566 // copy the original into that space.
3567 //
3568 // Also, build up the list of actual arguments to pass in for the call
3569 int lValueCount = 0;
3570 int rValueCount = 0;
3571 std::vector<spv::Id> spvArgs;
3572 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003573 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003574 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003575 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003576 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3577 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003578 builder.setAccessChain(lValues[lValueCount]);
3579 arg = builder.accessChainGetLValue();
3580 ++lValueCount;
LoopDawg76117922017-09-06 14:59:06 -06003581 } else if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003582 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003583 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3584 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3585 // need to copy the input into output space
3586 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003587 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003588 builder.clearAccessChain();
3589 builder.setAccessChainLValue(arg);
3590 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003591 }
3592 ++lValueCount;
3593 } else {
3594 arg = rValues[rValueCount];
3595 ++rValueCount;
3596 }
3597 spvArgs.push_back(arg);
3598 }
3599
3600 // 3. Make the call.
3601 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003602 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003603
3604 // 4. Copy back out an "out" arguments.
3605 lValueCount = 0;
3606 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003607 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
LoopDawg76117922017-09-06 14:59:06 -06003608 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003609 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3610 spv::Id copy = builder.createLoad(spvArgs[a]);
3611 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003612 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003613 }
3614 ++lValueCount;
3615 }
3616 }
3617
3618 return result;
3619}
3620
3621// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003622spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3623 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003624 spv::Id typeId, spv::Id left, spv::Id right,
3625 glslang::TBasicType typeProxy, bool reduceComparison)
3626{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003627#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003628 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003629 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3630#else
Rex Xucabbb782017-03-24 13:41:14 +08003631 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003632 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003633#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003634 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003635
3636 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003637 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003638 bool comparison = false;
3639
3640 switch (op) {
3641 case glslang::EOpAdd:
3642 case glslang::EOpAddAssign:
3643 if (isFloat)
3644 binOp = spv::OpFAdd;
3645 else
3646 binOp = spv::OpIAdd;
3647 break;
3648 case glslang::EOpSub:
3649 case glslang::EOpSubAssign:
3650 if (isFloat)
3651 binOp = spv::OpFSub;
3652 else
3653 binOp = spv::OpISub;
3654 break;
3655 case glslang::EOpMul:
3656 case glslang::EOpMulAssign:
3657 if (isFloat)
3658 binOp = spv::OpFMul;
3659 else
3660 binOp = spv::OpIMul;
3661 break;
3662 case glslang::EOpVectorTimesScalar:
3663 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003664 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003665 if (builder.isVector(right))
3666 std::swap(left, right);
3667 assert(builder.isScalar(right));
3668 needMatchingVectors = false;
3669 binOp = spv::OpVectorTimesScalar;
3670 } else
3671 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003672 break;
3673 case glslang::EOpVectorTimesMatrix:
3674 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003675 binOp = spv::OpVectorTimesMatrix;
3676 break;
3677 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003678 binOp = spv::OpMatrixTimesVector;
3679 break;
3680 case glslang::EOpMatrixTimesScalar:
3681 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003682 binOp = spv::OpMatrixTimesScalar;
3683 break;
3684 case glslang::EOpMatrixTimesMatrix:
3685 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003686 binOp = spv::OpMatrixTimesMatrix;
3687 break;
3688 case glslang::EOpOuterProduct:
3689 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003690 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003691 break;
3692
3693 case glslang::EOpDiv:
3694 case glslang::EOpDivAssign:
3695 if (isFloat)
3696 binOp = spv::OpFDiv;
3697 else if (isUnsigned)
3698 binOp = spv::OpUDiv;
3699 else
3700 binOp = spv::OpSDiv;
3701 break;
3702 case glslang::EOpMod:
3703 case glslang::EOpModAssign:
3704 if (isFloat)
3705 binOp = spv::OpFMod;
3706 else if (isUnsigned)
3707 binOp = spv::OpUMod;
3708 else
3709 binOp = spv::OpSMod;
3710 break;
3711 case glslang::EOpRightShift:
3712 case glslang::EOpRightShiftAssign:
3713 if (isUnsigned)
3714 binOp = spv::OpShiftRightLogical;
3715 else
3716 binOp = spv::OpShiftRightArithmetic;
3717 break;
3718 case glslang::EOpLeftShift:
3719 case glslang::EOpLeftShiftAssign:
3720 binOp = spv::OpShiftLeftLogical;
3721 break;
3722 case glslang::EOpAnd:
3723 case glslang::EOpAndAssign:
3724 binOp = spv::OpBitwiseAnd;
3725 break;
3726 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003727 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003728 binOp = spv::OpLogicalAnd;
3729 break;
3730 case glslang::EOpInclusiveOr:
3731 case glslang::EOpInclusiveOrAssign:
3732 binOp = spv::OpBitwiseOr;
3733 break;
3734 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003735 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003736 binOp = spv::OpLogicalOr;
3737 break;
3738 case glslang::EOpExclusiveOr:
3739 case glslang::EOpExclusiveOrAssign:
3740 binOp = spv::OpBitwiseXor;
3741 break;
3742 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003743 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003744 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003745 break;
3746
3747 case glslang::EOpLessThan:
3748 case glslang::EOpGreaterThan:
3749 case glslang::EOpLessThanEqual:
3750 case glslang::EOpGreaterThanEqual:
3751 case glslang::EOpEqual:
3752 case glslang::EOpNotEqual:
3753 case glslang::EOpVectorEqual:
3754 case glslang::EOpVectorNotEqual:
3755 comparison = true;
3756 break;
3757 default:
3758 break;
3759 }
3760
John Kessenich7c1aa102015-10-15 13:29:11 -06003761 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003762 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003763 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003764 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003765 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003766
3767 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003768 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003769 builder.promoteScalar(precision, left, right);
3770
qining25262b32016-05-06 17:25:16 -04003771 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3772 addDecoration(result, noContraction);
3773 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003774 }
3775
3776 if (! comparison)
3777 return 0;
3778
John Kessenich7c1aa102015-10-15 13:29:11 -06003779 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003780
John Kessenich4583b612016-08-07 19:14:22 -06003781 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3782 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003783 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003784
3785 switch (op) {
3786 case glslang::EOpLessThan:
3787 if (isFloat)
3788 binOp = spv::OpFOrdLessThan;
3789 else if (isUnsigned)
3790 binOp = spv::OpULessThan;
3791 else
3792 binOp = spv::OpSLessThan;
3793 break;
3794 case glslang::EOpGreaterThan:
3795 if (isFloat)
3796 binOp = spv::OpFOrdGreaterThan;
3797 else if (isUnsigned)
3798 binOp = spv::OpUGreaterThan;
3799 else
3800 binOp = spv::OpSGreaterThan;
3801 break;
3802 case glslang::EOpLessThanEqual:
3803 if (isFloat)
3804 binOp = spv::OpFOrdLessThanEqual;
3805 else if (isUnsigned)
3806 binOp = spv::OpULessThanEqual;
3807 else
3808 binOp = spv::OpSLessThanEqual;
3809 break;
3810 case glslang::EOpGreaterThanEqual:
3811 if (isFloat)
3812 binOp = spv::OpFOrdGreaterThanEqual;
3813 else if (isUnsigned)
3814 binOp = spv::OpUGreaterThanEqual;
3815 else
3816 binOp = spv::OpSGreaterThanEqual;
3817 break;
3818 case glslang::EOpEqual:
3819 case glslang::EOpVectorEqual:
3820 if (isFloat)
3821 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003822 else if (isBool)
3823 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003824 else
3825 binOp = spv::OpIEqual;
3826 break;
3827 case glslang::EOpNotEqual:
3828 case glslang::EOpVectorNotEqual:
3829 if (isFloat)
3830 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003831 else if (isBool)
3832 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003833 else
3834 binOp = spv::OpINotEqual;
3835 break;
3836 default:
3837 break;
3838 }
3839
qining25262b32016-05-06 17:25:16 -04003840 if (binOp != spv::OpNop) {
3841 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3842 addDecoration(result, noContraction);
3843 return builder.setPrecision(result, precision);
3844 }
John Kessenich140f3df2015-06-26 16:58:36 -06003845
3846 return 0;
3847}
3848
John Kessenich04bb8a02015-12-12 12:28:14 -07003849//
3850// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3851// These can be any of:
3852//
3853// matrix * scalar
3854// scalar * matrix
3855// matrix * matrix linear algebraic
3856// matrix * vector
3857// vector * matrix
3858// matrix * matrix componentwise
3859// matrix op matrix op in {+, -, /}
3860// matrix op scalar op in {+, -, /}
3861// scalar op matrix op in {+, -, /}
3862//
qining25262b32016-05-06 17:25:16 -04003863spv::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 -07003864{
3865 bool firstClass = true;
3866
3867 // First, handle first-class matrix operations (* and matrix/scalar)
3868 switch (op) {
3869 case spv::OpFDiv:
3870 if (builder.isMatrix(left) && builder.isScalar(right)) {
3871 // turn matrix / scalar into a multiply...
3872 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3873 op = spv::OpMatrixTimesScalar;
3874 } else
3875 firstClass = false;
3876 break;
3877 case spv::OpMatrixTimesScalar:
3878 if (builder.isMatrix(right))
3879 std::swap(left, right);
3880 assert(builder.isScalar(right));
3881 break;
3882 case spv::OpVectorTimesMatrix:
3883 assert(builder.isVector(left));
3884 assert(builder.isMatrix(right));
3885 break;
3886 case spv::OpMatrixTimesVector:
3887 assert(builder.isMatrix(left));
3888 assert(builder.isVector(right));
3889 break;
3890 case spv::OpMatrixTimesMatrix:
3891 assert(builder.isMatrix(left));
3892 assert(builder.isMatrix(right));
3893 break;
3894 default:
3895 firstClass = false;
3896 break;
3897 }
3898
qining25262b32016-05-06 17:25:16 -04003899 if (firstClass) {
3900 spv::Id result = builder.createBinOp(op, typeId, left, right);
3901 addDecoration(result, noContraction);
3902 return builder.setPrecision(result, precision);
3903 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003904
LoopDawg592860c2016-06-09 08:57:35 -06003905 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003906 // The result type of all of them is the same type as the (a) matrix operand.
3907 // The algorithm is to:
3908 // - break the matrix(es) into vectors
3909 // - smear any scalar to a vector
3910 // - do vector operations
3911 // - make a matrix out the vector results
3912 switch (op) {
3913 case spv::OpFAdd:
3914 case spv::OpFSub:
3915 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003916 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003917 case spv::OpFMul:
3918 {
3919 // one time set up...
3920 bool leftMat = builder.isMatrix(left);
3921 bool rightMat = builder.isMatrix(right);
3922 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3923 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3924 spv::Id scalarType = builder.getScalarTypeId(typeId);
3925 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3926 std::vector<spv::Id> results;
3927 spv::Id smearVec = spv::NoResult;
3928 if (builder.isScalar(left))
3929 smearVec = builder.smearScalar(precision, left, vecType);
3930 else if (builder.isScalar(right))
3931 smearVec = builder.smearScalar(precision, right, vecType);
3932
3933 // do each vector op
3934 for (unsigned int c = 0; c < numCols; ++c) {
3935 std::vector<unsigned int> indexes;
3936 indexes.push_back(c);
3937 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3938 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003939 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3940 addDecoration(result, noContraction);
3941 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003942 }
3943
3944 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003945 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003946 }
3947 default:
3948 assert(0);
3949 return spv::NoResult;
3950 }
3951}
3952
qining25262b32016-05-06 17:25:16 -04003953spv::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 -06003954{
3955 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003956 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003957 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003958#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003959 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003960 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3961#else
Rex Xucabbb782017-03-24 13:41:14 +08003962 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003963 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003964#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003965
3966 switch (op) {
3967 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003968 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003969 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003970 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003971 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003972 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003973 unaryOp = spv::OpSNegate;
3974 break;
3975
3976 case glslang::EOpLogicalNot:
3977 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003978 unaryOp = spv::OpLogicalNot;
3979 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003980 case glslang::EOpBitwiseNot:
3981 unaryOp = spv::OpNot;
3982 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003983
John Kessenich140f3df2015-06-26 16:58:36 -06003984 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003985 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003986 break;
3987 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003988 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003989 break;
3990 case glslang::EOpTranspose:
3991 unaryOp = spv::OpTranspose;
3992 break;
3993
3994 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003995 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003996 break;
3997 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003998 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003999 break;
4000 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004001 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004002 break;
4003 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004004 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004005 break;
4006 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004007 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004008 break;
4009 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004010 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004011 break;
4012 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004013 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004014 break;
4015 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004016 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004017 break;
4018
4019 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004020 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004021 break;
4022 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004023 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004024 break;
4025 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004026 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004027 break;
4028 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004029 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004030 break;
4031 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004032 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004033 break;
4034 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004035 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004036 break;
4037
4038 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004039 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004040 break;
4041 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004042 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004043 break;
4044
4045 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004046 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004047 break;
4048 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004049 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004050 break;
4051 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004052 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004053 break;
4054 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004055 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004056 break;
4057 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004058 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004059 break;
4060 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004061 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004062 break;
4063
4064 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 break;
4067 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
4070 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004071 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
4073 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004074 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004075 break;
4076 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004077 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004078 break;
4079 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004080 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004081 break;
4082
4083 case glslang::EOpIsNan:
4084 unaryOp = spv::OpIsNan;
4085 break;
4086 case glslang::EOpIsInf:
4087 unaryOp = spv::OpIsInf;
4088 break;
LoopDawg592860c2016-06-09 08:57:35 -06004089 case glslang::EOpIsFinite:
4090 unaryOp = spv::OpIsFinite;
4091 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004092
Rex Xucbc426e2015-12-15 16:03:10 +08004093 case glslang::EOpFloatBitsToInt:
4094 case glslang::EOpFloatBitsToUint:
4095 case glslang::EOpIntBitsToFloat:
4096 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004097 case glslang::EOpDoubleBitsToInt64:
4098 case glslang::EOpDoubleBitsToUint64:
4099 case glslang::EOpInt64BitsToDouble:
4100 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004101#ifdef AMD_EXTENSIONS
4102 case glslang::EOpFloat16BitsToInt16:
4103 case glslang::EOpFloat16BitsToUint16:
4104 case glslang::EOpInt16BitsToFloat16:
4105 case glslang::EOpUint16BitsToFloat16:
4106#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004107 unaryOp = spv::OpBitcast;
4108 break;
4109
John Kessenich140f3df2015-06-26 16:58:36 -06004110 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004111 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004112 break;
4113 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004114 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004115 break;
4116 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004117 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004118 break;
4119 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004120 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004121 break;
4122 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004126 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004127 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004128 case glslang::EOpPackSnorm4x8:
4129 libCall = spv::GLSLstd450PackSnorm4x8;
4130 break;
4131 case glslang::EOpUnpackSnorm4x8:
4132 libCall = spv::GLSLstd450UnpackSnorm4x8;
4133 break;
4134 case glslang::EOpPackUnorm4x8:
4135 libCall = spv::GLSLstd450PackUnorm4x8;
4136 break;
4137 case glslang::EOpUnpackUnorm4x8:
4138 libCall = spv::GLSLstd450UnpackUnorm4x8;
4139 break;
4140 case glslang::EOpPackDouble2x32:
4141 libCall = spv::GLSLstd450PackDouble2x32;
4142 break;
4143 case glslang::EOpUnpackDouble2x32:
4144 libCall = spv::GLSLstd450UnpackDouble2x32;
4145 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004146
Rex Xu8ff43de2016-04-22 16:51:45 +08004147 case glslang::EOpPackInt2x32:
4148 case glslang::EOpUnpackInt2x32:
4149 case glslang::EOpPackUint2x32:
4150 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004151 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004152 break;
4153
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004154#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004155 case glslang::EOpPackInt2x16:
4156 case glslang::EOpUnpackInt2x16:
4157 case glslang::EOpPackUint2x16:
4158 case glslang::EOpUnpackUint2x16:
4159 case glslang::EOpPackInt4x16:
4160 case glslang::EOpUnpackInt4x16:
4161 case glslang::EOpPackUint4x16:
4162 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004163 case glslang::EOpPackFloat2x16:
4164 case glslang::EOpUnpackFloat2x16:
4165 unaryOp = spv::OpBitcast;
4166 break;
4167#endif
4168
John Kessenich140f3df2015-06-26 16:58:36 -06004169 case glslang::EOpDPdx:
4170 unaryOp = spv::OpDPdx;
4171 break;
4172 case glslang::EOpDPdy:
4173 unaryOp = spv::OpDPdy;
4174 break;
4175 case glslang::EOpFwidth:
4176 unaryOp = spv::OpFwidth;
4177 break;
4178 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004179 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004180 unaryOp = spv::OpDPdxFine;
4181 break;
4182 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004183 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004184 unaryOp = spv::OpDPdyFine;
4185 break;
4186 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004187 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004188 unaryOp = spv::OpFwidthFine;
4189 break;
4190 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004191 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004192 unaryOp = spv::OpDPdxCoarse;
4193 break;
4194 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004195 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004196 unaryOp = spv::OpDPdyCoarse;
4197 break;
4198 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004199 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004200 unaryOp = spv::OpFwidthCoarse;
4201 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004202 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004203 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004204 libCall = spv::GLSLstd450InterpolateAtCentroid;
4205 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004206 case glslang::EOpAny:
4207 unaryOp = spv::OpAny;
4208 break;
4209 case glslang::EOpAll:
4210 unaryOp = spv::OpAll;
4211 break;
4212
4213 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004214 if (isFloat)
4215 libCall = spv::GLSLstd450FAbs;
4216 else
4217 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004218 break;
4219 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004220 if (isFloat)
4221 libCall = spv::GLSLstd450FSign;
4222 else
4223 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004224 break;
4225
John Kessenichfc51d282015-08-19 13:34:18 -06004226 case glslang::EOpAtomicCounterIncrement:
4227 case glslang::EOpAtomicCounterDecrement:
4228 case glslang::EOpAtomicCounter:
4229 {
4230 // Handle all of the atomics in one place, in createAtomicOperation()
4231 std::vector<spv::Id> operands;
4232 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004233 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004234 }
4235
John Kessenichfc51d282015-08-19 13:34:18 -06004236 case glslang::EOpBitFieldReverse:
4237 unaryOp = spv::OpBitReverse;
4238 break;
4239 case glslang::EOpBitCount:
4240 unaryOp = spv::OpBitCount;
4241 break;
4242 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004243 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004244 break;
4245 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004246 if (isUnsigned)
4247 libCall = spv::GLSLstd450FindUMsb;
4248 else
4249 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004250 break;
4251
Rex Xu574ab042016-04-14 16:53:07 +08004252 case glslang::EOpBallot:
4253 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004254 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004255 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004256 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004257#ifdef AMD_EXTENSIONS
4258 case glslang::EOpMinInvocations:
4259 case glslang::EOpMaxInvocations:
4260 case glslang::EOpAddInvocations:
4261 case glslang::EOpMinInvocationsNonUniform:
4262 case glslang::EOpMaxInvocationsNonUniform:
4263 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004264 case glslang::EOpMinInvocationsInclusiveScan:
4265 case glslang::EOpMaxInvocationsInclusiveScan:
4266 case glslang::EOpAddInvocationsInclusiveScan:
4267 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4268 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4269 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4270 case glslang::EOpMinInvocationsExclusiveScan:
4271 case glslang::EOpMaxInvocationsExclusiveScan:
4272 case glslang::EOpAddInvocationsExclusiveScan:
4273 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4274 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4275 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004276#endif
Rex Xu51596642016-09-21 18:56:12 +08004277 {
4278 std::vector<spv::Id> operands;
4279 operands.push_back(operand);
4280 return createInvocationsOperation(op, typeId, operands, typeProxy);
4281 }
Rex Xu9d93a232016-05-05 12:30:44 +08004282
4283#ifdef AMD_EXTENSIONS
4284 case glslang::EOpMbcnt:
4285 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4286 libCall = spv::MbcntAMD;
4287 break;
4288
4289 case glslang::EOpCubeFaceIndex:
4290 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4291 libCall = spv::CubeFaceIndexAMD;
4292 break;
4293
4294 case glslang::EOpCubeFaceCoord:
4295 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4296 libCall = spv::CubeFaceCoordAMD;
4297 break;
4298#endif
Rex Xu338b1852016-05-05 20:38:33 +08004299
John Kessenich140f3df2015-06-26 16:58:36 -06004300 default:
4301 return 0;
4302 }
4303
4304 spv::Id id;
4305 if (libCall >= 0) {
4306 std::vector<spv::Id> args;
4307 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004308 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004309 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004310 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004311 }
John Kessenich140f3df2015-06-26 16:58:36 -06004312
qining25262b32016-05-06 17:25:16 -04004313 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004314 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004315}
4316
John Kessenich7a53f762016-01-20 11:19:27 -07004317// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004318spv::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 -07004319{
4320 // Handle unary operations vector by vector.
4321 // The result type is the same type as the original type.
4322 // The algorithm is to:
4323 // - break the matrix into vectors
4324 // - apply the operation to each vector
4325 // - make a matrix out the vector results
4326
4327 // get the types sorted out
4328 int numCols = builder.getNumColumns(operand);
4329 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004330 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4331 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004332 std::vector<spv::Id> results;
4333
4334 // do each vector op
4335 for (int c = 0; c < numCols; ++c) {
4336 std::vector<unsigned int> indexes;
4337 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004338 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4339 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4340 addDecoration(destVec, noContraction);
4341 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004342 }
4343
4344 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004345 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004346}
4347
Rex Xu73e3ce72016-04-27 18:48:17 +08004348spv::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 -06004349{
4350 spv::Op convOp = spv::OpNop;
4351 spv::Id zero = 0;
4352 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004353 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004354
4355 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4356
4357 switch (op) {
4358 case glslang::EOpConvIntToBool:
4359 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004360 case glslang::EOpConvInt64ToBool:
4361 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004362#ifdef AMD_EXTENSIONS
4363 case glslang::EOpConvInt16ToBool:
4364 case glslang::EOpConvUint16ToBool:
4365#endif
4366 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4367 zero = builder.makeUint64Constant(0);
4368#ifdef AMD_EXTENSIONS
4369 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4370 zero = builder.makeUint16Constant(0);
4371#endif
4372 else
4373 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004374 zero = makeSmearedConstant(zero, vectorSize);
4375 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4376
4377 case glslang::EOpConvFloatToBool:
4378 zero = builder.makeFloatConstant(0.0F);
4379 zero = makeSmearedConstant(zero, vectorSize);
4380 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4381
4382 case glslang::EOpConvDoubleToBool:
4383 zero = builder.makeDoubleConstant(0.0);
4384 zero = makeSmearedConstant(zero, vectorSize);
4385 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4386
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004387#ifdef AMD_EXTENSIONS
4388 case glslang::EOpConvFloat16ToBool:
4389 zero = builder.makeFloat16Constant(0.0F);
4390 zero = makeSmearedConstant(zero, vectorSize);
4391 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4392#endif
4393
John Kessenich140f3df2015-06-26 16:58:36 -06004394 case glslang::EOpConvBoolToFloat:
4395 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004396 zero = builder.makeFloatConstant(0.0F);
4397 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004398 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004399
John Kessenich140f3df2015-06-26 16:58:36 -06004400 case glslang::EOpConvBoolToDouble:
4401 convOp = spv::OpSelect;
4402 zero = builder.makeDoubleConstant(0.0);
4403 one = builder.makeDoubleConstant(1.0);
4404 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004405
4406#ifdef AMD_EXTENSIONS
4407 case glslang::EOpConvBoolToFloat16:
4408 convOp = spv::OpSelect;
4409 zero = builder.makeFloat16Constant(0.0F);
4410 one = builder.makeFloat16Constant(1.0F);
4411 break;
4412#endif
4413
John Kessenich140f3df2015-06-26 16:58:36 -06004414 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004415 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004416#ifdef AMD_EXTENSIONS
4417 case glslang::EOpConvBoolToInt16:
4418#endif
4419 if (op == glslang::EOpConvBoolToInt64)
4420 zero = builder.makeInt64Constant(0);
4421#ifdef AMD_EXTENSIONS
4422 else if (op == glslang::EOpConvBoolToInt16)
4423 zero = builder.makeInt16Constant(0);
4424#endif
4425 else
4426 zero = builder.makeIntConstant(0);
4427
4428 if (op == glslang::EOpConvBoolToInt64)
4429 one = builder.makeInt64Constant(1);
4430#ifdef AMD_EXTENSIONS
4431 else if (op == glslang::EOpConvBoolToInt16)
4432 one = builder.makeInt16Constant(1);
4433#endif
4434 else
4435 one = builder.makeIntConstant(1);
4436
John Kessenich140f3df2015-06-26 16:58:36 -06004437 convOp = spv::OpSelect;
4438 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004439
John Kessenich140f3df2015-06-26 16:58:36 -06004440 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004441 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004442#ifdef AMD_EXTENSIONS
4443 case glslang::EOpConvBoolToUint16:
4444#endif
4445 if (op == glslang::EOpConvBoolToUint64)
4446 zero = builder.makeUint64Constant(0);
4447#ifdef AMD_EXTENSIONS
4448 else if (op == glslang::EOpConvBoolToUint16)
4449 zero = builder.makeUint16Constant(0);
4450#endif
4451 else
4452 zero = builder.makeUintConstant(0);
4453
4454 if (op == glslang::EOpConvBoolToUint64)
4455 one = builder.makeUint64Constant(1);
4456#ifdef AMD_EXTENSIONS
4457 else if (op == glslang::EOpConvBoolToUint16)
4458 one = builder.makeUint16Constant(1);
4459#endif
4460 else
4461 one = builder.makeUintConstant(1);
4462
John Kessenich140f3df2015-06-26 16:58:36 -06004463 convOp = spv::OpSelect;
4464 break;
4465
4466 case glslang::EOpConvIntToFloat:
4467 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004468 case glslang::EOpConvInt64ToFloat:
4469 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004470#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004471 case glslang::EOpConvInt16ToFloat:
4472 case glslang::EOpConvInt16ToDouble:
4473 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004474 case glslang::EOpConvIntToFloat16:
4475 case glslang::EOpConvInt64ToFloat16:
4476#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004477 convOp = spv::OpConvertSToF;
4478 break;
4479
4480 case glslang::EOpConvUintToFloat:
4481 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004482 case glslang::EOpConvUint64ToFloat:
4483 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004484#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004485 case glslang::EOpConvUint16ToFloat:
4486 case glslang::EOpConvUint16ToDouble:
4487 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004488 case glslang::EOpConvUintToFloat16:
4489 case glslang::EOpConvUint64ToFloat16:
4490#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004491 convOp = spv::OpConvertUToF;
4492 break;
4493
4494 case glslang::EOpConvDoubleToFloat:
4495 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004496#ifdef AMD_EXTENSIONS
4497 case glslang::EOpConvDoubleToFloat16:
4498 case glslang::EOpConvFloat16ToDouble:
4499 case glslang::EOpConvFloatToFloat16:
4500 case glslang::EOpConvFloat16ToFloat:
4501#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004502 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004503 if (builder.isMatrixType(destType))
4504 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004505 break;
4506
4507 case glslang::EOpConvFloatToInt:
4508 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004509 case glslang::EOpConvFloatToInt64:
4510 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004511#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004512 case glslang::EOpConvFloatToInt16:
4513 case glslang::EOpConvDoubleToInt16:
4514 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004515 case glslang::EOpConvFloat16ToInt:
4516 case glslang::EOpConvFloat16ToInt64:
4517#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004518 convOp = spv::OpConvertFToS;
4519 break;
4520
4521 case glslang::EOpConvUintToInt:
4522 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004523 case glslang::EOpConvUint64ToInt64:
4524 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004525#ifdef AMD_EXTENSIONS
4526 case glslang::EOpConvUint16ToInt16:
4527 case glslang::EOpConvInt16ToUint16:
4528#endif
qininge24aa5e2016-04-07 15:40:27 -04004529 if (builder.isInSpecConstCodeGenMode()) {
4530 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004531 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4532 zero = builder.makeUint64Constant(0);
4533#ifdef AMD_EXTENSIONS
4534 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4535 zero = builder.makeUint16Constant(0);
4536#endif
4537 else
4538 zero = builder.makeUintConstant(0);
4539
qining189b2032016-04-12 23:16:20 -04004540 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004541 // Use OpIAdd, instead of OpBitcast to do the conversion when
4542 // generating for OpSpecConstantOp instruction.
4543 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4544 }
4545 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004546 convOp = spv::OpBitcast;
4547 break;
4548
4549 case glslang::EOpConvFloatToUint:
4550 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004551 case glslang::EOpConvFloatToUint64:
4552 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004553#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004554 case glslang::EOpConvFloatToUint16:
4555 case glslang::EOpConvDoubleToUint16:
4556 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004557 case glslang::EOpConvFloat16ToUint:
4558 case glslang::EOpConvFloat16ToUint64:
4559#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004560 convOp = spv::OpConvertFToU;
4561 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004562
4563 case glslang::EOpConvIntToInt64:
4564 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004565#ifdef AMD_EXTENSIONS
4566 case glslang::EOpConvIntToInt16:
4567 case glslang::EOpConvInt16ToInt:
4568 case glslang::EOpConvInt64ToInt16:
4569 case glslang::EOpConvInt16ToInt64:
4570#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004571 convOp = spv::OpSConvert;
4572 break;
4573
4574 case glslang::EOpConvUintToUint64:
4575 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004576#ifdef AMD_EXTENSIONS
4577 case glslang::EOpConvUintToUint16:
4578 case glslang::EOpConvUint16ToUint:
4579 case glslang::EOpConvUint64ToUint16:
4580 case glslang::EOpConvUint16ToUint64:
4581#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004582 convOp = spv::OpUConvert;
4583 break;
4584
4585 case glslang::EOpConvIntToUint64:
4586 case glslang::EOpConvInt64ToUint:
4587 case glslang::EOpConvUint64ToInt:
4588 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004589#ifdef AMD_EXTENSIONS
4590 case glslang::EOpConvInt16ToUint:
4591 case glslang::EOpConvUintToInt16:
4592 case glslang::EOpConvInt16ToUint64:
4593 case glslang::EOpConvUint64ToInt16:
4594 case glslang::EOpConvUint16ToInt:
4595 case glslang::EOpConvIntToUint16:
4596 case glslang::EOpConvUint16ToInt64:
4597 case glslang::EOpConvInt64ToUint16:
4598#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004599 // OpSConvert/OpUConvert + OpBitCast
4600 switch (op) {
4601 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004602#ifdef AMD_EXTENSIONS
4603 case glslang::EOpConvInt16ToUint64:
4604#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004605 convOp = spv::OpSConvert;
4606 type = builder.makeIntType(64);
4607 break;
4608 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004609#ifdef AMD_EXTENSIONS
4610 case glslang::EOpConvInt16ToUint:
4611#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004612 convOp = spv::OpSConvert;
4613 type = builder.makeIntType(32);
4614 break;
4615 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004616#ifdef AMD_EXTENSIONS
4617 case glslang::EOpConvUint16ToInt:
4618#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004619 convOp = spv::OpUConvert;
4620 type = builder.makeUintType(32);
4621 break;
4622 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004623#ifdef AMD_EXTENSIONS
4624 case glslang::EOpConvUint16ToInt64:
4625#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004626 convOp = spv::OpUConvert;
4627 type = builder.makeUintType(64);
4628 break;
Rex Xucabbb782017-03-24 13:41:14 +08004629#ifdef AMD_EXTENSIONS
4630 case glslang::EOpConvUintToInt16:
4631 case glslang::EOpConvUint64ToInt16:
4632 convOp = spv::OpUConvert;
4633 type = builder.makeUintType(16);
4634 break;
4635 case glslang::EOpConvIntToUint16:
4636 case glslang::EOpConvInt64ToUint16:
4637 convOp = spv::OpSConvert;
4638 type = builder.makeIntType(16);
4639 break;
4640#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004641 default:
4642 assert(0);
4643 break;
4644 }
4645
4646 if (vectorSize > 0)
4647 type = builder.makeVectorType(type, vectorSize);
4648
4649 operand = builder.createUnaryOp(convOp, type, operand);
4650
4651 if (builder.isInSpecConstCodeGenMode()) {
4652 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004653#ifdef AMD_EXTENSIONS
4654 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4655 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4656 zero = builder.makeUint64Constant(0);
4657 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4658 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4659 zero = builder.makeUint16Constant(0);
4660 else
4661 zero = builder.makeUintConstant(0);
4662#else
4663 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4664 zero = builder.makeUint64Constant(0);
4665 else
4666 zero = builder.makeUintConstant(0);
4667#endif
4668
Rex Xu8ff43de2016-04-22 16:51:45 +08004669 zero = makeSmearedConstant(zero, vectorSize);
4670 // Use OpIAdd, instead of OpBitcast to do the conversion when
4671 // generating for OpSpecConstantOp instruction.
4672 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4673 }
4674 // For normal run-time conversion instruction, use OpBitcast.
4675 convOp = spv::OpBitcast;
4676 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004677 default:
4678 break;
4679 }
4680
4681 spv::Id result = 0;
4682 if (convOp == spv::OpNop)
4683 return result;
4684
4685 if (convOp == spv::OpSelect) {
4686 zero = makeSmearedConstant(zero, vectorSize);
4687 one = makeSmearedConstant(one, vectorSize);
4688 result = builder.createTriOp(convOp, destType, operand, one, zero);
4689 } else
4690 result = builder.createUnaryOp(convOp, destType, operand);
4691
John Kessenich32cfd492016-02-02 12:37:46 -07004692 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004693}
4694
4695spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4696{
4697 if (vectorSize == 0)
4698 return constant;
4699
4700 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4701 std::vector<spv::Id> components;
4702 for (int c = 0; c < vectorSize; ++c)
4703 components.push_back(constant);
4704 return builder.makeCompositeConstant(vectorTypeId, components);
4705}
4706
John Kessenich426394d2015-07-23 10:22:48 -06004707// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004708spv::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 -06004709{
4710 spv::Op opCode = spv::OpNop;
4711
4712 switch (op) {
4713 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004714 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004715 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004716 opCode = spv::OpAtomicIAdd;
4717 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004718 case glslang::EOpAtomicCounterSubtract:
4719 opCode = spv::OpAtomicISub;
4720 break;
John Kessenich426394d2015-07-23 10:22:48 -06004721 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004722 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004723 case glslang::EOpAtomicCounterMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004724 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004725 break;
4726 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004727 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004728 case glslang::EOpAtomicCounterMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004729 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004730 break;
4731 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004732 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004733 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004734 opCode = spv::OpAtomicAnd;
4735 break;
4736 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004737 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004738 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004739 opCode = spv::OpAtomicOr;
4740 break;
4741 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004742 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004743 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004744 opCode = spv::OpAtomicXor;
4745 break;
4746 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004747 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004748 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004749 opCode = spv::OpAtomicExchange;
4750 break;
4751 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004752 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004753 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004754 opCode = spv::OpAtomicCompareExchange;
4755 break;
4756 case glslang::EOpAtomicCounterIncrement:
4757 opCode = spv::OpAtomicIIncrement;
4758 break;
4759 case glslang::EOpAtomicCounterDecrement:
4760 opCode = spv::OpAtomicIDecrement;
4761 break;
4762 case glslang::EOpAtomicCounter:
4763 opCode = spv::OpAtomicLoad;
4764 break;
4765 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004766 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004767 break;
4768 }
4769
4770 // Sort out the operands
4771 // - mapping from glslang -> SPV
4772 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004773 // - compare-exchange swaps the value and comparator
4774 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004775 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4776 auto opIt = operands.begin(); // walk the glslang operands
4777 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004778 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4779 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4780 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004781 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4782 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004783 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004784 spvAtomicOperands.push_back(*(opIt + 1));
4785 spvAtomicOperands.push_back(*opIt);
4786 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004787 }
John Kessenich426394d2015-07-23 10:22:48 -06004788
John Kessenich3e60a6f2015-09-14 22:45:16 -06004789 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004790 for (; opIt != operands.end(); ++opIt)
4791 spvAtomicOperands.push_back(*opIt);
4792
4793 return builder.createOp(opCode, typeId, spvAtomicOperands);
4794}
4795
John Kessenich91cef522016-05-05 16:45:40 -06004796// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004797spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004798{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004799#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004800 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004801 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004802#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004803
Rex Xu51596642016-09-21 18:56:12 +08004804 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004805 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004806 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4807
chaocf200da82016-12-20 12:44:35 -08004808 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4809 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004810 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4811 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004812 } else if (op == glslang::EOpAnyInvocation ||
4813 op == glslang::EOpAllInvocations ||
4814 op == glslang::EOpAllInvocationsEqual) {
4815 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4816 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004817 } else {
4818 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004819#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004820 if (op == glslang::EOpMinInvocationsNonUniform ||
4821 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004822 op == glslang::EOpAddInvocationsNonUniform ||
4823 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4824 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4825 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4826 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4827 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4828 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004829 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004830#endif
Rex Xu51596642016-09-21 18:56:12 +08004831
4832 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004833#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004834 switch (op) {
4835 case glslang::EOpMinInvocations:
4836 case glslang::EOpMaxInvocations:
4837 case glslang::EOpAddInvocations:
4838 case glslang::EOpMinInvocationsNonUniform:
4839 case glslang::EOpMaxInvocationsNonUniform:
4840 case glslang::EOpAddInvocationsNonUniform:
4841 groupOperation = spv::GroupOperationReduce;
4842 spvGroupOperands.push_back(groupOperation);
4843 break;
4844 case glslang::EOpMinInvocationsInclusiveScan:
4845 case glslang::EOpMaxInvocationsInclusiveScan:
4846 case glslang::EOpAddInvocationsInclusiveScan:
4847 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4848 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4849 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4850 groupOperation = spv::GroupOperationInclusiveScan;
4851 spvGroupOperands.push_back(groupOperation);
4852 break;
4853 case glslang::EOpMinInvocationsExclusiveScan:
4854 case glslang::EOpMaxInvocationsExclusiveScan:
4855 case glslang::EOpAddInvocationsExclusiveScan:
4856 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4857 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4858 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4859 groupOperation = spv::GroupOperationExclusiveScan;
4860 spvGroupOperands.push_back(groupOperation);
4861 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004862 default:
4863 break;
Rex Xu430ef402016-10-14 17:22:23 +08004864 }
Rex Xu9d93a232016-05-05 12:30:44 +08004865#endif
Rex Xu51596642016-09-21 18:56:12 +08004866 }
4867
4868 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4869 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004870
4871 switch (op) {
4872 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004873 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004874 break;
John Kessenich91cef522016-05-05 16:45:40 -06004875 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004876 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004877 break;
John Kessenich91cef522016-05-05 16:45:40 -06004878 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004879 opCode = spv::OpSubgroupAllEqualKHR;
4880 break;
Rex Xu51596642016-09-21 18:56:12 +08004881 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004882 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004883 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004884 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004885 break;
4886 case glslang::EOpReadFirstInvocation:
4887 opCode = spv::OpSubgroupFirstInvocationKHR;
4888 break;
4889 case glslang::EOpBallot:
4890 {
4891 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4892 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4893 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4894 //
4895 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4896 //
4897 spv::Id uintType = builder.makeUintType(32);
4898 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4899 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4900
4901 std::vector<spv::Id> components;
4902 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4903 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4904
4905 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4906 return builder.createUnaryOp(spv::OpBitcast, typeId,
4907 builder.createCompositeConstruct(uvec2Type, components));
4908 }
4909
Rex Xu9d93a232016-05-05 12:30:44 +08004910#ifdef AMD_EXTENSIONS
4911 case glslang::EOpMinInvocations:
4912 case glslang::EOpMaxInvocations:
4913 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004914 case glslang::EOpMinInvocationsInclusiveScan:
4915 case glslang::EOpMaxInvocationsInclusiveScan:
4916 case glslang::EOpAddInvocationsInclusiveScan:
4917 case glslang::EOpMinInvocationsExclusiveScan:
4918 case glslang::EOpMaxInvocationsExclusiveScan:
4919 case glslang::EOpAddInvocationsExclusiveScan:
4920 if (op == glslang::EOpMinInvocations ||
4921 op == glslang::EOpMinInvocationsInclusiveScan ||
4922 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004923 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004924 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004925 else {
4926 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004927 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004928 else
Rex Xu51596642016-09-21 18:56:12 +08004929 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004930 }
Rex Xu430ef402016-10-14 17:22:23 +08004931 } else if (op == glslang::EOpMaxInvocations ||
4932 op == glslang::EOpMaxInvocationsInclusiveScan ||
4933 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004934 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004935 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004936 else {
4937 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004938 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004939 else
Rex Xu51596642016-09-21 18:56:12 +08004940 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004941 }
4942 } else {
4943 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004944 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004945 else
Rex Xu51596642016-09-21 18:56:12 +08004946 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004947 }
4948
Rex Xu2bbbe062016-08-23 15:41:05 +08004949 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004950 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004951
4952 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004953 case glslang::EOpMinInvocationsNonUniform:
4954 case glslang::EOpMaxInvocationsNonUniform:
4955 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004956 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4957 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4958 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4959 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4960 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4961 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4962 if (op == glslang::EOpMinInvocationsNonUniform ||
4963 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4964 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004965 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004966 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004967 else {
4968 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004969 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004970 else
Rex Xu51596642016-09-21 18:56:12 +08004971 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004972 }
4973 }
Rex Xu430ef402016-10-14 17:22:23 +08004974 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4975 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4976 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004977 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004978 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004979 else {
4980 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004981 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004982 else
Rex Xu51596642016-09-21 18:56:12 +08004983 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004984 }
4985 }
4986 else {
4987 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004988 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004989 else
Rex Xu51596642016-09-21 18:56:12 +08004990 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004991 }
4992
Rex Xu2bbbe062016-08-23 15:41:05 +08004993 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004994 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004995
4996 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004997#endif
John Kessenich91cef522016-05-05 16:45:40 -06004998 default:
4999 logger->missingFunctionality("invocation operation");
5000 return spv::NoResult;
5001 }
Rex Xu51596642016-09-21 18:56:12 +08005002
5003 assert(opCode != spv::OpNop);
5004 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005005}
5006
Rex Xu2bbbe062016-08-23 15:41:05 +08005007// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005008spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005009{
Rex Xub7072052016-09-26 15:53:40 +08005010#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005011 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5012 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005013 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005014 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005015 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5016 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5017 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005018#else
5019 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5020 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005021 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5022 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005023#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005024
5025 // Handle group invocation operations scalar by scalar.
5026 // The result type is the same type as the original type.
5027 // The algorithm is to:
5028 // - break the vector into scalars
5029 // - apply the operation to each scalar
5030 // - make a vector out the scalar results
5031
5032 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005033 int numComponents = builder.getNumComponents(operands[0]);
5034 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005035 std::vector<spv::Id> results;
5036
5037 // do each scalar op
5038 for (int comp = 0; comp < numComponents; ++comp) {
5039 std::vector<unsigned int> indexes;
5040 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005041 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005042 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005043 if (op == spv::OpSubgroupReadInvocationKHR) {
5044 spvGroupOperands.push_back(scalar);
5045 spvGroupOperands.push_back(operands[1]);
5046 } else if (op == spv::OpGroupBroadcast) {
5047 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005048 spvGroupOperands.push_back(scalar);
5049 spvGroupOperands.push_back(operands[1]);
5050 } else {
chaocf200da82016-12-20 12:44:35 -08005051 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005052 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005053 spvGroupOperands.push_back(scalar);
5054 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005055
Rex Xub7072052016-09-26 15:53:40 +08005056 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005057 }
5058
5059 // put the pieces together
5060 return builder.createCompositeConstruct(typeId, results);
5061}
Rex Xu2bbbe062016-08-23 15:41:05 +08005062
John Kessenich5e4b1242015-08-06 22:53:06 -06005063spv::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 -06005064{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005065#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005066 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005067 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5068#else
Rex Xucabbb782017-03-24 13:41:14 +08005069 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005070 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005071#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005072
John Kessenich140f3df2015-06-26 16:58:36 -06005073 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005074 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005075 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005076 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005077 spv::Id typeId0 = 0;
5078 if (consumedOperands > 0)
5079 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005080 spv::Id typeId1 = 0;
5081 if (consumedOperands > 1)
5082 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005083 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005084
5085 switch (op) {
5086 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005087 if (isFloat)
5088 libCall = spv::GLSLstd450FMin;
5089 else if (isUnsigned)
5090 libCall = spv::GLSLstd450UMin;
5091 else
5092 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005093 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005094 break;
5095 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005096 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005097 break;
5098 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005099 if (isFloat)
5100 libCall = spv::GLSLstd450FMax;
5101 else if (isUnsigned)
5102 libCall = spv::GLSLstd450UMax;
5103 else
5104 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005105 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005106 break;
5107 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005108 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005109 break;
5110 case glslang::EOpDot:
5111 opCode = spv::OpDot;
5112 break;
5113 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005114 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005115 break;
5116
5117 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005118 if (isFloat)
5119 libCall = spv::GLSLstd450FClamp;
5120 else if (isUnsigned)
5121 libCall = spv::GLSLstd450UClamp;
5122 else
5123 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005124 builder.promoteScalar(precision, operands.front(), operands[1]);
5125 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005126 break;
5127 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005128 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5129 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005130 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005131 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005132 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005133 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005134 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005135 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005136 break;
5137 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005138 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005139 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005140 break;
5141 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005142 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005143 builder.promoteScalar(precision, operands[0], operands[2]);
5144 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005145 break;
5146
5147 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005148 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005149 break;
5150 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005151 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005152 break;
5153 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005154 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005155 break;
5156 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005157 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005158 break;
5159 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005160 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005161 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005162 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005163 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005164 libCall = spv::GLSLstd450InterpolateAtSample;
5165 break;
5166 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005167 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005168 libCall = spv::GLSLstd450InterpolateAtOffset;
5169 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005170 case glslang::EOpAddCarry:
5171 opCode = spv::OpIAddCarry;
5172 typeId = builder.makeStructResultType(typeId0, typeId0);
5173 consumedOperands = 2;
5174 break;
5175 case glslang::EOpSubBorrow:
5176 opCode = spv::OpISubBorrow;
5177 typeId = builder.makeStructResultType(typeId0, typeId0);
5178 consumedOperands = 2;
5179 break;
5180 case glslang::EOpUMulExtended:
5181 opCode = spv::OpUMulExtended;
5182 typeId = builder.makeStructResultType(typeId0, typeId0);
5183 consumedOperands = 2;
5184 break;
5185 case glslang::EOpIMulExtended:
5186 opCode = spv::OpSMulExtended;
5187 typeId = builder.makeStructResultType(typeId0, typeId0);
5188 consumedOperands = 2;
5189 break;
5190 case glslang::EOpBitfieldExtract:
5191 if (isUnsigned)
5192 opCode = spv::OpBitFieldUExtract;
5193 else
5194 opCode = spv::OpBitFieldSExtract;
5195 break;
5196 case glslang::EOpBitfieldInsert:
5197 opCode = spv::OpBitFieldInsert;
5198 break;
5199
5200 case glslang::EOpFma:
5201 libCall = spv::GLSLstd450Fma;
5202 break;
5203 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005204 {
5205 libCall = spv::GLSLstd450FrexpStruct;
5206 assert(builder.isPointerType(typeId1));
5207 typeId1 = builder.getContainedTypeId(typeId1);
5208#ifdef AMD_EXTENSIONS
5209 int width = builder.getScalarTypeWidth(typeId1);
5210#else
5211 int width = 32;
5212#endif
5213 if (builder.getNumComponents(operands[0]) == 1)
5214 frexpIntType = builder.makeIntegerType(width, true);
5215 else
5216 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5217 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5218 consumedOperands = 1;
5219 }
John Kessenich55e7d112015-11-15 21:33:39 -07005220 break;
5221 case glslang::EOpLdexp:
5222 libCall = spv::GLSLstd450Ldexp;
5223 break;
5224
Rex Xu574ab042016-04-14 16:53:07 +08005225 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005226 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005227
Rex Xu9d93a232016-05-05 12:30:44 +08005228#ifdef AMD_EXTENSIONS
5229 case glslang::EOpSwizzleInvocations:
5230 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5231 libCall = spv::SwizzleInvocationsAMD;
5232 break;
5233 case glslang::EOpSwizzleInvocationsMasked:
5234 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5235 libCall = spv::SwizzleInvocationsMaskedAMD;
5236 break;
5237 case glslang::EOpWriteInvocation:
5238 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5239 libCall = spv::WriteInvocationAMD;
5240 break;
5241
5242 case glslang::EOpMin3:
5243 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5244 if (isFloat)
5245 libCall = spv::FMin3AMD;
5246 else {
5247 if (isUnsigned)
5248 libCall = spv::UMin3AMD;
5249 else
5250 libCall = spv::SMin3AMD;
5251 }
5252 break;
5253 case glslang::EOpMax3:
5254 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5255 if (isFloat)
5256 libCall = spv::FMax3AMD;
5257 else {
5258 if (isUnsigned)
5259 libCall = spv::UMax3AMD;
5260 else
5261 libCall = spv::SMax3AMD;
5262 }
5263 break;
5264 case glslang::EOpMid3:
5265 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5266 if (isFloat)
5267 libCall = spv::FMid3AMD;
5268 else {
5269 if (isUnsigned)
5270 libCall = spv::UMid3AMD;
5271 else
5272 libCall = spv::SMid3AMD;
5273 }
5274 break;
5275
5276 case glslang::EOpInterpolateAtVertex:
5277 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5278 libCall = spv::InterpolateAtVertexAMD;
5279 break;
5280#endif
5281
John Kessenich140f3df2015-06-26 16:58:36 -06005282 default:
5283 return 0;
5284 }
5285
5286 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005287 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005288 // Use an extended instruction from the standard library.
5289 // Construct the call arguments, without modifying the original operands vector.
5290 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5291 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005292 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005293 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005294 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005295 case 0:
5296 // should all be handled by visitAggregate and createNoArgOperation
5297 assert(0);
5298 return 0;
5299 case 1:
5300 // should all be handled by createUnaryOperation
5301 assert(0);
5302 return 0;
5303 case 2:
5304 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5305 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005306 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005307 // anything 3 or over doesn't have l-value operands, so all should be consumed
5308 assert(consumedOperands == operands.size());
5309 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005310 break;
5311 }
5312 }
5313
John Kessenich55e7d112015-11-15 21:33:39 -07005314 // Decode the return types that were structures
5315 switch (op) {
5316 case glslang::EOpAddCarry:
5317 case glslang::EOpSubBorrow:
5318 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5319 id = builder.createCompositeExtract(id, typeId0, 0);
5320 break;
5321 case glslang::EOpUMulExtended:
5322 case glslang::EOpIMulExtended:
5323 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5324 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5325 break;
5326 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005327 {
5328 assert(operands.size() == 2);
5329 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5330 // "exp" is floating-point type (from HLSL intrinsic)
5331 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5332 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5333 builder.createStore(member1, operands[1]);
5334 } else
5335 // "exp" is integer type (from GLSL built-in function)
5336 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5337 id = builder.createCompositeExtract(id, typeId0, 0);
5338 }
John Kessenich55e7d112015-11-15 21:33:39 -07005339 break;
5340 default:
5341 break;
5342 }
5343
John Kessenich32cfd492016-02-02 12:37:46 -07005344 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005345}
5346
Rex Xu9d93a232016-05-05 12:30:44 +08005347// Intrinsics with no arguments (or no return value, and no precision).
5348spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005349{
5350 // TODO: get the barrier operands correct
5351
5352 switch (op) {
5353 case glslang::EOpEmitVertex:
5354 builder.createNoResultOp(spv::OpEmitVertex);
5355 return 0;
5356 case glslang::EOpEndPrimitive:
5357 builder.createNoResultOp(spv::OpEndPrimitive);
5358 return 0;
5359 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005360 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005361 return 0;
5362 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005363 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005364 return 0;
5365 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005366 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005367 return 0;
5368 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005369 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005370 return 0;
5371 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005372 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005373 return 0;
5374 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005375 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005376 return 0;
5377 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005378 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005379 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005380 case glslang::EOpAllMemoryBarrierWithGroupSync:
5381 // Control barrier with non-"None" semantic is also a memory barrier.
5382 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5383 return 0;
5384 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5385 // Control barrier with non-"None" semantic is also a memory barrier.
5386 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5387 return 0;
5388 case glslang::EOpWorkgroupMemoryBarrier:
5389 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5390 return 0;
5391 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5392 // Control barrier with non-"None" semantic is also a memory barrier.
5393 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5394 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005395#ifdef AMD_EXTENSIONS
5396 case glslang::EOpTime:
5397 {
5398 std::vector<spv::Id> args; // Dummy arguments
5399 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5400 return builder.setPrecision(id, precision);
5401 }
5402#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005403 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005404 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005405 return 0;
5406 }
5407}
5408
5409spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5410{
John Kessenich2f273362015-07-18 22:34:27 -06005411 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005412 spv::Id id;
5413 if (symbolValues.end() != iter) {
5414 id = iter->second;
5415 return id;
5416 }
5417
5418 // it was not found, create it
5419 id = createSpvVariable(symbol);
5420 symbolValues[symbol->getId()] = id;
5421
Rex Xuc884b4a2016-06-29 15:03:44 +08005422 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005423 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005424 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005425 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005426 if (symbol->getType().getQualifier().hasSpecConstantId())
5427 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005428 if (symbol->getQualifier().hasIndex())
5429 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5430 if (symbol->getQualifier().hasComponent())
5431 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5432 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005433 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005434 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005435 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005436 if (symbol->getQualifier().hasXfbBuffer())
5437 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5438 if (symbol->getQualifier().hasXfbOffset())
5439 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5440 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005441 // atomic counters use this:
5442 if (symbol->getQualifier().hasOffset())
5443 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005444 }
5445
scygan2c864272016-05-18 18:09:17 +02005446 if (symbol->getQualifier().hasLocation())
5447 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005448 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005449 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005450 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005451 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005452 }
John Kessenich140f3df2015-06-26 16:58:36 -06005453 if (symbol->getQualifier().hasSet())
5454 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005455 else if (IsDescriptorResource(symbol->getType())) {
5456 // default to 0
5457 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5458 }
John Kessenich140f3df2015-06-26 16:58:36 -06005459 if (symbol->getQualifier().hasBinding())
5460 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005461 if (symbol->getQualifier().hasAttachment())
5462 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005463 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005464 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005465 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005466 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005467 if (symbol->getQualifier().hasXfbBuffer())
5468 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5469 }
5470
Rex Xu1da878f2016-02-21 20:59:01 +08005471 if (symbol->getType().isImage()) {
5472 std::vector<spv::Decoration> memory;
5473 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5474 for (unsigned int i = 0; i < memory.size(); ++i)
5475 addDecoration(id, memory[i]);
5476 }
5477
John Kessenich140f3df2015-06-26 16:58:36 -06005478 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005479 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005480 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005481 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005482
John Kessenichecba76f2017-01-06 00:34:48 -07005483#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005484 if (builtIn == spv::BuiltInSampleMask) {
5485 spv::Decoration decoration;
5486 // GL_NV_sample_mask_override_coverage extension
5487 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005488 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005489 else
5490 decoration = (spv::Decoration)spv::DecorationMax;
5491 addDecoration(id, decoration);
5492 if (decoration != spv::DecorationMax) {
5493 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5494 }
5495 }
chaoc771d89f2017-01-13 01:10:53 -08005496 else if (builtIn == spv::BuiltInLayer) {
5497 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005498 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005499 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5500 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5501 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5502 }
John Kessenichb41bff62017-08-11 13:07:17 -06005503 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005504 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5505 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5506 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5507 }
5508 }
5509
chaoc6e5acae2016-12-20 13:28:52 -08005510 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005511 addDecoration(id, spv::DecorationPassthroughNV);
5512 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005513 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5514 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005515#endif
5516
John Kessenich140f3df2015-06-26 16:58:36 -06005517 return id;
5518}
5519
John Kessenich55e7d112015-11-15 21:33:39 -07005520// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005521void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5522{
John Kessenich4016e382016-07-15 11:53:56 -06005523 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005524 builder.addDecoration(id, dec);
5525}
5526
John Kessenich55e7d112015-11-15 21:33:39 -07005527// If 'dec' is valid, add a one-operand decoration to an object
5528void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5529{
John Kessenich4016e382016-07-15 11:53:56 -06005530 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005531 builder.addDecoration(id, dec, value);
5532}
5533
5534// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005535void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5536{
John Kessenich4016e382016-07-15 11:53:56 -06005537 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005538 builder.addMemberDecoration(id, (unsigned)member, dec);
5539}
5540
John Kessenich92187592016-02-01 13:45:25 -07005541// If 'dec' is valid, add a one-operand decoration to a struct member
5542void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5543{
John Kessenich4016e382016-07-15 11:53:56 -06005544 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005545 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5546}
5547
John Kessenich55e7d112015-11-15 21:33:39 -07005548// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005549// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005550//
5551// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5552//
5553// Recursively walk the nodes. The nodes form a tree whose leaves are
5554// regular constants, which themselves are trees that createSpvConstant()
5555// recursively walks. So, this function walks the "top" of the tree:
5556// - emit specialization constant-building instructions for specConstant
5557// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005558spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005559{
John Kessenich7cc0e282016-03-20 00:46:02 -06005560 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005561
qining4f4bb812016-04-03 23:55:17 -04005562 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005563 if (! node.getQualifier().specConstant) {
5564 // hand off to the non-spec-constant path
5565 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5566 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005567 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005568 nextConst, false);
5569 }
5570
5571 // We now know we have a specialization constant to build
5572
John Kessenichd94c0032016-05-30 19:29:40 -06005573 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005574 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5575 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5576 std::vector<spv::Id> dimConstId;
5577 for (int dim = 0; dim < 3; ++dim) {
5578 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5579 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5580 if (specConst)
5581 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5582 }
5583 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5584 }
5585
5586 // An AST node labelled as specialization constant should be a symbol node.
5587 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5588 if (auto* sn = node.getAsSymbolNode()) {
5589 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005590 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5591 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5592 // will set the builder into spec constant op instruction generating mode.
5593 sub_tree->traverse(this);
5594 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005595 } else if (auto* const_union_array = &sn->getConstArray()){
5596 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005597 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5598 builder.addName(id, sn->getName().c_str());
5599 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005600 }
5601 }
qining4f4bb812016-04-03 23:55:17 -04005602
5603 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5604 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005605 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005606 exit(1);
5607 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005608}
5609
John Kessenich140f3df2015-06-26 16:58:36 -06005610// Use 'consts' as the flattened glslang source of scalar constants to recursively
5611// build the aggregate SPIR-V constant.
5612//
5613// If there are not enough elements present in 'consts', 0 will be substituted;
5614// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5615//
qining08408382016-03-21 09:51:37 -04005616spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005617{
5618 // vector of constants for SPIR-V
5619 std::vector<spv::Id> spvConsts;
5620
5621 // Type is used for struct and array constants
5622 spv::Id typeId = convertGlslangToSpvType(glslangType);
5623
5624 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005625 glslang::TType elementType(glslangType, 0);
5626 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005627 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005628 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005629 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005630 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005631 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005632 } else if (glslangType.getStruct()) {
5633 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5634 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005635 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005636 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005637 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5638 bool zero = nextConst >= consts.size();
5639 switch (glslangType.getBasicType()) {
5640 case glslang::EbtInt:
5641 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5642 break;
5643 case glslang::EbtUint:
5644 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5645 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005646 case glslang::EbtInt64:
5647 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5648 break;
5649 case glslang::EbtUint64:
5650 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5651 break;
Rex Xucabbb782017-03-24 13:41:14 +08005652#ifdef AMD_EXTENSIONS
5653 case glslang::EbtInt16:
5654 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5655 break;
5656 case glslang::EbtUint16:
5657 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5658 break;
5659#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005660 case glslang::EbtFloat:
5661 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5662 break;
5663 case glslang::EbtDouble:
5664 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5665 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005666#ifdef AMD_EXTENSIONS
5667 case glslang::EbtFloat16:
5668 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5669 break;
5670#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005671 case glslang::EbtBool:
5672 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5673 break;
5674 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005675 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005676 break;
5677 }
5678 ++nextConst;
5679 }
5680 } else {
5681 // we have a non-aggregate (scalar) constant
5682 bool zero = nextConst >= consts.size();
5683 spv::Id scalar = 0;
5684 switch (glslangType.getBasicType()) {
5685 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005686 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005687 break;
5688 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005689 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005690 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005691 case glslang::EbtInt64:
5692 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5693 break;
5694 case glslang::EbtUint64:
5695 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5696 break;
Rex Xucabbb782017-03-24 13:41:14 +08005697#ifdef AMD_EXTENSIONS
5698 case glslang::EbtInt16:
5699 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5700 break;
5701 case glslang::EbtUint16:
5702 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5703 break;
5704#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005705 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005706 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005707 break;
5708 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005709 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005710 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005711#ifdef AMD_EXTENSIONS
5712 case glslang::EbtFloat16:
5713 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5714 break;
5715#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005716 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005717 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005718 break;
5719 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005720 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005721 break;
5722 }
5723 ++nextConst;
5724 return scalar;
5725 }
5726
5727 return builder.makeCompositeConstant(typeId, spvConsts);
5728}
5729
John Kessenich7c1aa102015-10-15 13:29:11 -06005730// Return true if the node is a constant or symbol whose reading has no
5731// non-trivial observable cost or effect.
5732bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5733{
5734 // don't know what this is
5735 if (node == nullptr)
5736 return false;
5737
5738 // a constant is safe
5739 if (node->getAsConstantUnion() != nullptr)
5740 return true;
5741
5742 // not a symbol means non-trivial
5743 if (node->getAsSymbolNode() == nullptr)
5744 return false;
5745
5746 // a symbol, depends on what's being read
5747 switch (node->getType().getQualifier().storage) {
5748 case glslang::EvqTemporary:
5749 case glslang::EvqGlobal:
5750 case glslang::EvqIn:
5751 case glslang::EvqInOut:
5752 case glslang::EvqConst:
5753 case glslang::EvqConstReadOnly:
5754 case glslang::EvqUniform:
5755 return true;
5756 default:
5757 return false;
5758 }
qining25262b32016-05-06 17:25:16 -04005759}
John Kessenich7c1aa102015-10-15 13:29:11 -06005760
5761// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005762// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005763// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005764// Return true if trivial.
5765bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5766{
5767 if (node == nullptr)
5768 return false;
5769
John Kessenich84cc15f2017-05-24 16:44:47 -06005770 // count non scalars as trivial, as well as anything coming from HLSL
5771 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005772 return true;
5773
John Kessenich7c1aa102015-10-15 13:29:11 -06005774 // symbols and constants are trivial
5775 if (isTrivialLeaf(node))
5776 return true;
5777
5778 // otherwise, it needs to be a simple operation or one or two leaf nodes
5779
5780 // not a simple operation
5781 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5782 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5783 if (binaryNode == nullptr && unaryNode == nullptr)
5784 return false;
5785
5786 // not on leaf nodes
5787 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5788 return false;
5789
5790 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5791 return false;
5792 }
5793
5794 switch (node->getAsOperator()->getOp()) {
5795 case glslang::EOpLogicalNot:
5796 case glslang::EOpConvIntToBool:
5797 case glslang::EOpConvUintToBool:
5798 case glslang::EOpConvFloatToBool:
5799 case glslang::EOpConvDoubleToBool:
5800 case glslang::EOpEqual:
5801 case glslang::EOpNotEqual:
5802 case glslang::EOpLessThan:
5803 case glslang::EOpGreaterThan:
5804 case glslang::EOpLessThanEqual:
5805 case glslang::EOpGreaterThanEqual:
5806 case glslang::EOpIndexDirect:
5807 case glslang::EOpIndexDirectStruct:
5808 case glslang::EOpLogicalXor:
5809 case glslang::EOpAny:
5810 case glslang::EOpAll:
5811 return true;
5812 default:
5813 return false;
5814 }
5815}
5816
5817// Emit short-circuiting code, where 'right' is never evaluated unless
5818// the left side is true (for &&) or false (for ||).
5819spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5820{
5821 spv::Id boolTypeId = builder.makeBoolType();
5822
5823 // emit left operand
5824 builder.clearAccessChain();
5825 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005826 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005827
5828 // Operands to accumulate OpPhi operands
5829 std::vector<spv::Id> phiOperands;
5830 // accumulate left operand's phi information
5831 phiOperands.push_back(leftId);
5832 phiOperands.push_back(builder.getBuildPoint()->getId());
5833
5834 // Make the two kinds of operation symmetric with a "!"
5835 // || => emit "if (! left) result = right"
5836 // && => emit "if ( left) result = right"
5837 //
5838 // TODO: this runtime "not" for || could be avoided by adding functionality
5839 // to 'builder' to have an "else" without an "then"
5840 if (op == glslang::EOpLogicalOr)
5841 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5842
5843 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005844 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005845
5846 // emit right operand as the "then" part of the "if"
5847 builder.clearAccessChain();
5848 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005849 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005850
5851 // accumulate left operand's phi information
5852 phiOperands.push_back(rightId);
5853 phiOperands.push_back(builder.getBuildPoint()->getId());
5854
5855 // finish the "if"
5856 ifBuilder.makeEndIf();
5857
5858 // phi together the two results
5859 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5860}
5861
Rex Xu9d93a232016-05-05 12:30:44 +08005862// Return type Id of the imported set of extended instructions corresponds to the name.
5863// Import this set if it has not been imported yet.
5864spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5865{
5866 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5867 return extBuiltinMap[name];
5868 else {
Rex Xu51596642016-09-21 18:56:12 +08005869 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005870 spv::Id extBuiltins = builder.import(name);
5871 extBuiltinMap[name] = extBuiltins;
5872 return extBuiltins;
5873 }
5874}
5875
John Kessenich140f3df2015-06-26 16:58:36 -06005876}; // end anonymous namespace
5877
5878namespace glslang {
5879
John Kessenich68d78fd2015-07-12 19:28:10 -06005880void GetSpirvVersion(std::string& version)
5881{
John Kessenich9e55f632015-07-15 10:03:39 -06005882 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005883 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005884 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005885 version = buf;
5886}
5887
John Kessenich140f3df2015-06-26 16:58:36 -06005888// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005889void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005890{
5891 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005892 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005893 if (out.fail())
5894 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005895 for (int i = 0; i < (int)spirv.size(); ++i) {
5896 unsigned int word = spirv[i];
5897 out.write((const char*)&word, 4);
5898 }
5899 out.close();
5900}
5901
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005902// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005903void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005904{
5905 std::ofstream out;
5906 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005907 if (out.fail())
5908 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005909 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005910 if (varName != nullptr) {
5911 out << "\t #pragma once" << std::endl;
5912 out << "const uint32_t " << varName << "[] = {" << std::endl;
5913 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005914 const int WORDS_PER_LINE = 8;
5915 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5916 out << "\t";
5917 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5918 const unsigned int word = spirv[i + j];
5919 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5920 if (i + j + 1 < (int)spirv.size()) {
5921 out << ",";
5922 }
5923 }
5924 out << std::endl;
5925 }
Flavio15017db2017-02-15 14:29:33 -08005926 if (varName != nullptr) {
5927 out << "};";
5928 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005929 out.close();
5930}
5931
John Kessenich140f3df2015-06-26 16:58:36 -06005932//
5933// Set up the glslang traversal
5934//
John Kessenich121853f2017-05-31 17:11:16 -06005935void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005936{
Lei Zhang17535f72016-05-04 15:55:59 -04005937 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005938 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005939}
5940
John Kessenich121853f2017-05-31 17:11:16 -06005941void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5942 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005943{
John Kessenich140f3df2015-06-26 16:58:36 -06005944 TIntermNode* root = intermediate.getTreeRoot();
5945
5946 if (root == 0)
5947 return;
5948
John Kessenich121853f2017-05-31 17:11:16 -06005949 glslang::SpvOptions defaultOptions;
5950 if (options == nullptr)
5951 options = &defaultOptions;
5952
John Kessenich140f3df2015-06-26 16:58:36 -06005953 glslang::GetThreadPoolAllocator().push();
5954
John Kessenich121853f2017-05-31 17:11:16 -06005955 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005956 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005957 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005958 it.dumpSpv(spirv);
5959
5960 glslang::GetThreadPoolAllocator().pop();
5961}
5962
5963}; // end namespace glslang