blob: 2899a741db66e1ff7de56cd8176275ae5e027941 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
John Kessenich121853f2017-05-31 17:11:16 -0600104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800125 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600126 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600127 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600128 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
129 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600130 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
131 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
132 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600133 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700134 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600135 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600136 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
137 glslang::TLayoutPacking, const glslang::TQualifier&);
138 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
139 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700140 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700141 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800142 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600143 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700144 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700145 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
147 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100148 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600149
John Kessenich6fccb3c2016-09-19 16:01:41 -0600150 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 void makeFunctions(const glslang::TIntermSequence&);
152 void makeGlobalInitializers(const glslang::TIntermSequence&);
153 void visitFunctions(const glslang::TIntermSequence&);
154 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800155 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600156 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
157 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600158 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
159
qining25262b32016-05-06 17:25:16 -0400160 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
161 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
162 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800163 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800164 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800166 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800167 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800168 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600169 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800170 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
172 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700173 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700175 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400176 spv::Id createSpvConstant(const glslang::TIntermTyped&);
177 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600178 bool isTrivialLeaf(const glslang::TIntermTyped* node);
179 bool isTrivial(const glslang::TIntermTyped* node);
180 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800181 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich121853f2017-05-31 17:11:16 -0600183 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600184 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600185 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700186 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600187 int sequenceDepth;
188
Lei Zhang17535f72016-05-04 15:55:59 -0400189 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400190
John Kessenich140f3df2015-06-26 16:58:36 -0600191 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
192 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700193 bool inEntryPoint;
194 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700195 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700196 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600197 const glslang::TIntermediate* glslangIntermediate;
198 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800199 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600200
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600202 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600203 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700204 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600205 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600206 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600207};
208
209//
210// Helper functions for translating glslang representations to SPIR-V enumerants.
211//
212
213// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700214spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600215{
John Kessenich66e2faf2016-03-12 18:34:36 -0700216 switch (source) {
217 case glslang::EShSourceGlsl:
218 switch (profile) {
219 case ENoProfile:
220 case ECoreProfile:
221 case ECompatibilityProfile:
222 return spv::SourceLanguageGLSL;
223 case EEsProfile:
224 return spv::SourceLanguageESSL;
225 default:
226 return spv::SourceLanguageUnknown;
227 }
228 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600229 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600230 default:
231 return spv::SourceLanguageUnknown;
232 }
233}
234
235// Translate glslang language (stage) to SPIR-V execution model.
236spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
237{
238 switch (stage) {
239 case EShLangVertex: return spv::ExecutionModelVertex;
240 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
241 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
242 case EShLangGeometry: return spv::ExecutionModelGeometry;
243 case EShLangFragment: return spv::ExecutionModelFragment;
244 case EShLangCompute: return spv::ExecutionModelGLCompute;
245 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600247 return spv::ExecutionModelFragment;
248 }
249}
250
John Kessenich140f3df2015-06-26 16:58:36 -0600251// Translate glslang sampler type to SPIR-V dimensionality.
252spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
253{
254 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700255 case glslang::Esd1D: return spv::Dim1D;
256 case glslang::Esd2D: return spv::Dim2D;
257 case glslang::Esd3D: return spv::Dim3D;
258 case glslang::EsdCube: return spv::DimCube;
259 case glslang::EsdRect: return spv::DimRect;
260 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700261 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::Dim2D;
265 }
266}
267
John Kessenichf6640762016-08-01 19:44:00 -0600268// Translate glslang precision to SPIR-V precision decorations.
269spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600270{
John Kessenichf6640762016-08-01 19:44:00 -0600271 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700272 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600273 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::NoPrecision;
276 }
277}
278
John Kessenichf6640762016-08-01 19:44:00 -0600279// Translate glslang type to SPIR-V precision decorations.
280spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
281{
282 return TranslatePrecisionDecoration(type.getQualifier().precision);
283}
284
John Kessenich140f3df2015-06-26 16:58:36 -0600285// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600286spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600287{
288 if (type.getBasicType() == glslang::EbtBlock) {
289 switch (type.getQualifier().storage) {
290 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600291 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 case glslang::EvqVaryingIn: return spv::DecorationBlock;
293 case glslang::EvqVaryingOut: return spv::DecorationBlock;
294 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700295 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600296 break;
297 }
298 }
299
John Kessenich4016e382016-07-15 11:53:56 -0600300 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600301}
302
Rex Xu1da878f2016-02-21 20:59:01 +0800303// Translate glslang type to SPIR-V memory decorations.
304void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
305{
306 if (qualifier.coherent)
307 memory.push_back(spv::DecorationCoherent);
308 if (qualifier.volatil)
309 memory.push_back(spv::DecorationVolatile);
310 if (qualifier.restrict)
311 memory.push_back(spv::DecorationRestrict);
312 if (qualifier.readonly)
313 memory.push_back(spv::DecorationNonWritable);
314 if (qualifier.writeonly)
315 memory.push_back(spv::DecorationNonReadable);
316}
317
John Kessenich140f3df2015-06-26 16:58:36 -0600318// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700319spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600320{
321 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700322 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600323 case glslang::ElmRowMajor:
324 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700327 default:
328 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600329 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600330 }
331 } else {
332 switch (type.getBasicType()) {
333 default:
John Kessenich4016e382016-07-15 11:53:56 -0600334 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 break;
336 case glslang::EbtBlock:
337 switch (type.getQualifier().storage) {
338 case glslang::EvqUniform:
339 case glslang::EvqBuffer:
340 switch (type.getQualifier().layoutPacking) {
341 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
343 default:
John Kessenich4016e382016-07-15 11:53:56 -0600344 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600345 }
346 case glslang::EvqVaryingIn:
347 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700348 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600349 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600350 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700351 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 }
355 }
356}
357
358// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600359// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700360// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800361spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600362{
Rex Xubbceed72016-05-21 09:40:44 +0800363 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700364 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600365 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800366 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700367 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700368 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600369 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800370#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800371 else if (qualifier.explicitInterp) {
372 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800373 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800374 }
Rex Xu9d93a232016-05-05 12:30:44 +0800375#endif
Rex Xubbceed72016-05-21 09:40:44 +0800376 else
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378}
379
380// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600381// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800382// should be applied.
383spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
384{
385 if (qualifier.patch)
386 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700387 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600388 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700389 else if (qualifier.sample) {
390 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700392 } else
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600394}
395
John Kessenich92187592016-02-01 13:45:25 -0700396// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600398{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationInvariant;
401 else
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600403}
404
qining9220dbb2016-05-04 17:34:38 -0400405// If glslang type is noContraction, return SPIR-V NoContraction decoration.
406spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
407{
408 if (qualifier.noContraction)
409 return spv::DecorationNoContraction;
410 else
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400412}
413
David Netoa901ffe2016-06-08 14:11:40 +0100414// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
415// associated capabilities when required. For some built-in variables, a capability
416// is generated only when using the variable in an executable instruction, but not when
417// just declaring a struct member variable with it. This is true for PointSize,
418// ClipDistance, and CullDistance.
419spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600420{
421 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700422 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600423 // Defer adding the capability until the built-in is actually used.
424 if (! memberDeclaration) {
425 switch (glslangIntermediate->getStage()) {
426 case EShLangGeometry:
427 builder.addCapability(spv::CapabilityGeometryPointSize);
428 break;
429 case EShLangTessControl:
430 case EShLangTessEvaluation:
431 builder.addCapability(spv::CapabilityTessellationPointSize);
432 break;
433 default:
434 break;
435 }
John Kessenich92187592016-02-01 13:45:25 -0700436 }
437 return spv::BuiltInPointSize;
438
John Kessenichebb50532016-05-16 19:22:05 -0600439 // These *Distance capabilities logically belong here, but if the member is declared and
440 // then never used, consumers of SPIR-V prefer the capability not be declared.
441 // They are now generated when used, rather than here when declared.
442 // Potentially, the specification should be more clear what the minimum
443 // use needed is to trigger the capability.
444 //
John Kessenich92187592016-02-01 13:45:25 -0700445 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100446 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800447 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700448 return spv::BuiltInClipDistance;
449
450 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100451 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800452 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700453 return spv::BuiltInCullDistance;
454
455 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800456 if (!memberDeclaration) {
457 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800458#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800459 if (glslangIntermediate->getStage() == EShLangVertex ||
460 glslangIntermediate->getStage() == EShLangTessControl ||
461 glslangIntermediate->getStage() == EShLangTessEvaluation) {
462
463 builder.addExtension(spv::E_SPV_NV_viewport_array2);
464 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
465 }
chaoc771d89f2017-01-13 01:10:53 -0800466#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800467 }
John Kessenich92187592016-02-01 13:45:25 -0700468 return spv::BuiltInViewportIndex;
469
John Kessenich5e801132016-02-15 11:09:46 -0700470 case glslang::EbvSampleId:
471 builder.addCapability(spv::CapabilitySampleRateShading);
472 return spv::BuiltInSampleId;
473
474 case glslang::EbvSamplePosition:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSamplePosition;
477
478 case glslang::EbvSampleMask:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSampleMask;
481
John Kessenich78a45572016-07-08 14:05:15 -0600482 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800483 if (!memberDeclaration) {
484 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
489
chaoc771d89f2017-01-13 01:10:53 -0800490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
chaoc771d89f2017-01-13 01:10:53 -0800493#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800494 }
495
John Kessenich78a45572016-07-08 14:05:15 -0600496 return spv::BuiltInLayer;
497
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvVertexId: return spv::BuiltInVertexId;
500 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700501 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
502 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800503
John Kessenichda581a22015-10-14 14:10:30 -0600504 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800505 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
506 builder.addCapability(spv::CapabilityDrawParameters);
507 return spv::BuiltInBaseVertex;
508
John Kessenichda581a22015-10-14 14:10:30 -0600509 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800510 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
511 builder.addCapability(spv::CapabilityDrawParameters);
512 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200513
John Kessenichda581a22015-10-14 14:10:30 -0600514 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800515 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
516 builder.addCapability(spv::CapabilityDrawParameters);
517 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200518
519 case glslang::EbvPrimitiveId:
520 if (glslangIntermediate->getStage() == EShLangFragment)
521 builder.addCapability(spv::CapabilityGeometry);
522 return spv::BuiltInPrimitiveId;
523
Rex Xu37cdcee2017-06-29 17:46:34 +0800524 case glslang::EbvFragStencilRef:
525 logger->missingFunctionality("shader stencil export");
526 return spv::BuiltInMax;
527
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
530 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
531 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
532 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
533 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
534 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
535 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600536 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
537 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
538 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
539 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
540 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
541 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
542 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
543 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800544
Rex Xu574ab042016-04-14 16:53:07 +0800545 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800546 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800547 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
548 return spv::BuiltInSubgroupSize;
549
Rex Xu574ab042016-04-14 16:53:07 +0800550 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800551 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800552 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
553 return spv::BuiltInSubgroupLocalInvocationId;
554
Rex Xu574ab042016-04-14 16:53:07 +0800555 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800556 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
557 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
558 return spv::BuiltInSubgroupEqMaskKHR;
559
Rex Xu574ab042016-04-14 16:53:07 +0800560 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800561 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
562 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
563 return spv::BuiltInSubgroupGeMaskKHR;
564
Rex Xu574ab042016-04-14 16:53:07 +0800565 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800566 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
567 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
568 return spv::BuiltInSubgroupGtMaskKHR;
569
Rex Xu574ab042016-04-14 16:53:07 +0800570 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
572 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
573 return spv::BuiltInSubgroupLeMaskKHR;
574
Rex Xu574ab042016-04-14 16:53:07 +0800575 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800576 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
577 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
578 return spv::BuiltInSubgroupLtMaskKHR;
579
Rex Xu9d93a232016-05-05 12:30:44 +0800580#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800581 case glslang::EbvBaryCoordNoPersp:
582 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
583 return spv::BuiltInBaryCoordNoPerspAMD;
584
585 case glslang::EbvBaryCoordNoPerspCentroid:
586 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
587 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
588
589 case glslang::EbvBaryCoordNoPerspSample:
590 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
591 return spv::BuiltInBaryCoordNoPerspSampleAMD;
592
593 case glslang::EbvBaryCoordSmooth:
594 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
595 return spv::BuiltInBaryCoordSmoothAMD;
596
597 case glslang::EbvBaryCoordSmoothCentroid:
598 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
599 return spv::BuiltInBaryCoordSmoothCentroidAMD;
600
601 case glslang::EbvBaryCoordSmoothSample:
602 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
603 return spv::BuiltInBaryCoordSmoothSampleAMD;
604
605 case glslang::EbvBaryCoordPullModel:
606 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
607 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800608#endif
chaoc771d89f2017-01-13 01:10:53 -0800609
John Kessenich6c8aaac2017-02-27 01:20:51 -0700610 case glslang::EbvDeviceIndex:
611 builder.addExtension(spv::E_SPV_KHR_device_group);
612 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700613 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700614
615 case glslang::EbvViewIndex:
616 builder.addExtension(spv::E_SPV_KHR_multiview);
617 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700618 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700619
chaoc771d89f2017-01-13 01:10:53 -0800620#ifdef NV_EXTENSIONS
621 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800622 if (!memberDeclaration) {
623 builder.addExtension(spv::E_SPV_NV_viewport_array2);
624 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
625 }
chaoc771d89f2017-01-13 01:10:53 -0800626 return spv::BuiltInViewportMaskNV;
627 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800628 if (!memberDeclaration) {
629 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
630 builder.addCapability(spv::CapabilityShaderStereoViewNV);
631 }
chaoc771d89f2017-01-13 01:10:53 -0800632 return spv::BuiltInSecondaryPositionNV;
633 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800634 if (!memberDeclaration) {
635 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
636 builder.addCapability(spv::CapabilityShaderStereoViewNV);
637 }
chaoc771d89f2017-01-13 01:10:53 -0800638 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800639 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800640 if (!memberDeclaration) {
641 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
642 builder.addCapability(spv::CapabilityPerViewAttributesNV);
643 }
chaocdf3956c2017-02-14 14:52:34 -0800644 return spv::BuiltInPositionPerViewNV;
645 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800646 if (!memberDeclaration) {
647 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
648 builder.addCapability(spv::CapabilityPerViewAttributesNV);
649 }
chaocdf3956c2017-02-14 14:52:34 -0800650 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800651#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800652 default:
653 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600654 }
655}
656
Rex Xufc618912015-09-09 16:42:49 +0800657// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700658spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800659{
660 assert(type.getBasicType() == glslang::EbtSampler);
661
John Kessenich5d0fa972016-02-15 11:57:00 -0700662 // Check for capabilities
663 switch (type.getQualifier().layoutFormat) {
664 case glslang::ElfRg32f:
665 case glslang::ElfRg16f:
666 case glslang::ElfR11fG11fB10f:
667 case glslang::ElfR16f:
668 case glslang::ElfRgba16:
669 case glslang::ElfRgb10A2:
670 case glslang::ElfRg16:
671 case glslang::ElfRg8:
672 case glslang::ElfR16:
673 case glslang::ElfR8:
674 case glslang::ElfRgba16Snorm:
675 case glslang::ElfRg16Snorm:
676 case glslang::ElfRg8Snorm:
677 case glslang::ElfR16Snorm:
678 case glslang::ElfR8Snorm:
679
680 case glslang::ElfRg32i:
681 case glslang::ElfRg16i:
682 case glslang::ElfRg8i:
683 case glslang::ElfR16i:
684 case glslang::ElfR8i:
685
686 case glslang::ElfRgb10a2ui:
687 case glslang::ElfRg32ui:
688 case glslang::ElfRg16ui:
689 case glslang::ElfRg8ui:
690 case glslang::ElfR16ui:
691 case glslang::ElfR8ui:
692 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
693 break;
694
695 default:
696 break;
697 }
698
699 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800700 switch (type.getQualifier().layoutFormat) {
701 case glslang::ElfNone: return spv::ImageFormatUnknown;
702 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
703 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
704 case glslang::ElfR32f: return spv::ImageFormatR32f;
705 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
706 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
707 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
708 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
709 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
710 case glslang::ElfR16f: return spv::ImageFormatR16f;
711 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
712 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
713 case glslang::ElfRg16: return spv::ImageFormatRg16;
714 case glslang::ElfRg8: return spv::ImageFormatRg8;
715 case glslang::ElfR16: return spv::ImageFormatR16;
716 case glslang::ElfR8: return spv::ImageFormatR8;
717 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
718 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
719 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
720 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
721 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
722 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
723 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
724 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
725 case glslang::ElfR32i: return spv::ImageFormatR32i;
726 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
727 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
728 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
729 case glslang::ElfR16i: return spv::ImageFormatR16i;
730 case glslang::ElfR8i: return spv::ImageFormatR8i;
731 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
732 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
733 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
734 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
735 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
736 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
737 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
738 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
739 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
740 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600741 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800742 }
743}
744
Rex Xu57e65922017-07-04 23:23:40 +0800745spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
746{
747 switch (selectionControl) {
748 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
749 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
750 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
751 default: return spv::SelectionControlMaskNone;
752 }
753}
754
steve-lunargf1709e72017-05-02 20:14:50 -0600755spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
756{
757 switch (loopControl) {
758 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
759 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
760 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
761 // TODO: DependencyInfinite
762 // TODO: DependencyLength
763 default: return spv::LoopControlMaskNone;
764 }
765}
766
John Kessenicha5c5fb62017-05-05 05:09:58 -0600767// Translate glslang type to SPIR-V storage class.
768spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
769{
770 if (type.getQualifier().isPipeInput())
771 return spv::StorageClassInput;
772 else if (type.getQualifier().isPipeOutput())
773 return spv::StorageClassOutput;
774 else if (type.getBasicType() == glslang::EbtAtomicUint)
775 return spv::StorageClassAtomicCounter;
776 else if (type.containsOpaque())
777 return spv::StorageClassUniformConstant;
778 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
779 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
780 return spv::StorageClassStorageBuffer;
781 } else if (type.getQualifier().isUniformOrBuffer()) {
782 if (type.getQualifier().layoutPushConstant)
783 return spv::StorageClassPushConstant;
784 if (type.getBasicType() == glslang::EbtBlock)
785 return spv::StorageClassUniform;
786 else
787 return spv::StorageClassUniformConstant;
788 } else {
789 switch (type.getQualifier().storage) {
790 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
791 case glslang::EvqGlobal: return spv::StorageClassPrivate;
792 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
793 case glslang::EvqTemporary: return spv::StorageClassFunction;
794 default:
795 assert(0);
796 return spv::StorageClassFunction;
797 }
798 }
799}
800
qining25262b32016-05-06 17:25:16 -0400801// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700802// descriptor set.
803bool IsDescriptorResource(const glslang::TType& type)
804{
John Kessenichf7497e22016-03-08 21:36:22 -0700805 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700806 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700807 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700808
809 // non block...
810 // basically samplerXXX/subpass/sampler/texture are all included
811 // if they are the global-scope-class, not the function parameter
812 // (or local, if they ever exist) class.
813 if (type.getBasicType() == glslang::EbtSampler)
814 return type.getQualifier().isUniformOrBuffer();
815
816 // None of the above.
817 return false;
818}
819
John Kesseniche0b6cad2015-12-24 10:30:13 -0700820void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
821{
822 if (child.layoutMatrix == glslang::ElmNone)
823 child.layoutMatrix = parent.layoutMatrix;
824
825 if (parent.invariant)
826 child.invariant = true;
827 if (parent.nopersp)
828 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800829#ifdef AMD_EXTENSIONS
830 if (parent.explicitInterp)
831 child.explicitInterp = true;
832#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700833 if (parent.flat)
834 child.flat = true;
835 if (parent.centroid)
836 child.centroid = true;
837 if (parent.patch)
838 child.patch = true;
839 if (parent.sample)
840 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800841 if (parent.coherent)
842 child.coherent = true;
843 if (parent.volatil)
844 child.volatil = true;
845 if (parent.restrict)
846 child.restrict = true;
847 if (parent.readonly)
848 child.readonly = true;
849 if (parent.writeonly)
850 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851}
852
John Kessenichf2b7f332016-09-01 17:05:23 -0600853bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700854{
John Kessenich7b9fa252016-01-21 18:56:57 -0700855 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600856 // - struct members might inherit from a struct declaration
857 // (note that non-block structs don't explicitly inherit,
858 // only implicitly, meaning no decoration involved)
859 // - affect decorations on the struct members
860 // (note smooth does not, and expecting something like volatile
861 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700862 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600863 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864}
865
John Kessenich140f3df2015-06-26 16:58:36 -0600866//
867// Implement the TGlslangToSpvTraverser class.
868//
869
John Kessenich121853f2017-05-31 17:11:16 -0600870TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
871 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
872 : TIntermTraverser(true, false, true),
873 options(options),
874 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600875 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400876 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700877 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600878 glslangIntermediate(glslangIntermediate)
879{
880 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
881
882 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700883 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich121853f2017-05-31 17:11:16 -0600884 if (options.generateDebugInfo) {
885 builder.setSourceFile(glslangIntermediate->getSourceFile());
886 builder.setSourceText(glslangIntermediate->getSourceText());
John Kesseniche485c7a2017-05-31 18:50:53 -0600887 builder.setEmitOpLines();
John Kessenich121853f2017-05-31 17:11:16 -0600888 }
John Kessenich140f3df2015-06-26 16:58:36 -0600889 stdBuiltins = builder.import("GLSL.std.450");
890 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600891 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
892 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600893
894 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600895 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
896 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600897 builder.addSourceExtension(it->c_str());
898
899 // Add the top-level modes for this shader.
900
John Kessenich92187592016-02-01 13:45:25 -0700901 if (glslangIntermediate->getXfbMode()) {
902 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600903 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700904 }
John Kessenich140f3df2015-06-26 16:58:36 -0600905
906 unsigned int mode;
907 switch (glslangIntermediate->getStage()) {
908 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600909 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600910 break;
911
steve-lunarge7412492017-03-23 11:56:07 -0600912 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600913 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600914 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600915
steve-lunarge7412492017-03-23 11:56:07 -0600916 glslang::TLayoutGeometry primitive;
917
918 if (glslangIntermediate->getStage() == EShLangTessControl) {
919 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
920 primitive = glslangIntermediate->getOutputPrimitive();
921 } else {
922 primitive = glslangIntermediate->getInputPrimitive();
923 }
924
925 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700926 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
927 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
928 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600929 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600930 }
John Kessenich4016e382016-07-15 11:53:56 -0600931 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600932 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
933
John Kesseniche6903322015-10-13 16:29:02 -0600934 switch (glslangIntermediate->getVertexSpacing()) {
935 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
936 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
937 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600938 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600939 }
John Kessenich4016e382016-07-15 11:53:56 -0600940 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600941 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
942
943 switch (glslangIntermediate->getVertexOrder()) {
944 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
945 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600946 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600947 }
John Kessenich4016e382016-07-15 11:53:56 -0600948 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600949 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
950
951 if (glslangIntermediate->getPointMode())
952 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600953 break;
954
955 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600956 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600957 switch (glslangIntermediate->getInputPrimitive()) {
958 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
959 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
960 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700961 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600962 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600963 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600964 }
John Kessenich4016e382016-07-15 11:53:56 -0600965 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600966 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600967
John Kessenich140f3df2015-06-26 16:58:36 -0600968 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
969
970 switch (glslangIntermediate->getOutputPrimitive()) {
971 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
972 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
973 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600974 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600975 }
John Kessenich4016e382016-07-15 11:53:56 -0600976 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600977 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
978 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
979 break;
980
981 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600982 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600983 if (glslangIntermediate->getPixelCenterInteger())
984 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600985
John Kessenich140f3df2015-06-26 16:58:36 -0600986 if (glslangIntermediate->getOriginUpperLeft())
987 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600988 else
989 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600990
991 if (glslangIntermediate->getEarlyFragmentTests())
992 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
993
chaocc1204522017-06-30 17:14:30 -0700994 if (glslangIntermediate->getPostDepthCoverage()) {
995 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
996 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
997 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
998 }
999
John Kesseniche6903322015-10-13 16:29:02 -06001000 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001001 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1002 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001003 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001004 }
John Kessenich4016e382016-07-15 11:53:56 -06001005 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001006 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1007
1008 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1009 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001010 break;
1011
1012 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001013 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001014 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1015 glslangIntermediate->getLocalSize(1),
1016 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001017 break;
1018
1019 default:
1020 break;
1021 }
John Kessenich140f3df2015-06-26 16:58:36 -06001022}
1023
John Kessenichfca82622016-11-26 13:23:20 -07001024// Finish creating SPV, after the traversal is complete.
1025void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001026{
John Kessenich517fe7a2016-11-26 13:31:47 -07001027 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001028 builder.setBuildPoint(shaderEntry->getLastBlock());
1029 builder.leaveFunction();
1030 }
1031
John Kessenich7ba63412015-12-20 17:37:07 -07001032 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001033 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1034 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001035
qiningda397332016-03-09 19:54:03 -05001036 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001037}
1038
John Kessenichfca82622016-11-26 13:23:20 -07001039// Write the SPV into 'out'.
1040void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001041{
John Kessenichfca82622016-11-26 13:23:20 -07001042 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001043}
1044
1045//
1046// Implement the traversal functions.
1047//
1048// Return true from interior nodes to have the external traversal
1049// continue on to children. Return false if children were
1050// already processed.
1051//
1052
1053//
qining25262b32016-05-06 17:25:16 -04001054// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001055// - uniform/input reads
1056// - output writes
1057// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1058// - something simple that degenerates into the last bullet
1059//
1060void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1061{
qining75d1d802016-04-06 14:42:01 -04001062 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1063 if (symbol->getType().getQualifier().isSpecConstant())
1064 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1065
John Kessenich140f3df2015-06-26 16:58:36 -06001066 // getSymbolId() will set up all the IO decorations on the first call.
1067 // Formal function parameters were mapped during makeFunctions().
1068 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001069
1070 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1071 if (builder.isPointer(id)) {
1072 spv::StorageClass sc = builder.getStorageClass(id);
1073 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1074 iOSet.insert(id);
1075 }
1076
1077 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001078 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001079 // Prepare to generate code for the access
1080
1081 // L-value chains will be computed left to right. We're on the symbol now,
1082 // which is the left-most part of the access chain, so now is "clear" time,
1083 // followed by setting the base.
1084 builder.clearAccessChain();
1085
1086 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001087 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001088 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001089 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001090 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001091 // These are also pure R-values.
1092 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001093 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001094 builder.setAccessChainRValue(id);
1095 else
1096 builder.setAccessChainLValue(id);
1097 }
1098}
1099
1100bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1101{
John Kesseniche485c7a2017-05-31 18:50:53 -06001102 builder.setLine(node->getLoc().line);
1103
qining40887662016-04-03 22:20:42 -04001104 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1105 if (node->getType().getQualifier().isSpecConstant())
1106 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1107
John Kessenich140f3df2015-06-26 16:58:36 -06001108 // First, handle special cases
1109 switch (node->getOp()) {
1110 case glslang::EOpAssign:
1111 case glslang::EOpAddAssign:
1112 case glslang::EOpSubAssign:
1113 case glslang::EOpMulAssign:
1114 case glslang::EOpVectorTimesMatrixAssign:
1115 case glslang::EOpVectorTimesScalarAssign:
1116 case glslang::EOpMatrixTimesScalarAssign:
1117 case glslang::EOpMatrixTimesMatrixAssign:
1118 case glslang::EOpDivAssign:
1119 case glslang::EOpModAssign:
1120 case glslang::EOpAndAssign:
1121 case glslang::EOpInclusiveOrAssign:
1122 case glslang::EOpExclusiveOrAssign:
1123 case glslang::EOpLeftShiftAssign:
1124 case glslang::EOpRightShiftAssign:
1125 // A bin-op assign "a += b" means the same thing as "a = a + b"
1126 // where a is evaluated before b. For a simple assignment, GLSL
1127 // says to evaluate the left before the right. So, always, left
1128 // node then right node.
1129 {
1130 // get the left l-value, save it away
1131 builder.clearAccessChain();
1132 node->getLeft()->traverse(this);
1133 spv::Builder::AccessChain lValue = builder.getAccessChain();
1134
1135 // evaluate the right
1136 builder.clearAccessChain();
1137 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001138 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001139
1140 if (node->getOp() != glslang::EOpAssign) {
1141 // the left is also an r-value
1142 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001143 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001146 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001147 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001148 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1149 node->getType().getBasicType());
1150
1151 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001152 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001153 }
1154
1155 // store the result
1156 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001157 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001158
1159 // assignments are expressions having an rValue after they are evaluated...
1160 builder.clearAccessChain();
1161 builder.setAccessChainRValue(rValue);
1162 }
1163 return false;
1164 case glslang::EOpIndexDirect:
1165 case glslang::EOpIndexDirectStruct:
1166 {
1167 // Get the left part of the access chain.
1168 node->getLeft()->traverse(this);
1169
1170 // Add the next element in the chain
1171
David Netoa901ffe2016-06-08 14:11:40 +01001172 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001173 if (! node->getLeft()->getType().isArray() &&
1174 node->getLeft()->getType().isVector() &&
1175 node->getOp() == glslang::EOpIndexDirect) {
1176 // This is essentially a hard-coded vector swizzle of size 1,
1177 // so short circuit the access-chain stuff with a swizzle.
1178 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001179 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001180 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001181 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001182 int spvIndex = glslangIndex;
1183 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1184 node->getOp() == glslang::EOpIndexDirectStruct)
1185 {
1186 // This may be, e.g., an anonymous block-member selection, which generally need
1187 // index remapping due to hidden members in anonymous blocks.
1188 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1189 assert(remapper.size() > 0);
1190 spvIndex = remapper[glslangIndex];
1191 }
John Kessenichebb50532016-05-16 19:22:05 -06001192
David Netoa901ffe2016-06-08 14:11:40 +01001193 // normal case for indexing array or structure or block
1194 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1195
1196 // Add capabilities here for accessing PointSize and clip/cull distance.
1197 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001198 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001199 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001200 }
1201 }
1202 return false;
1203 case glslang::EOpIndexIndirect:
1204 {
1205 // Structure or array or vector indirection.
1206 // Will use native SPIR-V access-chain for struct and array indirection;
1207 // matrices are arrays of vectors, so will also work for a matrix.
1208 // Will use the access chain's 'component' for variable index into a vector.
1209
1210 // This adapter is building access chains left to right.
1211 // Set up the access chain to the left.
1212 node->getLeft()->traverse(this);
1213
1214 // save it so that computing the right side doesn't trash it
1215 spv::Builder::AccessChain partial = builder.getAccessChain();
1216
1217 // compute the next index in the chain
1218 builder.clearAccessChain();
1219 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001220 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001221
1222 // restore the saved access chain
1223 builder.setAccessChain(partial);
1224
1225 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001226 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001227 else
John Kessenichfa668da2015-09-13 14:46:30 -06001228 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001229 }
1230 return false;
1231 case glslang::EOpVectorSwizzle:
1232 {
1233 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001234 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001235 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001236 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001237 }
1238 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001239 case glslang::EOpMatrixSwizzle:
1240 logger->missingFunctionality("matrix swizzle");
1241 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001242 case glslang::EOpLogicalOr:
1243 case glslang::EOpLogicalAnd:
1244 {
1245
1246 // These may require short circuiting, but can sometimes be done as straight
1247 // binary operations. The right operand must be short circuited if it has
1248 // side effects, and should probably be if it is complex.
1249 if (isTrivial(node->getRight()->getAsTyped()))
1250 break; // handle below as a normal binary operation
1251 // otherwise, we need to do dynamic short circuiting on the right operand
1252 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1253 builder.clearAccessChain();
1254 builder.setAccessChainRValue(result);
1255 }
1256 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001257 default:
1258 break;
1259 }
1260
1261 // Assume generic binary op...
1262
John Kessenich32cfd492016-02-02 12:37:46 -07001263 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001264 builder.clearAccessChain();
1265 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001266 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001267
John Kessenich32cfd492016-02-02 12:37:46 -07001268 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001269 builder.clearAccessChain();
1270 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001271 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001272
John Kessenich32cfd492016-02-02 12:37:46 -07001273 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001274 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001275 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001276 convertGlslangToSpvType(node->getType()), left, right,
1277 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001278
John Kessenich50e57562015-12-21 21:21:11 -07001279 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001280 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001281 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001282 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001283 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001284 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001285 return false;
1286 }
John Kessenich140f3df2015-06-26 16:58:36 -06001287}
1288
1289bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1290{
John Kesseniche485c7a2017-05-31 18:50:53 -06001291 builder.setLine(node->getLoc().line);
1292
qining40887662016-04-03 22:20:42 -04001293 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1294 if (node->getType().getQualifier().isSpecConstant())
1295 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1296
John Kessenichfc51d282015-08-19 13:34:18 -06001297 spv::Id result = spv::NoResult;
1298
1299 // try texturing first
1300 result = createImageTextureFunctionCall(node);
1301 if (result != spv::NoResult) {
1302 builder.clearAccessChain();
1303 builder.setAccessChainRValue(result);
1304
1305 return false; // done with this node
1306 }
1307
1308 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001309
1310 if (node->getOp() == glslang::EOpArrayLength) {
1311 // Quite special; won't want to evaluate the operand.
1312
1313 // Normal .length() would have been constant folded by the front-end.
1314 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001315 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001316 assert(node->getOperand()->getType().isRuntimeSizedArray());
1317 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1318 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001319 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1320 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001321
1322 builder.clearAccessChain();
1323 builder.setAccessChainRValue(length);
1324
1325 return false;
1326 }
1327
John Kessenichfc51d282015-08-19 13:34:18 -06001328 // Start by evaluating the operand
1329
John Kessenich8c8505c2016-07-26 12:50:38 -06001330 // Does it need a swizzle inversion? If so, evaluation is inverted;
1331 // operate first on the swizzle base, then apply the swizzle.
1332 spv::Id invertedType = spv::NoType;
1333 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1334 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1335 invertedType = getInvertedSwizzleType(*node->getOperand());
1336
John Kessenich140f3df2015-06-26 16:58:36 -06001337 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001338 if (invertedType != spv::NoType)
1339 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1340 else
1341 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001342
Rex Xufc618912015-09-09 16:42:49 +08001343 spv::Id operand = spv::NoResult;
1344
1345 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1346 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001347 node->getOp() == glslang::EOpAtomicCounter ||
1348 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001349 operand = builder.accessChainGetLValue(); // Special case l-value operands
1350 else
John Kessenich32cfd492016-02-02 12:37:46 -07001351 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001352
John Kessenichf6640762016-08-01 19:44:00 -06001353 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001354 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001357 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001358 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001359
1360 // if not, then possibly an operation
1361 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001362 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001363
1364 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001365 if (invertedType)
1366 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1367
John Kessenich140f3df2015-06-26 16:58:36 -06001368 builder.clearAccessChain();
1369 builder.setAccessChainRValue(result);
1370
1371 return false; // done with this node
1372 }
1373
1374 // it must be a special case, check...
1375 switch (node->getOp()) {
1376 case glslang::EOpPostIncrement:
1377 case glslang::EOpPostDecrement:
1378 case glslang::EOpPreIncrement:
1379 case glslang::EOpPreDecrement:
1380 {
1381 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001382 spv::Id one = 0;
1383 if (node->getBasicType() == glslang::EbtFloat)
1384 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001385 else if (node->getBasicType() == glslang::EbtDouble)
1386 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001387#ifdef AMD_EXTENSIONS
1388 else if (node->getBasicType() == glslang::EbtFloat16)
1389 one = builder.makeFloat16Constant(1.0F);
1390#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001391 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1392 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001393#ifdef AMD_EXTENSIONS
1394 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1395 one = builder.makeInt16Constant(1);
1396#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001397 else
1398 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001399 glslang::TOperator op;
1400 if (node->getOp() == glslang::EOpPreIncrement ||
1401 node->getOp() == glslang::EOpPostIncrement)
1402 op = glslang::EOpAdd;
1403 else
1404 op = glslang::EOpSub;
1405
John Kessenichf6640762016-08-01 19:44:00 -06001406 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001407 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001408 convertGlslangToSpvType(node->getType()), operand, one,
1409 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001410 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001411
1412 // The result of operation is always stored, but conditionally the
1413 // consumed result. The consumed result is always an r-value.
1414 builder.accessChainStore(result);
1415 builder.clearAccessChain();
1416 if (node->getOp() == glslang::EOpPreIncrement ||
1417 node->getOp() == glslang::EOpPreDecrement)
1418 builder.setAccessChainRValue(result);
1419 else
1420 builder.setAccessChainRValue(operand);
1421 }
1422
1423 return false;
1424
1425 case glslang::EOpEmitStreamVertex:
1426 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1427 return false;
1428 case glslang::EOpEndStreamPrimitive:
1429 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1430 return false;
1431
1432 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001433 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001434 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001435 }
John Kessenich140f3df2015-06-26 16:58:36 -06001436}
1437
1438bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1439{
qining27e04a02016-04-14 16:40:20 -04001440 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1441 if (node->getType().getQualifier().isSpecConstant())
1442 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1443
John Kessenichfc51d282015-08-19 13:34:18 -06001444 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001445 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1446 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001447
1448 // try texturing
1449 result = createImageTextureFunctionCall(node);
1450 if (result != spv::NoResult) {
1451 builder.clearAccessChain();
1452 builder.setAccessChainRValue(result);
1453
1454 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001455 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001456 // "imageStore" is a special case, which has no result
1457 return false;
1458 }
John Kessenichfc51d282015-08-19 13:34:18 -06001459
John Kessenich140f3df2015-06-26 16:58:36 -06001460 glslang::TOperator binOp = glslang::EOpNull;
1461 bool reduceComparison = true;
1462 bool isMatrix = false;
1463 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001464 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001465
1466 assert(node->getOp());
1467
John Kessenichf6640762016-08-01 19:44:00 -06001468 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001469
1470 switch (node->getOp()) {
1471 case glslang::EOpSequence:
1472 {
1473 if (preVisit)
1474 ++sequenceDepth;
1475 else
1476 --sequenceDepth;
1477
1478 if (sequenceDepth == 1) {
1479 // If this is the parent node of all the functions, we want to see them
1480 // early, so all call points have actual SPIR-V functions to reference.
1481 // In all cases, still let the traverser visit the children for us.
1482 makeFunctions(node->getAsAggregate()->getSequence());
1483
John Kessenich6fccb3c2016-09-19 16:01:41 -06001484 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001485 // anything else gets there, so visit out of order, doing them all now.
1486 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1487
John Kessenich6a60c2f2016-12-08 21:01:59 -07001488 // 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 -06001489 // so do them manually.
1490 visitFunctions(node->getAsAggregate()->getSequence());
1491
1492 return false;
1493 }
1494
1495 return true;
1496 }
1497 case glslang::EOpLinkerObjects:
1498 {
1499 if (visit == glslang::EvPreVisit)
1500 linkageOnly = true;
1501 else
1502 linkageOnly = false;
1503
1504 return true;
1505 }
1506 case glslang::EOpComma:
1507 {
1508 // processing from left to right naturally leaves the right-most
1509 // lying around in the access chain
1510 glslang::TIntermSequence& glslangOperands = node->getSequence();
1511 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1512 glslangOperands[i]->traverse(this);
1513
1514 return false;
1515 }
1516 case glslang::EOpFunction:
1517 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001518 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001519 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001520 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001521 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001522 } else {
1523 handleFunctionEntry(node);
1524 }
1525 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001526 if (inEntryPoint)
1527 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001528 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001529 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001530 }
1531
1532 return true;
1533 case glslang::EOpParameters:
1534 // Parameters will have been consumed by EOpFunction processing, but not
1535 // the body, so we still visited the function node's children, making this
1536 // child redundant.
1537 return false;
1538 case glslang::EOpFunctionCall:
1539 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001540 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001541 if (node->isUserDefined())
1542 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001543 // 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 -07001544 if (result) {
1545 builder.clearAccessChain();
1546 builder.setAccessChainRValue(result);
1547 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001548 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001549
1550 return false;
1551 }
1552 case glslang::EOpConstructMat2x2:
1553 case glslang::EOpConstructMat2x3:
1554 case glslang::EOpConstructMat2x4:
1555 case glslang::EOpConstructMat3x2:
1556 case glslang::EOpConstructMat3x3:
1557 case glslang::EOpConstructMat3x4:
1558 case glslang::EOpConstructMat4x2:
1559 case glslang::EOpConstructMat4x3:
1560 case glslang::EOpConstructMat4x4:
1561 case glslang::EOpConstructDMat2x2:
1562 case glslang::EOpConstructDMat2x3:
1563 case glslang::EOpConstructDMat2x4:
1564 case glslang::EOpConstructDMat3x2:
1565 case glslang::EOpConstructDMat3x3:
1566 case glslang::EOpConstructDMat3x4:
1567 case glslang::EOpConstructDMat4x2:
1568 case glslang::EOpConstructDMat4x3:
1569 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001570 case glslang::EOpConstructIMat2x2:
1571 case glslang::EOpConstructIMat2x3:
1572 case glslang::EOpConstructIMat2x4:
1573 case glslang::EOpConstructIMat3x2:
1574 case glslang::EOpConstructIMat3x3:
1575 case glslang::EOpConstructIMat3x4:
1576 case glslang::EOpConstructIMat4x2:
1577 case glslang::EOpConstructIMat4x3:
1578 case glslang::EOpConstructIMat4x4:
1579 case glslang::EOpConstructUMat2x2:
1580 case glslang::EOpConstructUMat2x3:
1581 case glslang::EOpConstructUMat2x4:
1582 case glslang::EOpConstructUMat3x2:
1583 case glslang::EOpConstructUMat3x3:
1584 case glslang::EOpConstructUMat3x4:
1585 case glslang::EOpConstructUMat4x2:
1586 case glslang::EOpConstructUMat4x3:
1587 case glslang::EOpConstructUMat4x4:
1588 case glslang::EOpConstructBMat2x2:
1589 case glslang::EOpConstructBMat2x3:
1590 case glslang::EOpConstructBMat2x4:
1591 case glslang::EOpConstructBMat3x2:
1592 case glslang::EOpConstructBMat3x3:
1593 case glslang::EOpConstructBMat3x4:
1594 case glslang::EOpConstructBMat4x2:
1595 case glslang::EOpConstructBMat4x3:
1596 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001597#ifdef AMD_EXTENSIONS
1598 case glslang::EOpConstructF16Mat2x2:
1599 case glslang::EOpConstructF16Mat2x3:
1600 case glslang::EOpConstructF16Mat2x4:
1601 case glslang::EOpConstructF16Mat3x2:
1602 case glslang::EOpConstructF16Mat3x3:
1603 case glslang::EOpConstructF16Mat3x4:
1604 case glslang::EOpConstructF16Mat4x2:
1605 case glslang::EOpConstructF16Mat4x3:
1606 case glslang::EOpConstructF16Mat4x4:
1607#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001608 isMatrix = true;
1609 // fall through
1610 case glslang::EOpConstructFloat:
1611 case glslang::EOpConstructVec2:
1612 case glslang::EOpConstructVec3:
1613 case glslang::EOpConstructVec4:
1614 case glslang::EOpConstructDouble:
1615 case glslang::EOpConstructDVec2:
1616 case glslang::EOpConstructDVec3:
1617 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001618#ifdef AMD_EXTENSIONS
1619 case glslang::EOpConstructFloat16:
1620 case glslang::EOpConstructF16Vec2:
1621 case glslang::EOpConstructF16Vec3:
1622 case glslang::EOpConstructF16Vec4:
1623#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001624 case glslang::EOpConstructBool:
1625 case glslang::EOpConstructBVec2:
1626 case glslang::EOpConstructBVec3:
1627 case glslang::EOpConstructBVec4:
1628 case glslang::EOpConstructInt:
1629 case glslang::EOpConstructIVec2:
1630 case glslang::EOpConstructIVec3:
1631 case glslang::EOpConstructIVec4:
1632 case glslang::EOpConstructUint:
1633 case glslang::EOpConstructUVec2:
1634 case glslang::EOpConstructUVec3:
1635 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001636 case glslang::EOpConstructInt64:
1637 case glslang::EOpConstructI64Vec2:
1638 case glslang::EOpConstructI64Vec3:
1639 case glslang::EOpConstructI64Vec4:
1640 case glslang::EOpConstructUint64:
1641 case glslang::EOpConstructU64Vec2:
1642 case glslang::EOpConstructU64Vec3:
1643 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001644#ifdef AMD_EXTENSIONS
1645 case glslang::EOpConstructInt16:
1646 case glslang::EOpConstructI16Vec2:
1647 case glslang::EOpConstructI16Vec3:
1648 case glslang::EOpConstructI16Vec4:
1649 case glslang::EOpConstructUint16:
1650 case glslang::EOpConstructU16Vec2:
1651 case glslang::EOpConstructU16Vec3:
1652 case glslang::EOpConstructU16Vec4:
1653#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001654 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001655 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001656 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001657 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001658 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001659 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001660 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001661 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001662 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001663 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001664 std::vector<spv::Id> constituents;
1665 for (int c = 0; c < (int)arguments.size(); ++c)
1666 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001667 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001668 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001669 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001670 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001671 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001672
1673 builder.clearAccessChain();
1674 builder.setAccessChainRValue(constructed);
1675
1676 return false;
1677 }
1678
1679 // These six are component-wise compares with component-wise results.
1680 // Forward on to createBinaryOperation(), requesting a vector result.
1681 case glslang::EOpLessThan:
1682 case glslang::EOpGreaterThan:
1683 case glslang::EOpLessThanEqual:
1684 case glslang::EOpGreaterThanEqual:
1685 case glslang::EOpVectorEqual:
1686 case glslang::EOpVectorNotEqual:
1687 {
1688 // Map the operation to a binary
1689 binOp = node->getOp();
1690 reduceComparison = false;
1691 switch (node->getOp()) {
1692 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1693 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1694 default: binOp = node->getOp(); break;
1695 }
1696
1697 break;
1698 }
1699 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001700 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001701 binOp = glslang::EOpMul;
1702 break;
1703 case glslang::EOpOuterProduct:
1704 // two vectors multiplied to make a matrix
1705 binOp = glslang::EOpOuterProduct;
1706 break;
1707 case glslang::EOpDot:
1708 {
qining25262b32016-05-06 17:25:16 -04001709 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001710 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001711 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001712 binOp = glslang::EOpMul;
1713 break;
1714 }
1715 case glslang::EOpMod:
1716 // when an aggregate, this is the floating-point mod built-in function,
1717 // which can be emitted by the one in createBinaryOperation()
1718 binOp = glslang::EOpMod;
1719 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001720 case glslang::EOpEmitVertex:
1721 case glslang::EOpEndPrimitive:
1722 case glslang::EOpBarrier:
1723 case glslang::EOpMemoryBarrier:
1724 case glslang::EOpMemoryBarrierAtomicCounter:
1725 case glslang::EOpMemoryBarrierBuffer:
1726 case glslang::EOpMemoryBarrierImage:
1727 case glslang::EOpMemoryBarrierShared:
1728 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001729 case glslang::EOpAllMemoryBarrierWithGroupSync:
1730 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1731 case glslang::EOpWorkgroupMemoryBarrier:
1732 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001733 noReturnValue = true;
1734 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1735 break;
1736
John Kessenich426394d2015-07-23 10:22:48 -06001737 case glslang::EOpAtomicAdd:
1738 case glslang::EOpAtomicMin:
1739 case glslang::EOpAtomicMax:
1740 case glslang::EOpAtomicAnd:
1741 case glslang::EOpAtomicOr:
1742 case glslang::EOpAtomicXor:
1743 case glslang::EOpAtomicExchange:
1744 case glslang::EOpAtomicCompSwap:
1745 atomic = true;
1746 break;
1747
John Kessenich140f3df2015-06-26 16:58:36 -06001748 default:
1749 break;
1750 }
1751
1752 //
1753 // See if it maps to a regular operation.
1754 //
John Kessenich140f3df2015-06-26 16:58:36 -06001755 if (binOp != glslang::EOpNull) {
1756 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1757 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1758 assert(left && right);
1759
1760 builder.clearAccessChain();
1761 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001762 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001763
1764 builder.clearAccessChain();
1765 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001766 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001767
John Kesseniche485c7a2017-05-31 18:50:53 -06001768 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001769 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001770 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001771 left->getType().getBasicType(), reduceComparison);
1772
1773 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001774 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001775 builder.clearAccessChain();
1776 builder.setAccessChainRValue(result);
1777
1778 return false;
1779 }
1780
John Kessenich426394d2015-07-23 10:22:48 -06001781 //
1782 // Create the list of operands.
1783 //
John Kessenich140f3df2015-06-26 16:58:36 -06001784 glslang::TIntermSequence& glslangOperands = node->getSequence();
1785 std::vector<spv::Id> operands;
1786 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001787 // special case l-value operands; there are just a few
1788 bool lvalue = false;
1789 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001790 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001791 case glslang::EOpModf:
1792 if (arg == 1)
1793 lvalue = true;
1794 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001795 case glslang::EOpInterpolateAtSample:
1796 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001797#ifdef AMD_EXTENSIONS
1798 case glslang::EOpInterpolateAtVertex:
1799#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001800 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001801 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001802
1803 // Does it need a swizzle inversion? If so, evaluation is inverted;
1804 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001805 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001806 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1807 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1808 }
Rex Xu7a26c172015-12-08 17:12:09 +08001809 break;
Rex Xud4782c12015-09-06 16:30:11 +08001810 case glslang::EOpAtomicAdd:
1811 case glslang::EOpAtomicMin:
1812 case glslang::EOpAtomicMax:
1813 case glslang::EOpAtomicAnd:
1814 case glslang::EOpAtomicOr:
1815 case glslang::EOpAtomicXor:
1816 case glslang::EOpAtomicExchange:
1817 case glslang::EOpAtomicCompSwap:
1818 if (arg == 0)
1819 lvalue = true;
1820 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001821 case glslang::EOpAddCarry:
1822 case glslang::EOpSubBorrow:
1823 if (arg == 2)
1824 lvalue = true;
1825 break;
1826 case glslang::EOpUMulExtended:
1827 case glslang::EOpIMulExtended:
1828 if (arg >= 2)
1829 lvalue = true;
1830 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001831 default:
1832 break;
1833 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001834 builder.clearAccessChain();
1835 if (invertedType != spv::NoType && arg == 0)
1836 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1837 else
1838 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001839 if (lvalue)
1840 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001841 else {
1842 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001843 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001844 }
John Kessenich140f3df2015-06-26 16:58:36 -06001845 }
John Kessenich426394d2015-07-23 10:22:48 -06001846
John Kesseniche485c7a2017-05-31 18:50:53 -06001847 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001848 if (atomic) {
1849 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001850 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001851 } else {
1852 // Pass through to generic operations.
1853 switch (glslangOperands.size()) {
1854 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001855 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001856 break;
1857 case 1:
qining25262b32016-05-06 17:25:16 -04001858 result = createUnaryOperation(
1859 node->getOp(), precision,
1860 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001861 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001862 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001863 break;
1864 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001865 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001866 break;
1867 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001868 if (invertedType)
1869 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001870 }
1871
1872 if (noReturnValue)
1873 return false;
1874
1875 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001876 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001877 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001878 } else {
1879 builder.clearAccessChain();
1880 builder.setAccessChainRValue(result);
1881 return false;
1882 }
1883}
1884
John Kessenich433e9ff2017-01-26 20:31:11 -07001885// This path handles both if-then-else and ?:
1886// The if-then-else has a node type of void, while
1887// ?: has either a void or a non-void node type
1888//
1889// Leaving the result, when not void:
1890// GLSL only has r-values as the result of a :?, but
1891// if we have an l-value, that can be more efficient if it will
1892// become the base of a complex r-value expression, because the
1893// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001894bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1895{
John Kessenich433e9ff2017-01-26 20:31:11 -07001896 // See if it simple and safe to generate OpSelect instead of using control flow.
1897 // Crucially, side effects must be avoided, and there are performance trade-offs.
1898 // Return true if good idea (and safe) for OpSelect, false otherwise.
1899 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001900 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1901 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001902 return false;
1903
1904 if (node->getTrueBlock() == nullptr ||
1905 node->getFalseBlock() == nullptr)
1906 return false;
1907
1908 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1909 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1910
1911 // return true if a single operand to ? : is okay for OpSelect
1912 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001913 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001914 };
1915
1916 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1917 operandOkay(node->getFalseBlock()->getAsTyped());
1918 };
1919
1920 // Emit OpSelect for this selection.
1921 const auto handleAsOpSelect = [&]() {
1922 node->getCondition()->traverse(this);
1923 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1924 node->getTrueBlock()->traverse(this);
1925 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1926 node->getFalseBlock()->traverse(this);
1927 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1928
John Kesseniche485c7a2017-05-31 18:50:53 -06001929 builder.setLine(node->getLoc().line);
1930
John Kesseniche434ad92017-03-30 10:09:28 -06001931 // smear condition to vector, if necessary (AST is always scalar)
1932 if (builder.isVector(trueValue))
1933 condition = builder.smearScalar(spv::NoPrecision, condition,
1934 builder.makeVectorType(builder.makeBoolType(),
1935 builder.getNumComponents(trueValue)));
1936
1937 spv::Id select = builder.createTriOp(spv::OpSelect,
1938 convertGlslangToSpvType(node->getType()), condition,
1939 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001940 builder.clearAccessChain();
1941 builder.setAccessChainRValue(select);
1942 };
1943
1944 // Try for OpSelect
1945
1946 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001947 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1948 if (node->getType().getQualifier().isSpecConstant())
1949 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1950
John Kessenich433e9ff2017-01-26 20:31:11 -07001951 handleAsOpSelect();
1952 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001953 }
1954
Rex Xu57e65922017-07-04 23:23:40 +08001955 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07001956 // Don't handle results as temporaries, because there will be two names
1957 // and better to leave SSA to later passes.
1958 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1959 ? spv::NoResult
1960 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1961
John Kessenich140f3df2015-06-26 16:58:36 -06001962 // emit the condition before doing anything with selection
1963 node->getCondition()->traverse(this);
1964
Rex Xu57e65922017-07-04 23:23:40 +08001965 // Selection control:
1966 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
1967
John Kessenich140f3df2015-06-26 16:58:36 -06001968 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08001969 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001970
John Kessenich433e9ff2017-01-26 20:31:11 -07001971 // emit the "then" statement
1972 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001973 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001974 if (result != spv::NoResult)
1975 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001976 }
1977
John Kessenich433e9ff2017-01-26 20:31:11 -07001978 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001979 ifBuilder.makeBeginElse();
1980 // emit the "else" statement
1981 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001982 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001983 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001984 }
1985
John Kessenich433e9ff2017-01-26 20:31:11 -07001986 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001987 ifBuilder.makeEndIf();
1988
John Kessenich433e9ff2017-01-26 20:31:11 -07001989 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001990 // GLSL only has r-values as the result of a :?, but
1991 // if we have an l-value, that can be more efficient if it will
1992 // become the base of a complex r-value expression, because the
1993 // next layer copies r-values into memory to use the access-chain mechanism
1994 builder.clearAccessChain();
1995 builder.setAccessChainLValue(result);
1996 }
1997
1998 return false;
1999}
2000
2001bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2002{
2003 // emit and get the condition before doing anything with switch
2004 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002005 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002006
Rex Xu57e65922017-07-04 23:23:40 +08002007 // Selection control:
2008 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2009
John Kessenich140f3df2015-06-26 16:58:36 -06002010 // browse the children to sort out code segments
2011 int defaultSegment = -1;
2012 std::vector<TIntermNode*> codeSegments;
2013 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2014 std::vector<int> caseValues;
2015 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2016 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2017 TIntermNode* child = *c;
2018 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002019 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002020 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002021 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002022 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2023 } else
2024 codeSegments.push_back(child);
2025 }
2026
qining25262b32016-05-06 17:25:16 -04002027 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002028 // statements between the last case and the end of the switch statement
2029 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2030 (int)codeSegments.size() == defaultSegment)
2031 codeSegments.push_back(nullptr);
2032
2033 // make the switch statement
2034 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002035 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002036
2037 // emit all the code in the segments
2038 breakForLoop.push(false);
2039 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2040 builder.nextSwitchSegment(segmentBlocks, s);
2041 if (codeSegments[s])
2042 codeSegments[s]->traverse(this);
2043 else
2044 builder.addSwitchBreak();
2045 }
2046 breakForLoop.pop();
2047
2048 builder.endSwitch(segmentBlocks);
2049
2050 return false;
2051}
2052
2053void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2054{
2055 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002056 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002057
2058 builder.clearAccessChain();
2059 builder.setAccessChainRValue(constant);
2060}
2061
2062bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2063{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002064 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002065 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002066
2067 // Loop control:
2068 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2069
2070 // TODO: dependency length
2071
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002072 // Spec requires back edges to target header blocks, and every header block
2073 // must dominate its merge block. Make a header block first to ensure these
2074 // conditions are met. By definition, it will contain OpLoopMerge, followed
2075 // by a block-ending branch. But we don't want to put any other body/test
2076 // instructions in it, since the body/test may have arbitrary instructions,
2077 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002078 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002079 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002080 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002081 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002082 spv::Block& test = builder.makeNewBlock();
2083 builder.createBranch(&test);
2084
2085 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002086 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002087 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002088 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2089
2090 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002091 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002092 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002093 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002094 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002095 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002096
2097 builder.setBuildPoint(&blocks.continue_target);
2098 if (node->getTerminal())
2099 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002100 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002101 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002102 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002103 builder.createBranch(&blocks.body);
2104
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002105 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002106 builder.setBuildPoint(&blocks.body);
2107 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002108 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002109 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002110 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002111
2112 builder.setBuildPoint(&blocks.continue_target);
2113 if (node->getTerminal())
2114 node->getTerminal()->traverse(this);
2115 if (node->getTest()) {
2116 node->getTest()->traverse(this);
2117 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002118 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002119 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002120 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002121 // TODO: unless there was a break/return/discard instruction
2122 // somewhere in the body, this is an infinite loop, so we should
2123 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002124 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002125 }
John Kessenich140f3df2015-06-26 16:58:36 -06002126 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002127 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002128 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002129 return false;
2130}
2131
2132bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2133{
2134 if (node->getExpression())
2135 node->getExpression()->traverse(this);
2136
John Kesseniche485c7a2017-05-31 18:50:53 -06002137 builder.setLine(node->getLoc().line);
2138
John Kessenich140f3df2015-06-26 16:58:36 -06002139 switch (node->getFlowOp()) {
2140 case glslang::EOpKill:
2141 builder.makeDiscard();
2142 break;
2143 case glslang::EOpBreak:
2144 if (breakForLoop.top())
2145 builder.createLoopExit();
2146 else
2147 builder.addSwitchBreak();
2148 break;
2149 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002150 builder.createLoopContinue();
2151 break;
2152 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002153 if (node->getExpression()) {
2154 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2155 spv::Id returnId = accessChainLoad(glslangReturnType);
2156 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2157 builder.clearAccessChain();
2158 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2159 builder.setAccessChainLValue(copyId);
2160 multiTypeStore(glslangReturnType, returnId);
2161 returnId = builder.createLoad(copyId);
2162 }
2163 builder.makeReturn(false, returnId);
2164 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002165 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002166
2167 builder.clearAccessChain();
2168 break;
2169
2170 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002171 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002172 break;
2173 }
2174
2175 return false;
2176}
2177
2178spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2179{
qining25262b32016-05-06 17:25:16 -04002180 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002181 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002182 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002183 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002184 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002185 }
2186
2187 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002188 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002189 spv::Id spvType = convertGlslangToSpvType(node->getType());
2190
Rex Xuf89ad982017-04-07 23:22:33 +08002191#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002192 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2193 node->getType().containsBasicType(glslang::EbtInt16) ||
2194 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002195 if (contains16BitType) {
2196 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2197 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2198 builder.addCapability(spv::CapabilityStorageInputOutput16);
2199 } else if (storageClass == spv::StorageClassPushConstant) {
2200 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2201 builder.addCapability(spv::CapabilityStoragePushConstant16);
2202 } else if (storageClass == spv::StorageClassUniform) {
2203 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2204 builder.addCapability(spv::CapabilityStorageUniform16);
2205 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2206 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2207 }
2208 }
2209#endif
2210
John Kessenich140f3df2015-06-26 16:58:36 -06002211 const char* name = node->getName().c_str();
2212 if (glslang::IsAnonymous(name))
2213 name = "";
2214
2215 return builder.createVariable(storageClass, spvType, name);
2216}
2217
2218// Return type Id of the sampled type.
2219spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2220{
2221 switch (sampler.type) {
2222 case glslang::EbtFloat: return builder.makeFloatType(32);
2223 case glslang::EbtInt: return builder.makeIntType(32);
2224 case glslang::EbtUint: return builder.makeUintType(32);
2225 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002226 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002227 return builder.makeFloatType(32);
2228 }
2229}
2230
John Kessenich8c8505c2016-07-26 12:50:38 -06002231// If node is a swizzle operation, return the type that should be used if
2232// the swizzle base is first consumed by another operation, before the swizzle
2233// is applied.
2234spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2235{
John Kessenichecba76f2017-01-06 00:34:48 -07002236 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002237 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2238 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2239 else
2240 return spv::NoType;
2241}
2242
2243// When inverting a swizzle with a parent op, this function
2244// will apply the swizzle operation to a completed parent operation.
2245spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2246{
2247 std::vector<unsigned> swizzle;
2248 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2249 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2250}
2251
John Kessenich8c8505c2016-07-26 12:50:38 -06002252// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2253void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2254{
2255 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2256 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2257 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2258}
2259
John Kessenich3ac051e2015-12-20 11:29:16 -07002260// Convert from a glslang type to an SPV type, by calling into a
2261// recursive version of this function. This establishes the inherited
2262// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002263spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2264{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002265 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002266}
2267
2268// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002269// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002270// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002271spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002272{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002273 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002274
2275 switch (type.getBasicType()) {
2276 case glslang::EbtVoid:
2277 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002278 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002279 break;
2280 case glslang::EbtFloat:
2281 spvType = builder.makeFloatType(32);
2282 break;
2283 case glslang::EbtDouble:
2284 spvType = builder.makeFloatType(64);
2285 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002286#ifdef AMD_EXTENSIONS
2287 case glslang::EbtFloat16:
2288 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002289 spvType = builder.makeFloatType(16);
2290 break;
2291#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002292 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002293 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2294 // a 32-bit int where non-0 means true.
2295 if (explicitLayout != glslang::ElpNone)
2296 spvType = builder.makeUintType(32);
2297 else
2298 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002299 break;
2300 case glslang::EbtInt:
2301 spvType = builder.makeIntType(32);
2302 break;
2303 case glslang::EbtUint:
2304 spvType = builder.makeUintType(32);
2305 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002306 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002307 spvType = builder.makeIntType(64);
2308 break;
2309 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002310 spvType = builder.makeUintType(64);
2311 break;
Rex Xucabbb782017-03-24 13:41:14 +08002312#ifdef AMD_EXTENSIONS
2313 case glslang::EbtInt16:
2314 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2315 spvType = builder.makeIntType(16);
2316 break;
2317 case glslang::EbtUint16:
2318 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2319 spvType = builder.makeUintType(16);
2320 break;
2321#endif
John Kessenich426394d2015-07-23 10:22:48 -06002322 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002323 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002324 spvType = builder.makeUintType(32);
2325 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002326 case glslang::EbtSampler:
2327 {
2328 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002329 if (sampler.sampler) {
2330 // pure sampler
2331 spvType = builder.makeSamplerType();
2332 } else {
2333 // an image is present, make its type
2334 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2335 sampler.image ? 2 : 1, TranslateImageFormat(type));
2336 if (sampler.combined) {
2337 // already has both image and sampler, make the combined type
2338 spvType = builder.makeSampledImageType(spvType);
2339 }
John Kessenich55e7d112015-11-15 21:33:39 -07002340 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002341 }
John Kessenich140f3df2015-06-26 16:58:36 -06002342 break;
2343 case glslang::EbtStruct:
2344 case glslang::EbtBlock:
2345 {
2346 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002347 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002348
2349 // Try to share structs for different layouts, but not yet for other
2350 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002351 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002352 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002353 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002354 break;
2355
2356 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002357 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002358 memberRemapper[glslangMembers].resize(glslangMembers->size());
2359 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002360 }
2361 break;
2362 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002363 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002364 break;
2365 }
2366
2367 if (type.isMatrix())
2368 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2369 else {
2370 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2371 if (type.getVectorSize() > 1)
2372 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2373 }
2374
2375 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002376 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2377
John Kessenichc9a80832015-09-12 12:17:44 -06002378 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002379 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002380 // We need to decorate array strides for types needing explicit layout, except blocks.
2381 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002382 // Use a dummy glslang type for querying internal strides of
2383 // arrays of arrays, but using just a one-dimensional array.
2384 glslang::TType simpleArrayType(type, 0); // deference type of the array
2385 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2386 simpleArrayType.getArraySizes().dereference();
2387
2388 // Will compute the higher-order strides here, rather than making a whole
2389 // pile of types and doing repetitive recursion on their contents.
2390 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2391 }
John Kessenichf8842e52016-01-04 19:22:56 -07002392
2393 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002394 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002395 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002396 if (stride > 0)
2397 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002398 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002399 }
2400 } else {
2401 // single-dimensional array, and don't yet have stride
2402
John Kessenichf8842e52016-01-04 19:22:56 -07002403 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002404 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2405 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002406 }
John Kessenich31ed4832015-09-09 17:51:38 -06002407
John Kessenichc9a80832015-09-12 12:17:44 -06002408 // Do the outer dimension, which might not be known for a runtime-sized array
2409 if (type.isRuntimeSizedArray()) {
2410 spvType = builder.makeRuntimeArray(spvType);
2411 } else {
2412 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002413 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002414 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002415 if (stride > 0)
2416 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002417 }
2418
2419 return spvType;
2420}
2421
John Kessenich0e737842017-03-24 18:38:16 -06002422// TODO: this functionality should exist at a higher level, in creating the AST
2423//
2424// Identify interface members that don't have their required extension turned on.
2425//
2426bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2427{
2428 auto& extensions = glslangIntermediate->getRequestedExtensions();
2429
Rex Xubcf291a2017-03-29 23:01:36 +08002430 if (member.getFieldName() == "gl_ViewportMask" &&
2431 extensions.find("GL_NV_viewport_array2") == extensions.end())
2432 return true;
2433 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2434 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2435 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002436 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2437 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2438 return true;
2439 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2440 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2441 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002442 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2443 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2444 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002445
2446 return false;
2447};
2448
John Kessenich6090df02016-06-30 21:18:02 -06002449// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2450// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2451// Mutually recursive with convertGlslangToSpvType().
2452spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2453 const glslang::TTypeList* glslangMembers,
2454 glslang::TLayoutPacking explicitLayout,
2455 const glslang::TQualifier& qualifier)
2456{
2457 // Create a vector of struct types for SPIR-V to consume
2458 std::vector<spv::Id> spvMembers;
2459 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 -06002460 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2461 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2462 if (glslangMember.hiddenMember()) {
2463 ++memberDelta;
2464 if (type.getBasicType() == glslang::EbtBlock)
2465 memberRemapper[glslangMembers][i] = -1;
2466 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002467 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002468 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002469 if (filterMember(glslangMember))
2470 continue;
2471 }
John Kessenich6090df02016-06-30 21:18:02 -06002472 // modify just this child's view of the qualifier
2473 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2474 InheritQualifiers(memberQualifier, qualifier);
2475
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002476 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002477 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002478 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002479
2480 // recurse
2481 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2482 }
2483 }
2484
2485 // Make the SPIR-V type
2486 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002487 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002488 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2489
2490 // Decorate it
2491 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2492
2493 return spvType;
2494}
2495
2496void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2497 const glslang::TTypeList* glslangMembers,
2498 glslang::TLayoutPacking explicitLayout,
2499 const glslang::TQualifier& qualifier,
2500 spv::Id spvType)
2501{
2502 // Name and decorate the non-hidden members
2503 int offset = -1;
2504 int locationOffset = 0; // for use within the members of this struct
2505 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2506 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2507 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002508 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002509 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002510 if (filterMember(glslangMember))
2511 continue;
2512 }
John Kessenich6090df02016-06-30 21:18:02 -06002513
2514 // modify just this child's view of the qualifier
2515 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2516 InheritQualifiers(memberQualifier, qualifier);
2517
2518 // using -1 above to indicate a hidden member
2519 if (member >= 0) {
2520 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2521 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2522 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2523 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002524 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2525 type.getQualifier().storage == glslang::EvqVaryingOut) {
2526 if (type.getBasicType() == glslang::EbtBlock ||
2527 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002528 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2529 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2530 }
2531 }
2532 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2533
2534 if (qualifier.storage == glslang::EvqBuffer) {
2535 std::vector<spv::Decoration> memory;
2536 TranslateMemoryDecoration(memberQualifier, memory);
2537 for (unsigned int i = 0; i < memory.size(); ++i)
2538 addMemberDecoration(spvType, member, memory[i]);
2539 }
2540
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002541 // Location assignment was already completed correctly by the front end,
2542 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002543 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002544 // ill-specified and decisions have been made to not allow this.
2545 if (! type.isArray() && memberQualifier.hasLocation())
2546 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002547
John Kessenich2f47bc92016-06-30 21:47:35 -06002548 if (qualifier.hasLocation()) // track for upcoming inheritance
2549 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2550
John Kessenich6090df02016-06-30 21:18:02 -06002551 // component, XFB, others
2552 if (glslangMember.getQualifier().hasComponent())
2553 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2554 if (glslangMember.getQualifier().hasXfbOffset())
2555 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2556 else if (explicitLayout != glslang::ElpNone) {
2557 // figure out what to do with offset, which is accumulating
2558 int nextOffset;
2559 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2560 if (offset >= 0)
2561 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2562 offset = nextOffset;
2563 }
2564
2565 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2566 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2567
2568 // built-in variable decorations
2569 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002570 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002571 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002572
2573#ifdef NV_EXTENSIONS
2574 if (builtIn == spv::BuiltInLayer) {
2575 // SPV_NV_viewport_array2 extension
2576 if (glslangMember.getQualifier().layoutViewportRelative){
2577 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2578 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2579 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2580 }
2581 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2582 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2583 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2584 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2585 }
2586 }
chaocdf3956c2017-02-14 14:52:34 -08002587 if (glslangMember.getQualifier().layoutPassthrough) {
2588 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2589 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2590 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2591 }
chaoc771d89f2017-01-13 01:10:53 -08002592#endif
John Kessenich6090df02016-06-30 21:18:02 -06002593 }
2594 }
2595
2596 // Decorate the structure
2597 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002598 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002599 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2600 builder.addCapability(spv::CapabilityGeometryStreams);
2601 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2602 }
2603 if (glslangIntermediate->getXfbMode()) {
2604 builder.addCapability(spv::CapabilityTransformFeedback);
2605 if (type.getQualifier().hasXfbStride())
2606 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2607 if (type.getQualifier().hasXfbBuffer())
2608 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2609 }
2610}
2611
John Kessenich6c292d32016-02-15 20:58:50 -07002612// Turn the expression forming the array size into an id.
2613// This is not quite trivial, because of specialization constants.
2614// Sometimes, a raw constant is turned into an Id, and sometimes
2615// a specialization constant expression is.
2616spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2617{
2618 // First, see if this is sized with a node, meaning a specialization constant:
2619 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2620 if (specNode != nullptr) {
2621 builder.clearAccessChain();
2622 specNode->traverse(this);
2623 return accessChainLoad(specNode->getAsTyped()->getType());
2624 }
qining25262b32016-05-06 17:25:16 -04002625
John Kessenich6c292d32016-02-15 20:58:50 -07002626 // Otherwise, need a compile-time (front end) size, get it:
2627 int size = arraySizes.getDimSize(dim);
2628 assert(size > 0);
2629 return builder.makeUintConstant(size);
2630}
2631
John Kessenich103bef92016-02-08 21:38:15 -07002632// Wrap the builder's accessChainLoad to:
2633// - localize handling of RelaxedPrecision
2634// - use the SPIR-V inferred type instead of another conversion of the glslang type
2635// (avoids unnecessary work and possible type punning for structures)
2636// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002637spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2638{
John Kessenich103bef92016-02-08 21:38:15 -07002639 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2640 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2641
2642 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002643 if (type.getBasicType() == glslang::EbtBool) {
2644 if (builder.isScalarType(nominalTypeId)) {
2645 // Conversion for bool
2646 spv::Id boolType = builder.makeBoolType();
2647 if (nominalTypeId != boolType)
2648 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2649 } else if (builder.isVectorType(nominalTypeId)) {
2650 // Conversion for bvec
2651 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2652 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2653 if (nominalTypeId != bvecType)
2654 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2655 }
2656 }
John Kessenich103bef92016-02-08 21:38:15 -07002657
2658 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002659}
2660
Rex Xu27253232016-02-23 17:51:09 +08002661// Wrap the builder's accessChainStore to:
2662// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002663//
2664// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002665void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2666{
2667 // Need to convert to abstract types when necessary
2668 if (type.getBasicType() == glslang::EbtBool) {
2669 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2670
2671 if (builder.isScalarType(nominalTypeId)) {
2672 // Conversion for bool
2673 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002674 if (nominalTypeId != boolType) {
2675 // keep these outside arguments, for determinant order-of-evaluation
2676 spv::Id one = builder.makeUintConstant(1);
2677 spv::Id zero = builder.makeUintConstant(0);
2678 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2679 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002680 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002681 } else if (builder.isVectorType(nominalTypeId)) {
2682 // Conversion for bvec
2683 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2684 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002685 if (nominalTypeId != bvecType) {
2686 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002687 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2688 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2689 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002690 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002691 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2692 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002693 }
2694 }
2695
2696 builder.accessChainStore(rvalue);
2697}
2698
John Kessenich4bf71552016-09-02 11:20:21 -06002699// For storing when types match at the glslang level, but not might match at the
2700// SPIR-V level.
2701//
2702// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002703// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002704// as in a member-decorated way.
2705//
2706// NOTE: This function can handle any store request; if it's not special it
2707// simplifies to a simple OpStore.
2708//
2709// Implicitly uses the existing builder.accessChain as the storage target.
2710void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2711{
John Kessenichb3e24e42016-09-11 12:33:43 -06002712 // we only do the complex path here if it's an aggregate
2713 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002714 accessChainStore(type, rValue);
2715 return;
2716 }
2717
John Kessenichb3e24e42016-09-11 12:33:43 -06002718 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002719 spv::Id rType = builder.getTypeId(rValue);
2720 spv::Id lValue = builder.accessChainGetLValue();
2721 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2722 if (lType == rType) {
2723 accessChainStore(type, rValue);
2724 return;
2725 }
2726
John Kessenichb3e24e42016-09-11 12:33:43 -06002727 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002728 // where the two types were the same type in GLSL. This requires member
2729 // by member copy, recursively.
2730
John Kessenichb3e24e42016-09-11 12:33:43 -06002731 // If an array, copy element by element.
2732 if (type.isArray()) {
2733 glslang::TType glslangElementType(type, 0);
2734 spv::Id elementRType = builder.getContainedTypeId(rType);
2735 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2736 // get the source member
2737 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002738
John Kessenichb3e24e42016-09-11 12:33:43 -06002739 // set up the target storage
2740 builder.clearAccessChain();
2741 builder.setAccessChainLValue(lValue);
2742 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002743
John Kessenichb3e24e42016-09-11 12:33:43 -06002744 // store the member
2745 multiTypeStore(glslangElementType, elementRValue);
2746 }
2747 } else {
2748 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002749
John Kessenichb3e24e42016-09-11 12:33:43 -06002750 // loop over structure members
2751 const glslang::TTypeList& members = *type.getStruct();
2752 for (int m = 0; m < (int)members.size(); ++m) {
2753 const glslang::TType& glslangMemberType = *members[m].type;
2754
2755 // get the source member
2756 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2757 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2758
2759 // set up the target storage
2760 builder.clearAccessChain();
2761 builder.setAccessChainLValue(lValue);
2762 builder.accessChainPush(builder.makeIntConstant(m));
2763
2764 // store the member
2765 multiTypeStore(glslangMemberType, memberRValue);
2766 }
John Kessenich4bf71552016-09-02 11:20:21 -06002767 }
2768}
2769
John Kessenichf85e8062015-12-19 13:57:10 -07002770// Decide whether or not this type should be
2771// decorated with offsets and strides, and if so
2772// whether std140 or std430 rules should be applied.
2773glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002774{
John Kessenichf85e8062015-12-19 13:57:10 -07002775 // has to be a block
2776 if (type.getBasicType() != glslang::EbtBlock)
2777 return glslang::ElpNone;
2778
2779 // has to be a uniform or buffer block
2780 if (type.getQualifier().storage != glslang::EvqUniform &&
2781 type.getQualifier().storage != glslang::EvqBuffer)
2782 return glslang::ElpNone;
2783
2784 // return the layout to use
2785 switch (type.getQualifier().layoutPacking) {
2786 case glslang::ElpStd140:
2787 case glslang::ElpStd430:
2788 return type.getQualifier().layoutPacking;
2789 default:
2790 return glslang::ElpNone;
2791 }
John Kessenich31ed4832015-09-09 17:51:38 -06002792}
2793
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002794// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002795int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002796{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002797 int size;
John Kessenich49987892015-12-29 17:11:44 -07002798 int stride;
2799 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002800
2801 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002802}
2803
John Kessenich49987892015-12-29 17:11:44 -07002804// 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 -07002805// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002806int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002807{
John Kessenich49987892015-12-29 17:11:44 -07002808 glslang::TType elementType;
2809 elementType.shallowCopy(matrixType);
2810 elementType.clearArraySizes();
2811
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002812 int size;
John Kessenich49987892015-12-29 17:11:44 -07002813 int stride;
2814 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2815
2816 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002817}
2818
John Kessenich5e4b1242015-08-06 22:53:06 -06002819// Given a member type of a struct, realign the current offset for it, and compute
2820// the next (not yet aligned) offset for the next member, which will get aligned
2821// on the next call.
2822// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2823// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2824// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002825void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002826 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002827{
2828 // this will get a positive value when deemed necessary
2829 nextOffset = -1;
2830
John Kessenich5e4b1242015-08-06 22:53:06 -06002831 // override anything in currentOffset with user-set offset
2832 if (memberType.getQualifier().hasOffset())
2833 currentOffset = memberType.getQualifier().layoutOffset;
2834
2835 // It could be that current linker usage in glslang updated all the layoutOffset,
2836 // in which case the following code does not matter. But, that's not quite right
2837 // once cross-compilation unit GLSL validation is done, as the original user
2838 // settings are needed in layoutOffset, and then the following will come into play.
2839
John Kessenichf85e8062015-12-19 13:57:10 -07002840 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002841 if (! memberType.getQualifier().hasOffset())
2842 currentOffset = -1;
2843
2844 return;
2845 }
2846
John Kessenichf85e8062015-12-19 13:57:10 -07002847 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002848 if (currentOffset < 0)
2849 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002850
John Kessenich5e4b1242015-08-06 22:53:06 -06002851 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2852 // but possibly not yet correctly aligned.
2853
2854 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002855 int dummyStride;
2856 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002857
2858 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002859 // TODO: make this consistent in early phases of code:
2860 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2861 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2862 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002863 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002864 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002865 int dummySize;
2866 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2867 if (componentAlignment <= 4)
2868 memberAlignment = componentAlignment;
2869 }
2870
2871 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002872 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002873
2874 // Bump up to vec4 if there is a bad straddle
2875 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2876 glslang::RoundToPow2(currentOffset, 16);
2877
John Kessenich5e4b1242015-08-06 22:53:06 -06002878 nextOffset = currentOffset + memberSize;
2879}
2880
David Netoa901ffe2016-06-08 14:11:40 +01002881void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002882{
David Netoa901ffe2016-06-08 14:11:40 +01002883 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2884 switch (glslangBuiltIn)
2885 {
2886 case glslang::EbvClipDistance:
2887 case glslang::EbvCullDistance:
2888 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002889#ifdef NV_EXTENSIONS
2890 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002891 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002892 case glslang::EbvViewportMaskNV:
2893 case glslang::EbvSecondaryPositionNV:
2894 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002895 case glslang::EbvPositionPerViewNV:
2896 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002897#endif
David Netoa901ffe2016-06-08 14:11:40 +01002898 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2899 // Alternately, we could just call this for any glslang built-in, since the
2900 // capability already guards against duplicates.
2901 TranslateBuiltInDecoration(glslangBuiltIn, false);
2902 break;
2903 default:
2904 // Capabilities were already generated when the struct was declared.
2905 break;
2906 }
John Kessenichebb50532016-05-16 19:22:05 -06002907}
2908
John Kessenich6fccb3c2016-09-19 16:01:41 -06002909bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002910{
John Kessenicheee9d532016-09-19 18:09:30 -06002911 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002912}
2913
2914// Make all the functions, skeletally, without actually visiting their bodies.
2915void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2916{
2917 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2918 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002919 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002920 continue;
2921
2922 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002923 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002924 //
qining25262b32016-05-06 17:25:16 -04002925 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002926 // function. What it is an address of varies:
2927 //
John Kessenich4bf71552016-09-02 11:20:21 -06002928 // - "in" parameters not marked as "const" can be written to without modifying the calling
2929 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002930 //
2931 // - "const in" parameters can just be the r-value, as no writes need occur.
2932 //
John Kessenich4bf71552016-09-02 11:20:21 -06002933 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2934 // 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 -06002935
2936 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002937 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002938 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2939
John Kessenich37789792017-03-21 23:56:40 -06002940 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2941
John Kessenich140f3df2015-06-26 16:58:36 -06002942 for (int p = 0; p < (int)parameters.size(); ++p) {
2943 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2944 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002945 // can we pass by reference?
2946 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002947 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002948 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002949 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002950 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002951 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002952 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2953 else
John Kessenich4bf71552016-09-02 11:20:21 -06002954 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002955 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002956 paramTypes.push_back(typeId);
2957 }
2958
2959 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002960 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2961 convertGlslangToSpvType(glslFunction->getType()),
2962 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002963 if (implicitThis)
2964 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002965
2966 // Track function to emit/call later
2967 functionMap[glslFunction->getName().c_str()] = function;
2968
2969 // Set the parameter id's
2970 for (int p = 0; p < (int)parameters.size(); ++p) {
2971 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2972 // give a name too
2973 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2974 }
2975 }
2976}
2977
2978// Process all the initializers, while skipping the functions and link objects
2979void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2980{
2981 builder.setBuildPoint(shaderEntry->getLastBlock());
2982 for (int i = 0; i < (int)initializers.size(); ++i) {
2983 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2984 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2985
2986 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002987 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002988 initializer->traverse(this);
2989 }
2990 }
2991}
2992
2993// Process all the functions, while skipping initializers.
2994void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2995{
2996 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2997 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002998 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002999 node->traverse(this);
3000 }
3001}
3002
3003void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3004{
qining25262b32016-05-06 17:25:16 -04003005 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003006 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003007 currentFunction = functionMap[node->getName().c_str()];
3008 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003009 builder.setBuildPoint(functionBlock);
3010}
3011
Rex Xu04db3f52015-09-16 11:44:02 +08003012void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003013{
Rex Xufc618912015-09-09 16:42:49 +08003014 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003015
3016 glslang::TSampler sampler = {};
3017 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003018 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003019 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3020 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3021 }
3022
John Kessenich140f3df2015-06-26 16:58:36 -06003023 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3024 builder.clearAccessChain();
3025 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003026
3027 // Special case l-value operands
3028 bool lvalue = false;
3029 switch (node.getOp()) {
3030 case glslang::EOpImageAtomicAdd:
3031 case glslang::EOpImageAtomicMin:
3032 case glslang::EOpImageAtomicMax:
3033 case glslang::EOpImageAtomicAnd:
3034 case glslang::EOpImageAtomicOr:
3035 case glslang::EOpImageAtomicXor:
3036 case glslang::EOpImageAtomicExchange:
3037 case glslang::EOpImageAtomicCompSwap:
3038 if (i == 0)
3039 lvalue = true;
3040 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003041 case glslang::EOpSparseImageLoad:
3042 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3043 lvalue = true;
3044 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003045 case glslang::EOpSparseTexture:
3046 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3047 lvalue = true;
3048 break;
3049 case glslang::EOpSparseTextureClamp:
3050 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3051 lvalue = true;
3052 break;
3053 case glslang::EOpSparseTextureLod:
3054 case glslang::EOpSparseTextureOffset:
3055 if (i == 3)
3056 lvalue = true;
3057 break;
3058 case glslang::EOpSparseTextureFetch:
3059 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3060 lvalue = true;
3061 break;
3062 case glslang::EOpSparseTextureFetchOffset:
3063 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3064 lvalue = true;
3065 break;
3066 case glslang::EOpSparseTextureLodOffset:
3067 case glslang::EOpSparseTextureGrad:
3068 case glslang::EOpSparseTextureOffsetClamp:
3069 if (i == 4)
3070 lvalue = true;
3071 break;
3072 case glslang::EOpSparseTextureGradOffset:
3073 case glslang::EOpSparseTextureGradClamp:
3074 if (i == 5)
3075 lvalue = true;
3076 break;
3077 case glslang::EOpSparseTextureGradOffsetClamp:
3078 if (i == 6)
3079 lvalue = true;
3080 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003081 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003082 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3083 lvalue = true;
3084 break;
3085 case glslang::EOpSparseTextureGatherOffset:
3086 case glslang::EOpSparseTextureGatherOffsets:
3087 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3088 lvalue = true;
3089 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003090#ifdef AMD_EXTENSIONS
3091 case glslang::EOpSparseTextureGatherLod:
3092 if (i == 3)
3093 lvalue = true;
3094 break;
3095 case glslang::EOpSparseTextureGatherLodOffset:
3096 case glslang::EOpSparseTextureGatherLodOffsets:
3097 if (i == 4)
3098 lvalue = true;
3099 break;
3100#endif
Rex Xufc618912015-09-09 16:42:49 +08003101 default:
3102 break;
3103 }
3104
Rex Xu6b86d492015-09-16 17:48:22 +08003105 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003106 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003107 else
John Kessenich32cfd492016-02-02 12:37:46 -07003108 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003109 }
3110}
3111
John Kessenichfc51d282015-08-19 13:34:18 -06003112void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003113{
John Kessenichfc51d282015-08-19 13:34:18 -06003114 builder.clearAccessChain();
3115 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003116 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003117}
John Kessenich140f3df2015-06-26 16:58:36 -06003118
John Kessenichfc51d282015-08-19 13:34:18 -06003119spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3120{
John Kesseniche485c7a2017-05-31 18:50:53 -06003121 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003122 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003123
3124 builder.setLine(node->getLoc().line);
3125
John Kessenich8c8505c2016-07-26 12:50:38 -06003126 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003127
John Kessenichfc51d282015-08-19 13:34:18 -06003128 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003129 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3130 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3131 std::vector<spv::Id> arguments;
3132 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003133 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003134 else
3135 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003136 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003137
3138 spv::Builder::TextureParameters params = { };
3139 params.sampler = arguments[0];
3140
Rex Xu04db3f52015-09-16 11:44:02 +08003141 glslang::TCrackedTextureOp cracked;
3142 node->crackTexture(sampler, cracked);
3143
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003144 const bool isUnsignedResult =
3145 node->getType().getBasicType() == glslang::EbtUint64 ||
3146 node->getType().getBasicType() == glslang::EbtUint;
3147
John Kessenichfc51d282015-08-19 13:34:18 -06003148 // Check for queries
3149 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003150 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3151 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003152 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003153
John Kessenichfc51d282015-08-19 13:34:18 -06003154 switch (node->getOp()) {
3155 case glslang::EOpImageQuerySize:
3156 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003157 if (arguments.size() > 1) {
3158 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003159 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003160 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003161 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003162 case glslang::EOpImageQuerySamples:
3163 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003164 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003165 case glslang::EOpTextureQueryLod:
3166 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003167 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003168 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003169 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003170 case glslang::EOpSparseTexelsResident:
3171 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003172 default:
3173 assert(0);
3174 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003175 }
John Kessenich140f3df2015-06-26 16:58:36 -06003176 }
3177
Rex Xufc618912015-09-09 16:42:49 +08003178 // Check for image functions other than queries
3179 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003180 std::vector<spv::Id> operands;
3181 auto opIt = arguments.begin();
3182 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003183
3184 // Handle subpass operations
3185 // TODO: GLSL should change to have the "MS" only on the type rather than the
3186 // built-in function.
3187 if (cracked.subpass) {
3188 // add on the (0,0) coordinate
3189 spv::Id zero = builder.makeIntConstant(0);
3190 std::vector<spv::Id> comps;
3191 comps.push_back(zero);
3192 comps.push_back(zero);
3193 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3194 if (sampler.ms) {
3195 operands.push_back(spv::ImageOperandsSampleMask);
3196 operands.push_back(*(opIt++));
3197 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003198 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003199 }
3200
John Kessenich56bab042015-09-16 10:54:31 -06003201 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003202 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003203 if (sampler.ms) {
3204 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003205 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003206 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003207 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3208 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003209 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003210 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003211 if (sampler.ms) {
3212 operands.push_back(*(opIt + 1));
3213 operands.push_back(spv::ImageOperandsSampleMask);
3214 operands.push_back(*opIt);
3215 } else
3216 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003217 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003218 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3219 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003220 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003221 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3222 builder.addCapability(spv::CapabilitySparseResidency);
3223 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3224 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3225
3226 if (sampler.ms) {
3227 operands.push_back(spv::ImageOperandsSampleMask);
3228 operands.push_back(*opIt++);
3229 }
3230
3231 // Create the return type that was a special structure
3232 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003233 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003234 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3235 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3236
3237 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3238
3239 // Decode the return type
3240 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3241 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003242 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003243 // Process image atomic operations
3244
3245 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3246 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003247 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003248
John Kessenich8c8505c2016-07-26 12:50:38 -06003249 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003250 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003251
3252 std::vector<spv::Id> operands;
3253 operands.push_back(pointer);
3254 for (; opIt != arguments.end(); ++opIt)
3255 operands.push_back(*opIt);
3256
John Kessenich8c8505c2016-07-26 12:50:38 -06003257 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003258 }
3259 }
3260
3261 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003262 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003263 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3264
John Kessenichfc51d282015-08-19 13:34:18 -06003265 // check for bias argument
3266 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003267#ifdef AMD_EXTENSIONS
3268 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3269#else
Rex Xu71519fe2015-11-11 15:35:47 +08003270 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003271#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003272 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003273#ifdef AMD_EXTENSIONS
3274 if (cracked.gather)
3275 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3276#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003277 if (cracked.offset)
3278 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003279#ifdef AMD_EXTENSIONS
3280 else if (cracked.offsets)
3281 ++nonBiasArgCount;
3282#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003283 if (cracked.grad)
3284 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003285 if (cracked.lodClamp)
3286 ++nonBiasArgCount;
3287 if (sparse)
3288 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003289
3290 if ((int)arguments.size() > nonBiasArgCount)
3291 bias = true;
3292 }
3293
John Kessenicha5c33d62016-06-02 23:45:21 -06003294 // See if the sampler param should really be just the SPV image part
3295 if (cracked.fetch) {
3296 // a fetch needs to have the image extracted first
3297 if (builder.isSampledImage(params.sampler))
3298 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3299 }
3300
Rex Xu225e0fc2016-11-17 17:47:59 +08003301#ifdef AMD_EXTENSIONS
3302 if (cracked.gather) {
3303 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3304 if (bias || cracked.lod ||
3305 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3306 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003307 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003308 }
3309 }
3310#endif
3311
John Kessenichfc51d282015-08-19 13:34:18 -06003312 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003313
John Kessenichfc51d282015-08-19 13:34:18 -06003314 params.coords = arguments[1];
3315 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003316 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003317
3318 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003319 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003320 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003321 ++extraArgs;
3322 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003323 params.Dref = arguments[2];
3324 ++extraArgs;
3325 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003326 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003327 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003328 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003329 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003330 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003331 dRefComp = builder.getNumComponents(params.coords) - 1;
3332 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003333 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3334 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003335
3336 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003337 if (cracked.lod) {
3338 params.lod = arguments[2];
3339 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003340 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3341 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3342 noImplicitLod = true;
3343 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003344
3345 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003346 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003347 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003348 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003349 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003350
3351 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003352 if (cracked.grad) {
3353 params.gradX = arguments[2 + extraArgs];
3354 params.gradY = arguments[3 + extraArgs];
3355 extraArgs += 2;
3356 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003357
3358 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003359 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003360 params.offset = arguments[2 + extraArgs];
3361 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003362 } else if (cracked.offsets) {
3363 params.offsets = arguments[2 + extraArgs];
3364 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003365 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003366
3367 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003368 if (cracked.lodClamp) {
3369 params.lodClamp = arguments[2 + extraArgs];
3370 ++extraArgs;
3371 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003372
3373 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003374 if (sparse) {
3375 params.texelOut = arguments[2 + extraArgs];
3376 ++extraArgs;
3377 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003378
John Kessenich76d4dfc2016-06-16 12:43:23 -06003379 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003380 if (cracked.gather && ! sampler.shadow) {
3381 // default component is 0, if missing, otherwise an argument
3382 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003383 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003384 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003385 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003386 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003387 }
3388
3389 // bias
3390 if (bias) {
3391 params.bias = arguments[2 + extraArgs];
3392 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003393 }
John Kessenichfc51d282015-08-19 13:34:18 -06003394
John Kessenich65336482016-06-16 14:06:26 -06003395 // projective component (might not to move)
3396 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3397 // are divided by the last component of P."
3398 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3399 // unused components will appear after all used components."
3400 if (cracked.proj) {
3401 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3402 int projTargetComp;
3403 switch (sampler.dim) {
3404 case glslang::Esd1D: projTargetComp = 1; break;
3405 case glslang::Esd2D: projTargetComp = 2; break;
3406 case glslang::EsdRect: projTargetComp = 2; break;
3407 default: projTargetComp = projSourceComp; break;
3408 }
3409 // copy the projective coordinate if we have to
3410 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003411 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003412 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3413 projSourceComp);
3414 params.coords = builder.createCompositeInsert(projComp, params.coords,
3415 builder.getTypeId(params.coords), projTargetComp);
3416 }
3417 }
3418
John Kessenich8c8505c2016-07-26 12:50:38 -06003419 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003420}
3421
3422spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3423{
3424 // Grab the function's pointer from the previously created function
3425 spv::Function* function = functionMap[node->getName().c_str()];
3426 if (! function)
3427 return 0;
3428
3429 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3430 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3431
3432 // See comments in makeFunctions() for details about the semantics for parameter passing.
3433 //
3434 // These imply we need a four step process:
3435 // 1. Evaluate the arguments
3436 // 2. Allocate and make copies of in, out, and inout arguments
3437 // 3. Make the call
3438 // 4. Copy back the results
3439
3440 // 1. Evaluate the arguments
3441 std::vector<spv::Builder::AccessChain> lValues;
3442 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003443 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003444 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003445 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003446 // build l-value
3447 builder.clearAccessChain();
3448 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003449 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003450 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003451 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003452 // save l-value
3453 lValues.push_back(builder.getAccessChain());
3454 } else {
3455 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003456 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003457 }
3458 }
3459
3460 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3461 // copy the original into that space.
3462 //
3463 // Also, build up the list of actual arguments to pass in for the call
3464 int lValueCount = 0;
3465 int rValueCount = 0;
3466 std::vector<spv::Id> spvArgs;
3467 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003468 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003469 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003470 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003471 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3472 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003473 builder.setAccessChain(lValues[lValueCount]);
3474 arg = builder.accessChainGetLValue();
3475 ++lValueCount;
3476 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003477 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003478 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3479 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3480 // need to copy the input into output space
3481 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003482 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003483 builder.clearAccessChain();
3484 builder.setAccessChainLValue(arg);
3485 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003486 }
3487 ++lValueCount;
3488 } else {
3489 arg = rValues[rValueCount];
3490 ++rValueCount;
3491 }
3492 spvArgs.push_back(arg);
3493 }
3494
3495 // 3. Make the call.
3496 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003497 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003498
3499 // 4. Copy back out an "out" arguments.
3500 lValueCount = 0;
3501 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003502 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003503 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3504 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3505 spv::Id copy = builder.createLoad(spvArgs[a]);
3506 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003507 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003508 }
3509 ++lValueCount;
3510 }
3511 }
3512
3513 return result;
3514}
3515
3516// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003517spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3518 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003519 spv::Id typeId, spv::Id left, spv::Id right,
3520 glslang::TBasicType typeProxy, bool reduceComparison)
3521{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003522#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003523 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003524 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3525#else
Rex Xucabbb782017-03-24 13:41:14 +08003526 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003527 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003528#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003529 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003530
3531 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003532 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003533 bool comparison = false;
3534
3535 switch (op) {
3536 case glslang::EOpAdd:
3537 case glslang::EOpAddAssign:
3538 if (isFloat)
3539 binOp = spv::OpFAdd;
3540 else
3541 binOp = spv::OpIAdd;
3542 break;
3543 case glslang::EOpSub:
3544 case glslang::EOpSubAssign:
3545 if (isFloat)
3546 binOp = spv::OpFSub;
3547 else
3548 binOp = spv::OpISub;
3549 break;
3550 case glslang::EOpMul:
3551 case glslang::EOpMulAssign:
3552 if (isFloat)
3553 binOp = spv::OpFMul;
3554 else
3555 binOp = spv::OpIMul;
3556 break;
3557 case glslang::EOpVectorTimesScalar:
3558 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003559 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003560 if (builder.isVector(right))
3561 std::swap(left, right);
3562 assert(builder.isScalar(right));
3563 needMatchingVectors = false;
3564 binOp = spv::OpVectorTimesScalar;
3565 } else
3566 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003567 break;
3568 case glslang::EOpVectorTimesMatrix:
3569 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003570 binOp = spv::OpVectorTimesMatrix;
3571 break;
3572 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003573 binOp = spv::OpMatrixTimesVector;
3574 break;
3575 case glslang::EOpMatrixTimesScalar:
3576 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003577 binOp = spv::OpMatrixTimesScalar;
3578 break;
3579 case glslang::EOpMatrixTimesMatrix:
3580 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003581 binOp = spv::OpMatrixTimesMatrix;
3582 break;
3583 case glslang::EOpOuterProduct:
3584 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003585 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003586 break;
3587
3588 case glslang::EOpDiv:
3589 case glslang::EOpDivAssign:
3590 if (isFloat)
3591 binOp = spv::OpFDiv;
3592 else if (isUnsigned)
3593 binOp = spv::OpUDiv;
3594 else
3595 binOp = spv::OpSDiv;
3596 break;
3597 case glslang::EOpMod:
3598 case glslang::EOpModAssign:
3599 if (isFloat)
3600 binOp = spv::OpFMod;
3601 else if (isUnsigned)
3602 binOp = spv::OpUMod;
3603 else
3604 binOp = spv::OpSMod;
3605 break;
3606 case glslang::EOpRightShift:
3607 case glslang::EOpRightShiftAssign:
3608 if (isUnsigned)
3609 binOp = spv::OpShiftRightLogical;
3610 else
3611 binOp = spv::OpShiftRightArithmetic;
3612 break;
3613 case glslang::EOpLeftShift:
3614 case glslang::EOpLeftShiftAssign:
3615 binOp = spv::OpShiftLeftLogical;
3616 break;
3617 case glslang::EOpAnd:
3618 case glslang::EOpAndAssign:
3619 binOp = spv::OpBitwiseAnd;
3620 break;
3621 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003622 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003623 binOp = spv::OpLogicalAnd;
3624 break;
3625 case glslang::EOpInclusiveOr:
3626 case glslang::EOpInclusiveOrAssign:
3627 binOp = spv::OpBitwiseOr;
3628 break;
3629 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003630 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003631 binOp = spv::OpLogicalOr;
3632 break;
3633 case glslang::EOpExclusiveOr:
3634 case glslang::EOpExclusiveOrAssign:
3635 binOp = spv::OpBitwiseXor;
3636 break;
3637 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003638 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003639 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003640 break;
3641
3642 case glslang::EOpLessThan:
3643 case glslang::EOpGreaterThan:
3644 case glslang::EOpLessThanEqual:
3645 case glslang::EOpGreaterThanEqual:
3646 case glslang::EOpEqual:
3647 case glslang::EOpNotEqual:
3648 case glslang::EOpVectorEqual:
3649 case glslang::EOpVectorNotEqual:
3650 comparison = true;
3651 break;
3652 default:
3653 break;
3654 }
3655
John Kessenich7c1aa102015-10-15 13:29:11 -06003656 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003657 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003658 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003659 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003660 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003661
3662 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003663 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003664 builder.promoteScalar(precision, left, right);
3665
qining25262b32016-05-06 17:25:16 -04003666 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3667 addDecoration(result, noContraction);
3668 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003669 }
3670
3671 if (! comparison)
3672 return 0;
3673
John Kessenich7c1aa102015-10-15 13:29:11 -06003674 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003675
John Kessenich4583b612016-08-07 19:14:22 -06003676 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3677 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003678 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003679
3680 switch (op) {
3681 case glslang::EOpLessThan:
3682 if (isFloat)
3683 binOp = spv::OpFOrdLessThan;
3684 else if (isUnsigned)
3685 binOp = spv::OpULessThan;
3686 else
3687 binOp = spv::OpSLessThan;
3688 break;
3689 case glslang::EOpGreaterThan:
3690 if (isFloat)
3691 binOp = spv::OpFOrdGreaterThan;
3692 else if (isUnsigned)
3693 binOp = spv::OpUGreaterThan;
3694 else
3695 binOp = spv::OpSGreaterThan;
3696 break;
3697 case glslang::EOpLessThanEqual:
3698 if (isFloat)
3699 binOp = spv::OpFOrdLessThanEqual;
3700 else if (isUnsigned)
3701 binOp = spv::OpULessThanEqual;
3702 else
3703 binOp = spv::OpSLessThanEqual;
3704 break;
3705 case glslang::EOpGreaterThanEqual:
3706 if (isFloat)
3707 binOp = spv::OpFOrdGreaterThanEqual;
3708 else if (isUnsigned)
3709 binOp = spv::OpUGreaterThanEqual;
3710 else
3711 binOp = spv::OpSGreaterThanEqual;
3712 break;
3713 case glslang::EOpEqual:
3714 case glslang::EOpVectorEqual:
3715 if (isFloat)
3716 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003717 else if (isBool)
3718 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003719 else
3720 binOp = spv::OpIEqual;
3721 break;
3722 case glslang::EOpNotEqual:
3723 case glslang::EOpVectorNotEqual:
3724 if (isFloat)
3725 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003726 else if (isBool)
3727 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003728 else
3729 binOp = spv::OpINotEqual;
3730 break;
3731 default:
3732 break;
3733 }
3734
qining25262b32016-05-06 17:25:16 -04003735 if (binOp != spv::OpNop) {
3736 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3737 addDecoration(result, noContraction);
3738 return builder.setPrecision(result, precision);
3739 }
John Kessenich140f3df2015-06-26 16:58:36 -06003740
3741 return 0;
3742}
3743
John Kessenich04bb8a02015-12-12 12:28:14 -07003744//
3745// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3746// These can be any of:
3747//
3748// matrix * scalar
3749// scalar * matrix
3750// matrix * matrix linear algebraic
3751// matrix * vector
3752// vector * matrix
3753// matrix * matrix componentwise
3754// matrix op matrix op in {+, -, /}
3755// matrix op scalar op in {+, -, /}
3756// scalar op matrix op in {+, -, /}
3757//
qining25262b32016-05-06 17:25:16 -04003758spv::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 -07003759{
3760 bool firstClass = true;
3761
3762 // First, handle first-class matrix operations (* and matrix/scalar)
3763 switch (op) {
3764 case spv::OpFDiv:
3765 if (builder.isMatrix(left) && builder.isScalar(right)) {
3766 // turn matrix / scalar into a multiply...
3767 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3768 op = spv::OpMatrixTimesScalar;
3769 } else
3770 firstClass = false;
3771 break;
3772 case spv::OpMatrixTimesScalar:
3773 if (builder.isMatrix(right))
3774 std::swap(left, right);
3775 assert(builder.isScalar(right));
3776 break;
3777 case spv::OpVectorTimesMatrix:
3778 assert(builder.isVector(left));
3779 assert(builder.isMatrix(right));
3780 break;
3781 case spv::OpMatrixTimesVector:
3782 assert(builder.isMatrix(left));
3783 assert(builder.isVector(right));
3784 break;
3785 case spv::OpMatrixTimesMatrix:
3786 assert(builder.isMatrix(left));
3787 assert(builder.isMatrix(right));
3788 break;
3789 default:
3790 firstClass = false;
3791 break;
3792 }
3793
qining25262b32016-05-06 17:25:16 -04003794 if (firstClass) {
3795 spv::Id result = builder.createBinOp(op, typeId, left, right);
3796 addDecoration(result, noContraction);
3797 return builder.setPrecision(result, precision);
3798 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003799
LoopDawg592860c2016-06-09 08:57:35 -06003800 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003801 // The result type of all of them is the same type as the (a) matrix operand.
3802 // The algorithm is to:
3803 // - break the matrix(es) into vectors
3804 // - smear any scalar to a vector
3805 // - do vector operations
3806 // - make a matrix out the vector results
3807 switch (op) {
3808 case spv::OpFAdd:
3809 case spv::OpFSub:
3810 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003811 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003812 case spv::OpFMul:
3813 {
3814 // one time set up...
3815 bool leftMat = builder.isMatrix(left);
3816 bool rightMat = builder.isMatrix(right);
3817 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3818 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3819 spv::Id scalarType = builder.getScalarTypeId(typeId);
3820 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3821 std::vector<spv::Id> results;
3822 spv::Id smearVec = spv::NoResult;
3823 if (builder.isScalar(left))
3824 smearVec = builder.smearScalar(precision, left, vecType);
3825 else if (builder.isScalar(right))
3826 smearVec = builder.smearScalar(precision, right, vecType);
3827
3828 // do each vector op
3829 for (unsigned int c = 0; c < numCols; ++c) {
3830 std::vector<unsigned int> indexes;
3831 indexes.push_back(c);
3832 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3833 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003834 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3835 addDecoration(result, noContraction);
3836 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003837 }
3838
3839 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003840 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003841 }
3842 default:
3843 assert(0);
3844 return spv::NoResult;
3845 }
3846}
3847
qining25262b32016-05-06 17:25:16 -04003848spv::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 -06003849{
3850 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003851 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003852 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003853#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003854 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003855 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3856#else
Rex Xucabbb782017-03-24 13:41:14 +08003857 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003858 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003859#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003860
3861 switch (op) {
3862 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003863 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003864 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003865 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003866 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003867 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003868 unaryOp = spv::OpSNegate;
3869 break;
3870
3871 case glslang::EOpLogicalNot:
3872 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003873 unaryOp = spv::OpLogicalNot;
3874 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003875 case glslang::EOpBitwiseNot:
3876 unaryOp = spv::OpNot;
3877 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003878
John Kessenich140f3df2015-06-26 16:58:36 -06003879 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003880 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003881 break;
3882 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003883 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003884 break;
3885 case glslang::EOpTranspose:
3886 unaryOp = spv::OpTranspose;
3887 break;
3888
3889 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003890 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003891 break;
3892 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003893 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003894 break;
3895 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003896 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003897 break;
3898 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003899 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003900 break;
3901 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003902 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003903 break;
3904 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003905 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003906 break;
3907 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003908 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003909 break;
3910 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003911 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003912 break;
3913
3914 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003915 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003916 break;
3917 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003918 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003919 break;
3920 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003921 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003922 break;
3923 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003924 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003925 break;
3926 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003927 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003928 break;
3929 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003930 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003931 break;
3932
3933 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003934 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003935 break;
3936 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003937 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003938 break;
3939
3940 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003941 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003942 break;
3943 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003944 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003945 break;
3946 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003947 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003948 break;
3949 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003950 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003951 break;
3952 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003953 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003954 break;
3955 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003956 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003957 break;
3958
3959 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003960 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003961 break;
3962 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003963 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003964 break;
3965 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003966 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003967 break;
3968 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003969 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003970 break;
3971 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003972 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003973 break;
3974 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003975 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003976 break;
3977
3978 case glslang::EOpIsNan:
3979 unaryOp = spv::OpIsNan;
3980 break;
3981 case glslang::EOpIsInf:
3982 unaryOp = spv::OpIsInf;
3983 break;
LoopDawg592860c2016-06-09 08:57:35 -06003984 case glslang::EOpIsFinite:
3985 unaryOp = spv::OpIsFinite;
3986 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003987
Rex Xucbc426e2015-12-15 16:03:10 +08003988 case glslang::EOpFloatBitsToInt:
3989 case glslang::EOpFloatBitsToUint:
3990 case glslang::EOpIntBitsToFloat:
3991 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003992 case glslang::EOpDoubleBitsToInt64:
3993 case glslang::EOpDoubleBitsToUint64:
3994 case glslang::EOpInt64BitsToDouble:
3995 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08003996#ifdef AMD_EXTENSIONS
3997 case glslang::EOpFloat16BitsToInt16:
3998 case glslang::EOpFloat16BitsToUint16:
3999 case glslang::EOpInt16BitsToFloat16:
4000 case glslang::EOpUint16BitsToFloat16:
4001#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004002 unaryOp = spv::OpBitcast;
4003 break;
4004
John Kessenich140f3df2015-06-26 16:58:36 -06004005 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004006 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004007 break;
4008 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004009 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004010 break;
4011 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004012 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004013 break;
4014 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004015 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004016 break;
4017 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004018 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004019 break;
4020 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004021 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004022 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004023 case glslang::EOpPackSnorm4x8:
4024 libCall = spv::GLSLstd450PackSnorm4x8;
4025 break;
4026 case glslang::EOpUnpackSnorm4x8:
4027 libCall = spv::GLSLstd450UnpackSnorm4x8;
4028 break;
4029 case glslang::EOpPackUnorm4x8:
4030 libCall = spv::GLSLstd450PackUnorm4x8;
4031 break;
4032 case glslang::EOpUnpackUnorm4x8:
4033 libCall = spv::GLSLstd450UnpackUnorm4x8;
4034 break;
4035 case glslang::EOpPackDouble2x32:
4036 libCall = spv::GLSLstd450PackDouble2x32;
4037 break;
4038 case glslang::EOpUnpackDouble2x32:
4039 libCall = spv::GLSLstd450UnpackDouble2x32;
4040 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004041
Rex Xu8ff43de2016-04-22 16:51:45 +08004042 case glslang::EOpPackInt2x32:
4043 case glslang::EOpUnpackInt2x32:
4044 case glslang::EOpPackUint2x32:
4045 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004046 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004047 break;
4048
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004049#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004050 case glslang::EOpPackInt2x16:
4051 case glslang::EOpUnpackInt2x16:
4052 case glslang::EOpPackUint2x16:
4053 case glslang::EOpUnpackUint2x16:
4054 case glslang::EOpPackInt4x16:
4055 case glslang::EOpUnpackInt4x16:
4056 case glslang::EOpPackUint4x16:
4057 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004058 case glslang::EOpPackFloat2x16:
4059 case glslang::EOpUnpackFloat2x16:
4060 unaryOp = spv::OpBitcast;
4061 break;
4062#endif
4063
John Kessenich140f3df2015-06-26 16:58:36 -06004064 case glslang::EOpDPdx:
4065 unaryOp = spv::OpDPdx;
4066 break;
4067 case glslang::EOpDPdy:
4068 unaryOp = spv::OpDPdy;
4069 break;
4070 case glslang::EOpFwidth:
4071 unaryOp = spv::OpFwidth;
4072 break;
4073 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004074 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004075 unaryOp = spv::OpDPdxFine;
4076 break;
4077 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004078 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004079 unaryOp = spv::OpDPdyFine;
4080 break;
4081 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004082 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004083 unaryOp = spv::OpFwidthFine;
4084 break;
4085 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004086 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004087 unaryOp = spv::OpDPdxCoarse;
4088 break;
4089 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004090 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004091 unaryOp = spv::OpDPdyCoarse;
4092 break;
4093 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004094 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004095 unaryOp = spv::OpFwidthCoarse;
4096 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004097 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004098 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004099 libCall = spv::GLSLstd450InterpolateAtCentroid;
4100 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004101 case glslang::EOpAny:
4102 unaryOp = spv::OpAny;
4103 break;
4104 case glslang::EOpAll:
4105 unaryOp = spv::OpAll;
4106 break;
4107
4108 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004109 if (isFloat)
4110 libCall = spv::GLSLstd450FAbs;
4111 else
4112 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004113 break;
4114 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004115 if (isFloat)
4116 libCall = spv::GLSLstd450FSign;
4117 else
4118 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004119 break;
4120
John Kessenichfc51d282015-08-19 13:34:18 -06004121 case glslang::EOpAtomicCounterIncrement:
4122 case glslang::EOpAtomicCounterDecrement:
4123 case glslang::EOpAtomicCounter:
4124 {
4125 // Handle all of the atomics in one place, in createAtomicOperation()
4126 std::vector<spv::Id> operands;
4127 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004128 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004129 }
4130
John Kessenichfc51d282015-08-19 13:34:18 -06004131 case glslang::EOpBitFieldReverse:
4132 unaryOp = spv::OpBitReverse;
4133 break;
4134 case glslang::EOpBitCount:
4135 unaryOp = spv::OpBitCount;
4136 break;
4137 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004138 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004139 break;
4140 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004141 if (isUnsigned)
4142 libCall = spv::GLSLstd450FindUMsb;
4143 else
4144 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004145 break;
4146
Rex Xu574ab042016-04-14 16:53:07 +08004147 case glslang::EOpBallot:
4148 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004149 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004150 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004151 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004152#ifdef AMD_EXTENSIONS
4153 case glslang::EOpMinInvocations:
4154 case glslang::EOpMaxInvocations:
4155 case glslang::EOpAddInvocations:
4156 case glslang::EOpMinInvocationsNonUniform:
4157 case glslang::EOpMaxInvocationsNonUniform:
4158 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004159 case glslang::EOpMinInvocationsInclusiveScan:
4160 case glslang::EOpMaxInvocationsInclusiveScan:
4161 case glslang::EOpAddInvocationsInclusiveScan:
4162 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4163 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4164 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4165 case glslang::EOpMinInvocationsExclusiveScan:
4166 case glslang::EOpMaxInvocationsExclusiveScan:
4167 case glslang::EOpAddInvocationsExclusiveScan:
4168 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4169 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4170 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004171#endif
Rex Xu51596642016-09-21 18:56:12 +08004172 {
4173 std::vector<spv::Id> operands;
4174 operands.push_back(operand);
4175 return createInvocationsOperation(op, typeId, operands, typeProxy);
4176 }
Rex Xu9d93a232016-05-05 12:30:44 +08004177
4178#ifdef AMD_EXTENSIONS
4179 case glslang::EOpMbcnt:
4180 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4181 libCall = spv::MbcntAMD;
4182 break;
4183
4184 case glslang::EOpCubeFaceIndex:
4185 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4186 libCall = spv::CubeFaceIndexAMD;
4187 break;
4188
4189 case glslang::EOpCubeFaceCoord:
4190 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4191 libCall = spv::CubeFaceCoordAMD;
4192 break;
4193#endif
Rex Xu338b1852016-05-05 20:38:33 +08004194
John Kessenich140f3df2015-06-26 16:58:36 -06004195 default:
4196 return 0;
4197 }
4198
4199 spv::Id id;
4200 if (libCall >= 0) {
4201 std::vector<spv::Id> args;
4202 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004203 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004204 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004205 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004206 }
John Kessenich140f3df2015-06-26 16:58:36 -06004207
qining25262b32016-05-06 17:25:16 -04004208 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004209 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004210}
4211
John Kessenich7a53f762016-01-20 11:19:27 -07004212// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004213spv::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 -07004214{
4215 // Handle unary operations vector by vector.
4216 // The result type is the same type as the original type.
4217 // The algorithm is to:
4218 // - break the matrix into vectors
4219 // - apply the operation to each vector
4220 // - make a matrix out the vector results
4221
4222 // get the types sorted out
4223 int numCols = builder.getNumColumns(operand);
4224 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004225 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4226 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004227 std::vector<spv::Id> results;
4228
4229 // do each vector op
4230 for (int c = 0; c < numCols; ++c) {
4231 std::vector<unsigned int> indexes;
4232 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004233 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4234 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4235 addDecoration(destVec, noContraction);
4236 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004237 }
4238
4239 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004240 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004241}
4242
Rex Xu73e3ce72016-04-27 18:48:17 +08004243spv::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 -06004244{
4245 spv::Op convOp = spv::OpNop;
4246 spv::Id zero = 0;
4247 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004248 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004249
4250 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4251
4252 switch (op) {
4253 case glslang::EOpConvIntToBool:
4254 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004255 case glslang::EOpConvInt64ToBool:
4256 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004257#ifdef AMD_EXTENSIONS
4258 case glslang::EOpConvInt16ToBool:
4259 case glslang::EOpConvUint16ToBool:
4260#endif
4261 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4262 zero = builder.makeUint64Constant(0);
4263#ifdef AMD_EXTENSIONS
4264 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4265 zero = builder.makeUint16Constant(0);
4266#endif
4267 else
4268 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004269 zero = makeSmearedConstant(zero, vectorSize);
4270 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4271
4272 case glslang::EOpConvFloatToBool:
4273 zero = builder.makeFloatConstant(0.0F);
4274 zero = makeSmearedConstant(zero, vectorSize);
4275 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4276
4277 case glslang::EOpConvDoubleToBool:
4278 zero = builder.makeDoubleConstant(0.0);
4279 zero = makeSmearedConstant(zero, vectorSize);
4280 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4281
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004282#ifdef AMD_EXTENSIONS
4283 case glslang::EOpConvFloat16ToBool:
4284 zero = builder.makeFloat16Constant(0.0F);
4285 zero = makeSmearedConstant(zero, vectorSize);
4286 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4287#endif
4288
John Kessenich140f3df2015-06-26 16:58:36 -06004289 case glslang::EOpConvBoolToFloat:
4290 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004291 zero = builder.makeFloatConstant(0.0F);
4292 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004293 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004294
John Kessenich140f3df2015-06-26 16:58:36 -06004295 case glslang::EOpConvBoolToDouble:
4296 convOp = spv::OpSelect;
4297 zero = builder.makeDoubleConstant(0.0);
4298 one = builder.makeDoubleConstant(1.0);
4299 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004300
4301#ifdef AMD_EXTENSIONS
4302 case glslang::EOpConvBoolToFloat16:
4303 convOp = spv::OpSelect;
4304 zero = builder.makeFloat16Constant(0.0F);
4305 one = builder.makeFloat16Constant(1.0F);
4306 break;
4307#endif
4308
John Kessenich140f3df2015-06-26 16:58:36 -06004309 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004310 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004311#ifdef AMD_EXTENSIONS
4312 case glslang::EOpConvBoolToInt16:
4313#endif
4314 if (op == glslang::EOpConvBoolToInt64)
4315 zero = builder.makeInt64Constant(0);
4316#ifdef AMD_EXTENSIONS
4317 else if (op == glslang::EOpConvBoolToInt16)
4318 zero = builder.makeInt16Constant(0);
4319#endif
4320 else
4321 zero = builder.makeIntConstant(0);
4322
4323 if (op == glslang::EOpConvBoolToInt64)
4324 one = builder.makeInt64Constant(1);
4325#ifdef AMD_EXTENSIONS
4326 else if (op == glslang::EOpConvBoolToInt16)
4327 one = builder.makeInt16Constant(1);
4328#endif
4329 else
4330 one = builder.makeIntConstant(1);
4331
John Kessenich140f3df2015-06-26 16:58:36 -06004332 convOp = spv::OpSelect;
4333 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004334
John Kessenich140f3df2015-06-26 16:58:36 -06004335 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004336 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004337#ifdef AMD_EXTENSIONS
4338 case glslang::EOpConvBoolToUint16:
4339#endif
4340 if (op == glslang::EOpConvBoolToUint64)
4341 zero = builder.makeUint64Constant(0);
4342#ifdef AMD_EXTENSIONS
4343 else if (op == glslang::EOpConvBoolToUint16)
4344 zero = builder.makeUint16Constant(0);
4345#endif
4346 else
4347 zero = builder.makeUintConstant(0);
4348
4349 if (op == glslang::EOpConvBoolToUint64)
4350 one = builder.makeUint64Constant(1);
4351#ifdef AMD_EXTENSIONS
4352 else if (op == glslang::EOpConvBoolToUint16)
4353 one = builder.makeUint16Constant(1);
4354#endif
4355 else
4356 one = builder.makeUintConstant(1);
4357
John Kessenich140f3df2015-06-26 16:58:36 -06004358 convOp = spv::OpSelect;
4359 break;
4360
4361 case glslang::EOpConvIntToFloat:
4362 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004363 case glslang::EOpConvInt64ToFloat:
4364 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004365#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004366 case glslang::EOpConvInt16ToFloat:
4367 case glslang::EOpConvInt16ToDouble:
4368 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004369 case glslang::EOpConvIntToFloat16:
4370 case glslang::EOpConvInt64ToFloat16:
4371#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004372 convOp = spv::OpConvertSToF;
4373 break;
4374
4375 case glslang::EOpConvUintToFloat:
4376 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004377 case glslang::EOpConvUint64ToFloat:
4378 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004379#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004380 case glslang::EOpConvUint16ToFloat:
4381 case glslang::EOpConvUint16ToDouble:
4382 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004383 case glslang::EOpConvUintToFloat16:
4384 case glslang::EOpConvUint64ToFloat16:
4385#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004386 convOp = spv::OpConvertUToF;
4387 break;
4388
4389 case glslang::EOpConvDoubleToFloat:
4390 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004391#ifdef AMD_EXTENSIONS
4392 case glslang::EOpConvDoubleToFloat16:
4393 case glslang::EOpConvFloat16ToDouble:
4394 case glslang::EOpConvFloatToFloat16:
4395 case glslang::EOpConvFloat16ToFloat:
4396#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004397 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004398 if (builder.isMatrixType(destType))
4399 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004400 break;
4401
4402 case glslang::EOpConvFloatToInt:
4403 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004404 case glslang::EOpConvFloatToInt64:
4405 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004406#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004407 case glslang::EOpConvFloatToInt16:
4408 case glslang::EOpConvDoubleToInt16:
4409 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004410 case glslang::EOpConvFloat16ToInt:
4411 case glslang::EOpConvFloat16ToInt64:
4412#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004413 convOp = spv::OpConvertFToS;
4414 break;
4415
4416 case glslang::EOpConvUintToInt:
4417 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004418 case glslang::EOpConvUint64ToInt64:
4419 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004420#ifdef AMD_EXTENSIONS
4421 case glslang::EOpConvUint16ToInt16:
4422 case glslang::EOpConvInt16ToUint16:
4423#endif
qininge24aa5e2016-04-07 15:40:27 -04004424 if (builder.isInSpecConstCodeGenMode()) {
4425 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004426 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4427 zero = builder.makeUint64Constant(0);
4428#ifdef AMD_EXTENSIONS
4429 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4430 zero = builder.makeUint16Constant(0);
4431#endif
4432 else
4433 zero = builder.makeUintConstant(0);
4434
qining189b2032016-04-12 23:16:20 -04004435 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004436 // Use OpIAdd, instead of OpBitcast to do the conversion when
4437 // generating for OpSpecConstantOp instruction.
4438 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4439 }
4440 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004441 convOp = spv::OpBitcast;
4442 break;
4443
4444 case glslang::EOpConvFloatToUint:
4445 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004446 case glslang::EOpConvFloatToUint64:
4447 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004448#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004449 case glslang::EOpConvFloatToUint16:
4450 case glslang::EOpConvDoubleToUint16:
4451 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004452 case glslang::EOpConvFloat16ToUint:
4453 case glslang::EOpConvFloat16ToUint64:
4454#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004455 convOp = spv::OpConvertFToU;
4456 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004457
4458 case glslang::EOpConvIntToInt64:
4459 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004460#ifdef AMD_EXTENSIONS
4461 case glslang::EOpConvIntToInt16:
4462 case glslang::EOpConvInt16ToInt:
4463 case glslang::EOpConvInt64ToInt16:
4464 case glslang::EOpConvInt16ToInt64:
4465#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004466 convOp = spv::OpSConvert;
4467 break;
4468
4469 case glslang::EOpConvUintToUint64:
4470 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004471#ifdef AMD_EXTENSIONS
4472 case glslang::EOpConvUintToUint16:
4473 case glslang::EOpConvUint16ToUint:
4474 case glslang::EOpConvUint64ToUint16:
4475 case glslang::EOpConvUint16ToUint64:
4476#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004477 convOp = spv::OpUConvert;
4478 break;
4479
4480 case glslang::EOpConvIntToUint64:
4481 case glslang::EOpConvInt64ToUint:
4482 case glslang::EOpConvUint64ToInt:
4483 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004484#ifdef AMD_EXTENSIONS
4485 case glslang::EOpConvInt16ToUint:
4486 case glslang::EOpConvUintToInt16:
4487 case glslang::EOpConvInt16ToUint64:
4488 case glslang::EOpConvUint64ToInt16:
4489 case glslang::EOpConvUint16ToInt:
4490 case glslang::EOpConvIntToUint16:
4491 case glslang::EOpConvUint16ToInt64:
4492 case glslang::EOpConvInt64ToUint16:
4493#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004494 // OpSConvert/OpUConvert + OpBitCast
4495 switch (op) {
4496 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004497#ifdef AMD_EXTENSIONS
4498 case glslang::EOpConvInt16ToUint64:
4499#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004500 convOp = spv::OpSConvert;
4501 type = builder.makeIntType(64);
4502 break;
4503 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004504#ifdef AMD_EXTENSIONS
4505 case glslang::EOpConvInt16ToUint:
4506#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004507 convOp = spv::OpSConvert;
4508 type = builder.makeIntType(32);
4509 break;
4510 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004511#ifdef AMD_EXTENSIONS
4512 case glslang::EOpConvUint16ToInt:
4513#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004514 convOp = spv::OpUConvert;
4515 type = builder.makeUintType(32);
4516 break;
4517 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004518#ifdef AMD_EXTENSIONS
4519 case glslang::EOpConvUint16ToInt64:
4520#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004521 convOp = spv::OpUConvert;
4522 type = builder.makeUintType(64);
4523 break;
Rex Xucabbb782017-03-24 13:41:14 +08004524#ifdef AMD_EXTENSIONS
4525 case glslang::EOpConvUintToInt16:
4526 case glslang::EOpConvUint64ToInt16:
4527 convOp = spv::OpUConvert;
4528 type = builder.makeUintType(16);
4529 break;
4530 case glslang::EOpConvIntToUint16:
4531 case glslang::EOpConvInt64ToUint16:
4532 convOp = spv::OpSConvert;
4533 type = builder.makeIntType(16);
4534 break;
4535#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004536 default:
4537 assert(0);
4538 break;
4539 }
4540
4541 if (vectorSize > 0)
4542 type = builder.makeVectorType(type, vectorSize);
4543
4544 operand = builder.createUnaryOp(convOp, type, operand);
4545
4546 if (builder.isInSpecConstCodeGenMode()) {
4547 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004548#ifdef AMD_EXTENSIONS
4549 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4550 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4551 zero = builder.makeUint64Constant(0);
4552 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4553 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4554 zero = builder.makeUint16Constant(0);
4555 else
4556 zero = builder.makeUintConstant(0);
4557#else
4558 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4559 zero = builder.makeUint64Constant(0);
4560 else
4561 zero = builder.makeUintConstant(0);
4562#endif
4563
Rex Xu8ff43de2016-04-22 16:51:45 +08004564 zero = makeSmearedConstant(zero, vectorSize);
4565 // Use OpIAdd, instead of OpBitcast to do the conversion when
4566 // generating for OpSpecConstantOp instruction.
4567 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4568 }
4569 // For normal run-time conversion instruction, use OpBitcast.
4570 convOp = spv::OpBitcast;
4571 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004572 default:
4573 break;
4574 }
4575
4576 spv::Id result = 0;
4577 if (convOp == spv::OpNop)
4578 return result;
4579
4580 if (convOp == spv::OpSelect) {
4581 zero = makeSmearedConstant(zero, vectorSize);
4582 one = makeSmearedConstant(one, vectorSize);
4583 result = builder.createTriOp(convOp, destType, operand, one, zero);
4584 } else
4585 result = builder.createUnaryOp(convOp, destType, operand);
4586
John Kessenich32cfd492016-02-02 12:37:46 -07004587 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004588}
4589
4590spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4591{
4592 if (vectorSize == 0)
4593 return constant;
4594
4595 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4596 std::vector<spv::Id> components;
4597 for (int c = 0; c < vectorSize; ++c)
4598 components.push_back(constant);
4599 return builder.makeCompositeConstant(vectorTypeId, components);
4600}
4601
John Kessenich426394d2015-07-23 10:22:48 -06004602// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004603spv::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 -06004604{
4605 spv::Op opCode = spv::OpNop;
4606
4607 switch (op) {
4608 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004609 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004610 opCode = spv::OpAtomicIAdd;
4611 break;
4612 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004613 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004614 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004615 break;
4616 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004617 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004618 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004619 break;
4620 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004621 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004622 opCode = spv::OpAtomicAnd;
4623 break;
4624 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004625 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004626 opCode = spv::OpAtomicOr;
4627 break;
4628 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004629 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004630 opCode = spv::OpAtomicXor;
4631 break;
4632 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004633 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004634 opCode = spv::OpAtomicExchange;
4635 break;
4636 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004637 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004638 opCode = spv::OpAtomicCompareExchange;
4639 break;
4640 case glslang::EOpAtomicCounterIncrement:
4641 opCode = spv::OpAtomicIIncrement;
4642 break;
4643 case glslang::EOpAtomicCounterDecrement:
4644 opCode = spv::OpAtomicIDecrement;
4645 break;
4646 case glslang::EOpAtomicCounter:
4647 opCode = spv::OpAtomicLoad;
4648 break;
4649 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004650 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004651 break;
4652 }
4653
4654 // Sort out the operands
4655 // - mapping from glslang -> SPV
4656 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004657 // - compare-exchange swaps the value and comparator
4658 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004659 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4660 auto opIt = operands.begin(); // walk the glslang operands
4661 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004662 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4663 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4664 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004665 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4666 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004667 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004668 spvAtomicOperands.push_back(*(opIt + 1));
4669 spvAtomicOperands.push_back(*opIt);
4670 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004671 }
John Kessenich426394d2015-07-23 10:22:48 -06004672
John Kessenich3e60a6f2015-09-14 22:45:16 -06004673 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004674 for (; opIt != operands.end(); ++opIt)
4675 spvAtomicOperands.push_back(*opIt);
4676
4677 return builder.createOp(opCode, typeId, spvAtomicOperands);
4678}
4679
John Kessenich91cef522016-05-05 16:45:40 -06004680// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004681spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004682{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004683#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004684 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004685 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004686#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004687
Rex Xu51596642016-09-21 18:56:12 +08004688 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004689 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004690 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4691
chaocf200da82016-12-20 12:44:35 -08004692 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4693 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004694 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4695 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004696 } else if (op == glslang::EOpAnyInvocation ||
4697 op == glslang::EOpAllInvocations ||
4698 op == glslang::EOpAllInvocationsEqual) {
4699 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4700 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004701 } else {
4702 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004703#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004704 if (op == glslang::EOpMinInvocationsNonUniform ||
4705 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004706 op == glslang::EOpAddInvocationsNonUniform ||
4707 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4708 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4709 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4710 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4711 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4712 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004713 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004714#endif
Rex Xu51596642016-09-21 18:56:12 +08004715
4716 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004717#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004718 switch (op) {
4719 case glslang::EOpMinInvocations:
4720 case glslang::EOpMaxInvocations:
4721 case glslang::EOpAddInvocations:
4722 case glslang::EOpMinInvocationsNonUniform:
4723 case glslang::EOpMaxInvocationsNonUniform:
4724 case glslang::EOpAddInvocationsNonUniform:
4725 groupOperation = spv::GroupOperationReduce;
4726 spvGroupOperands.push_back(groupOperation);
4727 break;
4728 case glslang::EOpMinInvocationsInclusiveScan:
4729 case glslang::EOpMaxInvocationsInclusiveScan:
4730 case glslang::EOpAddInvocationsInclusiveScan:
4731 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4732 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4733 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4734 groupOperation = spv::GroupOperationInclusiveScan;
4735 spvGroupOperands.push_back(groupOperation);
4736 break;
4737 case glslang::EOpMinInvocationsExclusiveScan:
4738 case glslang::EOpMaxInvocationsExclusiveScan:
4739 case glslang::EOpAddInvocationsExclusiveScan:
4740 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4741 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4742 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4743 groupOperation = spv::GroupOperationExclusiveScan;
4744 spvGroupOperands.push_back(groupOperation);
4745 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004746 default:
4747 break;
Rex Xu430ef402016-10-14 17:22:23 +08004748 }
Rex Xu9d93a232016-05-05 12:30:44 +08004749#endif
Rex Xu51596642016-09-21 18:56:12 +08004750 }
4751
4752 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4753 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004754
4755 switch (op) {
4756 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004757 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004758 break;
John Kessenich91cef522016-05-05 16:45:40 -06004759 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004760 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004761 break;
John Kessenich91cef522016-05-05 16:45:40 -06004762 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004763 opCode = spv::OpSubgroupAllEqualKHR;
4764 break;
Rex Xu51596642016-09-21 18:56:12 +08004765 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004766 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004767 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004768 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004769 break;
4770 case glslang::EOpReadFirstInvocation:
4771 opCode = spv::OpSubgroupFirstInvocationKHR;
4772 break;
4773 case glslang::EOpBallot:
4774 {
4775 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4776 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4777 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4778 //
4779 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4780 //
4781 spv::Id uintType = builder.makeUintType(32);
4782 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4783 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4784
4785 std::vector<spv::Id> components;
4786 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4787 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4788
4789 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4790 return builder.createUnaryOp(spv::OpBitcast, typeId,
4791 builder.createCompositeConstruct(uvec2Type, components));
4792 }
4793
Rex Xu9d93a232016-05-05 12:30:44 +08004794#ifdef AMD_EXTENSIONS
4795 case glslang::EOpMinInvocations:
4796 case glslang::EOpMaxInvocations:
4797 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004798 case glslang::EOpMinInvocationsInclusiveScan:
4799 case glslang::EOpMaxInvocationsInclusiveScan:
4800 case glslang::EOpAddInvocationsInclusiveScan:
4801 case glslang::EOpMinInvocationsExclusiveScan:
4802 case glslang::EOpMaxInvocationsExclusiveScan:
4803 case glslang::EOpAddInvocationsExclusiveScan:
4804 if (op == glslang::EOpMinInvocations ||
4805 op == glslang::EOpMinInvocationsInclusiveScan ||
4806 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004807 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004808 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004809 else {
4810 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004811 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004812 else
Rex Xu51596642016-09-21 18:56:12 +08004813 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004814 }
Rex Xu430ef402016-10-14 17:22:23 +08004815 } else if (op == glslang::EOpMaxInvocations ||
4816 op == glslang::EOpMaxInvocationsInclusiveScan ||
4817 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004818 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004819 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004820 else {
4821 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004822 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004823 else
Rex Xu51596642016-09-21 18:56:12 +08004824 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004825 }
4826 } else {
4827 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004828 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004829 else
Rex Xu51596642016-09-21 18:56:12 +08004830 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004831 }
4832
Rex Xu2bbbe062016-08-23 15:41:05 +08004833 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004834 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004835
4836 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004837 case glslang::EOpMinInvocationsNonUniform:
4838 case glslang::EOpMaxInvocationsNonUniform:
4839 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004840 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4841 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4842 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4843 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4844 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4845 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4846 if (op == glslang::EOpMinInvocationsNonUniform ||
4847 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4848 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004849 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004850 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004851 else {
4852 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004853 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004854 else
Rex Xu51596642016-09-21 18:56:12 +08004855 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004856 }
4857 }
Rex Xu430ef402016-10-14 17:22:23 +08004858 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4859 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4860 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004861 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004862 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004863 else {
4864 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004865 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004866 else
Rex Xu51596642016-09-21 18:56:12 +08004867 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004868 }
4869 }
4870 else {
4871 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004872 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004873 else
Rex Xu51596642016-09-21 18:56:12 +08004874 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004875 }
4876
Rex Xu2bbbe062016-08-23 15:41:05 +08004877 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004878 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004879
4880 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004881#endif
John Kessenich91cef522016-05-05 16:45:40 -06004882 default:
4883 logger->missingFunctionality("invocation operation");
4884 return spv::NoResult;
4885 }
Rex Xu51596642016-09-21 18:56:12 +08004886
4887 assert(opCode != spv::OpNop);
4888 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004889}
4890
Rex Xu2bbbe062016-08-23 15:41:05 +08004891// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004892spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004893{
Rex Xub7072052016-09-26 15:53:40 +08004894#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004895 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4896 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004897 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004898 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004899 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4900 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4901 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004902#else
4903 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4904 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004905 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4906 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004907#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004908
4909 // Handle group invocation operations scalar by scalar.
4910 // The result type is the same type as the original type.
4911 // The algorithm is to:
4912 // - break the vector into scalars
4913 // - apply the operation to each scalar
4914 // - make a vector out the scalar results
4915
4916 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004917 int numComponents = builder.getNumComponents(operands[0]);
4918 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004919 std::vector<spv::Id> results;
4920
4921 // do each scalar op
4922 for (int comp = 0; comp < numComponents; ++comp) {
4923 std::vector<unsigned int> indexes;
4924 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004925 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004926 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004927 if (op == spv::OpSubgroupReadInvocationKHR) {
4928 spvGroupOperands.push_back(scalar);
4929 spvGroupOperands.push_back(operands[1]);
4930 } else if (op == spv::OpGroupBroadcast) {
4931 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004932 spvGroupOperands.push_back(scalar);
4933 spvGroupOperands.push_back(operands[1]);
4934 } else {
chaocf200da82016-12-20 12:44:35 -08004935 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004936 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004937 spvGroupOperands.push_back(scalar);
4938 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004939
Rex Xub7072052016-09-26 15:53:40 +08004940 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004941 }
4942
4943 // put the pieces together
4944 return builder.createCompositeConstruct(typeId, results);
4945}
Rex Xu2bbbe062016-08-23 15:41:05 +08004946
John Kessenich5e4b1242015-08-06 22:53:06 -06004947spv::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 -06004948{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004949#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004950 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004951 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4952#else
Rex Xucabbb782017-03-24 13:41:14 +08004953 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004954 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004955#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004956
John Kessenich140f3df2015-06-26 16:58:36 -06004957 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004958 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004959 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004960 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004961 spv::Id typeId0 = 0;
4962 if (consumedOperands > 0)
4963 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004964 spv::Id typeId1 = 0;
4965 if (consumedOperands > 1)
4966 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004967 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004968
4969 switch (op) {
4970 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004971 if (isFloat)
4972 libCall = spv::GLSLstd450FMin;
4973 else if (isUnsigned)
4974 libCall = spv::GLSLstd450UMin;
4975 else
4976 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004977 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004978 break;
4979 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004980 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004981 break;
4982 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004983 if (isFloat)
4984 libCall = spv::GLSLstd450FMax;
4985 else if (isUnsigned)
4986 libCall = spv::GLSLstd450UMax;
4987 else
4988 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004989 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004990 break;
4991 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004992 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004993 break;
4994 case glslang::EOpDot:
4995 opCode = spv::OpDot;
4996 break;
4997 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004998 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004999 break;
5000
5001 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005002 if (isFloat)
5003 libCall = spv::GLSLstd450FClamp;
5004 else if (isUnsigned)
5005 libCall = spv::GLSLstd450UClamp;
5006 else
5007 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005008 builder.promoteScalar(precision, operands.front(), operands[1]);
5009 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005010 break;
5011 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005012 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5013 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005014 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005015 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005016 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005017 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005018 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005019 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005020 break;
5021 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005022 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005023 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005024 break;
5025 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005026 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005027 builder.promoteScalar(precision, operands[0], operands[2]);
5028 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005029 break;
5030
5031 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005032 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005033 break;
5034 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005035 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005036 break;
5037 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005038 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005039 break;
5040 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005041 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005042 break;
5043 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005044 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005045 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005046 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005047 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005048 libCall = spv::GLSLstd450InterpolateAtSample;
5049 break;
5050 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005051 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005052 libCall = spv::GLSLstd450InterpolateAtOffset;
5053 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005054 case glslang::EOpAddCarry:
5055 opCode = spv::OpIAddCarry;
5056 typeId = builder.makeStructResultType(typeId0, typeId0);
5057 consumedOperands = 2;
5058 break;
5059 case glslang::EOpSubBorrow:
5060 opCode = spv::OpISubBorrow;
5061 typeId = builder.makeStructResultType(typeId0, typeId0);
5062 consumedOperands = 2;
5063 break;
5064 case glslang::EOpUMulExtended:
5065 opCode = spv::OpUMulExtended;
5066 typeId = builder.makeStructResultType(typeId0, typeId0);
5067 consumedOperands = 2;
5068 break;
5069 case glslang::EOpIMulExtended:
5070 opCode = spv::OpSMulExtended;
5071 typeId = builder.makeStructResultType(typeId0, typeId0);
5072 consumedOperands = 2;
5073 break;
5074 case glslang::EOpBitfieldExtract:
5075 if (isUnsigned)
5076 opCode = spv::OpBitFieldUExtract;
5077 else
5078 opCode = spv::OpBitFieldSExtract;
5079 break;
5080 case glslang::EOpBitfieldInsert:
5081 opCode = spv::OpBitFieldInsert;
5082 break;
5083
5084 case glslang::EOpFma:
5085 libCall = spv::GLSLstd450Fma;
5086 break;
5087 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005088 {
5089 libCall = spv::GLSLstd450FrexpStruct;
5090 assert(builder.isPointerType(typeId1));
5091 typeId1 = builder.getContainedTypeId(typeId1);
5092#ifdef AMD_EXTENSIONS
5093 int width = builder.getScalarTypeWidth(typeId1);
5094#else
5095 int width = 32;
5096#endif
5097 if (builder.getNumComponents(operands[0]) == 1)
5098 frexpIntType = builder.makeIntegerType(width, true);
5099 else
5100 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5101 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5102 consumedOperands = 1;
5103 }
John Kessenich55e7d112015-11-15 21:33:39 -07005104 break;
5105 case glslang::EOpLdexp:
5106 libCall = spv::GLSLstd450Ldexp;
5107 break;
5108
Rex Xu574ab042016-04-14 16:53:07 +08005109 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005110 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005111
Rex Xu9d93a232016-05-05 12:30:44 +08005112#ifdef AMD_EXTENSIONS
5113 case glslang::EOpSwizzleInvocations:
5114 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5115 libCall = spv::SwizzleInvocationsAMD;
5116 break;
5117 case glslang::EOpSwizzleInvocationsMasked:
5118 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5119 libCall = spv::SwizzleInvocationsMaskedAMD;
5120 break;
5121 case glslang::EOpWriteInvocation:
5122 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5123 libCall = spv::WriteInvocationAMD;
5124 break;
5125
5126 case glslang::EOpMin3:
5127 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5128 if (isFloat)
5129 libCall = spv::FMin3AMD;
5130 else {
5131 if (isUnsigned)
5132 libCall = spv::UMin3AMD;
5133 else
5134 libCall = spv::SMin3AMD;
5135 }
5136 break;
5137 case glslang::EOpMax3:
5138 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5139 if (isFloat)
5140 libCall = spv::FMax3AMD;
5141 else {
5142 if (isUnsigned)
5143 libCall = spv::UMax3AMD;
5144 else
5145 libCall = spv::SMax3AMD;
5146 }
5147 break;
5148 case glslang::EOpMid3:
5149 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5150 if (isFloat)
5151 libCall = spv::FMid3AMD;
5152 else {
5153 if (isUnsigned)
5154 libCall = spv::UMid3AMD;
5155 else
5156 libCall = spv::SMid3AMD;
5157 }
5158 break;
5159
5160 case glslang::EOpInterpolateAtVertex:
5161 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5162 libCall = spv::InterpolateAtVertexAMD;
5163 break;
5164#endif
5165
John Kessenich140f3df2015-06-26 16:58:36 -06005166 default:
5167 return 0;
5168 }
5169
5170 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005171 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005172 // Use an extended instruction from the standard library.
5173 // Construct the call arguments, without modifying the original operands vector.
5174 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5175 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005176 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005177 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005178 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005179 case 0:
5180 // should all be handled by visitAggregate and createNoArgOperation
5181 assert(0);
5182 return 0;
5183 case 1:
5184 // should all be handled by createUnaryOperation
5185 assert(0);
5186 return 0;
5187 case 2:
5188 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5189 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005190 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005191 // anything 3 or over doesn't have l-value operands, so all should be consumed
5192 assert(consumedOperands == operands.size());
5193 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005194 break;
5195 }
5196 }
5197
John Kessenich55e7d112015-11-15 21:33:39 -07005198 // Decode the return types that were structures
5199 switch (op) {
5200 case glslang::EOpAddCarry:
5201 case glslang::EOpSubBorrow:
5202 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5203 id = builder.createCompositeExtract(id, typeId0, 0);
5204 break;
5205 case glslang::EOpUMulExtended:
5206 case glslang::EOpIMulExtended:
5207 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5208 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5209 break;
5210 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005211 {
5212 assert(operands.size() == 2);
5213 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5214 // "exp" is floating-point type (from HLSL intrinsic)
5215 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5216 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5217 builder.createStore(member1, operands[1]);
5218 } else
5219 // "exp" is integer type (from GLSL built-in function)
5220 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5221 id = builder.createCompositeExtract(id, typeId0, 0);
5222 }
John Kessenich55e7d112015-11-15 21:33:39 -07005223 break;
5224 default:
5225 break;
5226 }
5227
John Kessenich32cfd492016-02-02 12:37:46 -07005228 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005229}
5230
Rex Xu9d93a232016-05-05 12:30:44 +08005231// Intrinsics with no arguments (or no return value, and no precision).
5232spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005233{
5234 // TODO: get the barrier operands correct
5235
5236 switch (op) {
5237 case glslang::EOpEmitVertex:
5238 builder.createNoResultOp(spv::OpEmitVertex);
5239 return 0;
5240 case glslang::EOpEndPrimitive:
5241 builder.createNoResultOp(spv::OpEndPrimitive);
5242 return 0;
5243 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005244 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005245 return 0;
5246 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005247 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005248 return 0;
5249 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005250 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005251 return 0;
5252 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005253 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005254 return 0;
5255 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005256 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005257 return 0;
5258 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005259 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005260 return 0;
5261 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005262 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005263 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005264 case glslang::EOpAllMemoryBarrierWithGroupSync:
5265 // Control barrier with non-"None" semantic is also a memory barrier.
5266 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5267 return 0;
5268 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5269 // Control barrier with non-"None" semantic is also a memory barrier.
5270 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5271 return 0;
5272 case glslang::EOpWorkgroupMemoryBarrier:
5273 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5274 return 0;
5275 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5276 // Control barrier with non-"None" semantic is also a memory barrier.
5277 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5278 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005279#ifdef AMD_EXTENSIONS
5280 case glslang::EOpTime:
5281 {
5282 std::vector<spv::Id> args; // Dummy arguments
5283 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5284 return builder.setPrecision(id, precision);
5285 }
5286#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005287 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005288 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005289 return 0;
5290 }
5291}
5292
5293spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5294{
John Kessenich2f273362015-07-18 22:34:27 -06005295 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005296 spv::Id id;
5297 if (symbolValues.end() != iter) {
5298 id = iter->second;
5299 return id;
5300 }
5301
5302 // it was not found, create it
5303 id = createSpvVariable(symbol);
5304 symbolValues[symbol->getId()] = id;
5305
Rex Xuc884b4a2016-06-29 15:03:44 +08005306 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005307 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005308 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005309 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005310 if (symbol->getType().getQualifier().hasSpecConstantId())
5311 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005312 if (symbol->getQualifier().hasIndex())
5313 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5314 if (symbol->getQualifier().hasComponent())
5315 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5316 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005317 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005318 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005319 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005320 if (symbol->getQualifier().hasXfbBuffer())
5321 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5322 if (symbol->getQualifier().hasXfbOffset())
5323 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5324 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005325 // atomic counters use this:
5326 if (symbol->getQualifier().hasOffset())
5327 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005328 }
5329
scygan2c864272016-05-18 18:09:17 +02005330 if (symbol->getQualifier().hasLocation())
5331 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005332 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005333 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005334 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005335 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005336 }
John Kessenich140f3df2015-06-26 16:58:36 -06005337 if (symbol->getQualifier().hasSet())
5338 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005339 else if (IsDescriptorResource(symbol->getType())) {
5340 // default to 0
5341 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5342 }
John Kessenich140f3df2015-06-26 16:58:36 -06005343 if (symbol->getQualifier().hasBinding())
5344 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005345 if (symbol->getQualifier().hasAttachment())
5346 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005347 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005348 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005349 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005350 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005351 if (symbol->getQualifier().hasXfbBuffer())
5352 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5353 }
5354
Rex Xu1da878f2016-02-21 20:59:01 +08005355 if (symbol->getType().isImage()) {
5356 std::vector<spv::Decoration> memory;
5357 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5358 for (unsigned int i = 0; i < memory.size(); ++i)
5359 addDecoration(id, memory[i]);
5360 }
5361
John Kessenich140f3df2015-06-26 16:58:36 -06005362 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005363 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005364 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005365 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005366
John Kessenichecba76f2017-01-06 00:34:48 -07005367#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005368 if (builtIn == spv::BuiltInSampleMask) {
5369 spv::Decoration decoration;
5370 // GL_NV_sample_mask_override_coverage extension
5371 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005372 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005373 else
5374 decoration = (spv::Decoration)spv::DecorationMax;
5375 addDecoration(id, decoration);
5376 if (decoration != spv::DecorationMax) {
5377 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5378 }
5379 }
chaoc771d89f2017-01-13 01:10:53 -08005380 else if (builtIn == spv::BuiltInLayer) {
5381 // SPV_NV_viewport_array2 extension
5382 if (symbol->getQualifier().layoutViewportRelative)
5383 {
5384 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5385 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5386 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5387 }
5388 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5389 {
5390 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5391 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5392 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5393 }
5394 }
5395
chaoc6e5acae2016-12-20 13:28:52 -08005396 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005397 addDecoration(id, spv::DecorationPassthroughNV);
5398 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005399 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5400 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005401#endif
5402
John Kessenich140f3df2015-06-26 16:58:36 -06005403 return id;
5404}
5405
John Kessenich55e7d112015-11-15 21:33:39 -07005406// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005407void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5408{
John Kessenich4016e382016-07-15 11:53:56 -06005409 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005410 builder.addDecoration(id, dec);
5411}
5412
John Kessenich55e7d112015-11-15 21:33:39 -07005413// If 'dec' is valid, add a one-operand decoration to an object
5414void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5415{
John Kessenich4016e382016-07-15 11:53:56 -06005416 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005417 builder.addDecoration(id, dec, value);
5418}
5419
5420// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005421void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5422{
John Kessenich4016e382016-07-15 11:53:56 -06005423 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005424 builder.addMemberDecoration(id, (unsigned)member, dec);
5425}
5426
John Kessenich92187592016-02-01 13:45:25 -07005427// If 'dec' is valid, add a one-operand decoration to a struct member
5428void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5429{
John Kessenich4016e382016-07-15 11:53:56 -06005430 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005431 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5432}
5433
John Kessenich55e7d112015-11-15 21:33:39 -07005434// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005435// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005436//
5437// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5438//
5439// Recursively walk the nodes. The nodes form a tree whose leaves are
5440// regular constants, which themselves are trees that createSpvConstant()
5441// recursively walks. So, this function walks the "top" of the tree:
5442// - emit specialization constant-building instructions for specConstant
5443// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005444spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005445{
John Kessenich7cc0e282016-03-20 00:46:02 -06005446 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005447
qining4f4bb812016-04-03 23:55:17 -04005448 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005449 if (! node.getQualifier().specConstant) {
5450 // hand off to the non-spec-constant path
5451 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5452 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005453 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005454 nextConst, false);
5455 }
5456
5457 // We now know we have a specialization constant to build
5458
John Kessenichd94c0032016-05-30 19:29:40 -06005459 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005460 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5461 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5462 std::vector<spv::Id> dimConstId;
5463 for (int dim = 0; dim < 3; ++dim) {
5464 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5465 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5466 if (specConst)
5467 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5468 }
5469 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5470 }
5471
5472 // An AST node labelled as specialization constant should be a symbol node.
5473 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5474 if (auto* sn = node.getAsSymbolNode()) {
5475 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005476 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5477 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5478 // will set the builder into spec constant op instruction generating mode.
5479 sub_tree->traverse(this);
5480 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005481 } else if (auto* const_union_array = &sn->getConstArray()){
5482 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005483 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5484 builder.addName(id, sn->getName().c_str());
5485 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005486 }
5487 }
qining4f4bb812016-04-03 23:55:17 -04005488
5489 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5490 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005491 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005492 exit(1);
5493 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005494}
5495
John Kessenich140f3df2015-06-26 16:58:36 -06005496// Use 'consts' as the flattened glslang source of scalar constants to recursively
5497// build the aggregate SPIR-V constant.
5498//
5499// If there are not enough elements present in 'consts', 0 will be substituted;
5500// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5501//
qining08408382016-03-21 09:51:37 -04005502spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005503{
5504 // vector of constants for SPIR-V
5505 std::vector<spv::Id> spvConsts;
5506
5507 // Type is used for struct and array constants
5508 spv::Id typeId = convertGlslangToSpvType(glslangType);
5509
5510 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005511 glslang::TType elementType(glslangType, 0);
5512 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005513 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005514 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005515 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005516 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005517 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005518 } else if (glslangType.getStruct()) {
5519 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5520 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005521 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005522 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005523 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5524 bool zero = nextConst >= consts.size();
5525 switch (glslangType.getBasicType()) {
5526 case glslang::EbtInt:
5527 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5528 break;
5529 case glslang::EbtUint:
5530 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5531 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005532 case glslang::EbtInt64:
5533 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5534 break;
5535 case glslang::EbtUint64:
5536 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5537 break;
Rex Xucabbb782017-03-24 13:41:14 +08005538#ifdef AMD_EXTENSIONS
5539 case glslang::EbtInt16:
5540 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5541 break;
5542 case glslang::EbtUint16:
5543 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5544 break;
5545#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005546 case glslang::EbtFloat:
5547 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5548 break;
5549 case glslang::EbtDouble:
5550 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5551 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005552#ifdef AMD_EXTENSIONS
5553 case glslang::EbtFloat16:
5554 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5555 break;
5556#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005557 case glslang::EbtBool:
5558 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5559 break;
5560 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005561 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005562 break;
5563 }
5564 ++nextConst;
5565 }
5566 } else {
5567 // we have a non-aggregate (scalar) constant
5568 bool zero = nextConst >= consts.size();
5569 spv::Id scalar = 0;
5570 switch (glslangType.getBasicType()) {
5571 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005572 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005573 break;
5574 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005575 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005576 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005577 case glslang::EbtInt64:
5578 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5579 break;
5580 case glslang::EbtUint64:
5581 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5582 break;
Rex Xucabbb782017-03-24 13:41:14 +08005583#ifdef AMD_EXTENSIONS
5584 case glslang::EbtInt16:
5585 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5586 break;
5587 case glslang::EbtUint16:
5588 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5589 break;
5590#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005591 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005592 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005593 break;
5594 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005595 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005596 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005597#ifdef AMD_EXTENSIONS
5598 case glslang::EbtFloat16:
5599 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5600 break;
5601#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005602 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005603 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005604 break;
5605 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005606 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005607 break;
5608 }
5609 ++nextConst;
5610 return scalar;
5611 }
5612
5613 return builder.makeCompositeConstant(typeId, spvConsts);
5614}
5615
John Kessenich7c1aa102015-10-15 13:29:11 -06005616// Return true if the node is a constant or symbol whose reading has no
5617// non-trivial observable cost or effect.
5618bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5619{
5620 // don't know what this is
5621 if (node == nullptr)
5622 return false;
5623
5624 // a constant is safe
5625 if (node->getAsConstantUnion() != nullptr)
5626 return true;
5627
5628 // not a symbol means non-trivial
5629 if (node->getAsSymbolNode() == nullptr)
5630 return false;
5631
5632 // a symbol, depends on what's being read
5633 switch (node->getType().getQualifier().storage) {
5634 case glslang::EvqTemporary:
5635 case glslang::EvqGlobal:
5636 case glslang::EvqIn:
5637 case glslang::EvqInOut:
5638 case glslang::EvqConst:
5639 case glslang::EvqConstReadOnly:
5640 case glslang::EvqUniform:
5641 return true;
5642 default:
5643 return false;
5644 }
qining25262b32016-05-06 17:25:16 -04005645}
John Kessenich7c1aa102015-10-15 13:29:11 -06005646
5647// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005648// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005649// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005650// Return true if trivial.
5651bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5652{
5653 if (node == nullptr)
5654 return false;
5655
John Kessenich84cc15f2017-05-24 16:44:47 -06005656 // count non scalars as trivial, as well as anything coming from HLSL
5657 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005658 return true;
5659
John Kessenich7c1aa102015-10-15 13:29:11 -06005660 // symbols and constants are trivial
5661 if (isTrivialLeaf(node))
5662 return true;
5663
5664 // otherwise, it needs to be a simple operation or one or two leaf nodes
5665
5666 // not a simple operation
5667 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5668 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5669 if (binaryNode == nullptr && unaryNode == nullptr)
5670 return false;
5671
5672 // not on leaf nodes
5673 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5674 return false;
5675
5676 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5677 return false;
5678 }
5679
5680 switch (node->getAsOperator()->getOp()) {
5681 case glslang::EOpLogicalNot:
5682 case glslang::EOpConvIntToBool:
5683 case glslang::EOpConvUintToBool:
5684 case glslang::EOpConvFloatToBool:
5685 case glslang::EOpConvDoubleToBool:
5686 case glslang::EOpEqual:
5687 case glslang::EOpNotEqual:
5688 case glslang::EOpLessThan:
5689 case glslang::EOpGreaterThan:
5690 case glslang::EOpLessThanEqual:
5691 case glslang::EOpGreaterThanEqual:
5692 case glslang::EOpIndexDirect:
5693 case glslang::EOpIndexDirectStruct:
5694 case glslang::EOpLogicalXor:
5695 case glslang::EOpAny:
5696 case glslang::EOpAll:
5697 return true;
5698 default:
5699 return false;
5700 }
5701}
5702
5703// Emit short-circuiting code, where 'right' is never evaluated unless
5704// the left side is true (for &&) or false (for ||).
5705spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5706{
5707 spv::Id boolTypeId = builder.makeBoolType();
5708
5709 // emit left operand
5710 builder.clearAccessChain();
5711 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005712 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005713
5714 // Operands to accumulate OpPhi operands
5715 std::vector<spv::Id> phiOperands;
5716 // accumulate left operand's phi information
5717 phiOperands.push_back(leftId);
5718 phiOperands.push_back(builder.getBuildPoint()->getId());
5719
5720 // Make the two kinds of operation symmetric with a "!"
5721 // || => emit "if (! left) result = right"
5722 // && => emit "if ( left) result = right"
5723 //
5724 // TODO: this runtime "not" for || could be avoided by adding functionality
5725 // to 'builder' to have an "else" without an "then"
5726 if (op == glslang::EOpLogicalOr)
5727 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5728
5729 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005730 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005731
5732 // emit right operand as the "then" part of the "if"
5733 builder.clearAccessChain();
5734 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005735 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005736
5737 // accumulate left operand's phi information
5738 phiOperands.push_back(rightId);
5739 phiOperands.push_back(builder.getBuildPoint()->getId());
5740
5741 // finish the "if"
5742 ifBuilder.makeEndIf();
5743
5744 // phi together the two results
5745 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5746}
5747
Rex Xu9d93a232016-05-05 12:30:44 +08005748// Return type Id of the imported set of extended instructions corresponds to the name.
5749// Import this set if it has not been imported yet.
5750spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5751{
5752 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5753 return extBuiltinMap[name];
5754 else {
Rex Xu51596642016-09-21 18:56:12 +08005755 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005756 spv::Id extBuiltins = builder.import(name);
5757 extBuiltinMap[name] = extBuiltins;
5758 return extBuiltins;
5759 }
5760}
5761
John Kessenich140f3df2015-06-26 16:58:36 -06005762}; // end anonymous namespace
5763
5764namespace glslang {
5765
John Kessenich68d78fd2015-07-12 19:28:10 -06005766void GetSpirvVersion(std::string& version)
5767{
John Kessenich9e55f632015-07-15 10:03:39 -06005768 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005769 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005770 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005771 version = buf;
5772}
5773
John Kessenich140f3df2015-06-26 16:58:36 -06005774// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005775void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005776{
5777 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005778 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005779 if (out.fail())
5780 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005781 for (int i = 0; i < (int)spirv.size(); ++i) {
5782 unsigned int word = spirv[i];
5783 out.write((const char*)&word, 4);
5784 }
5785 out.close();
5786}
5787
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005788// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005789void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005790{
5791 std::ofstream out;
5792 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005793 if (out.fail())
5794 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005795 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005796 if (varName != nullptr) {
5797 out << "\t #pragma once" << std::endl;
5798 out << "const uint32_t " << varName << "[] = {" << std::endl;
5799 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005800 const int WORDS_PER_LINE = 8;
5801 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5802 out << "\t";
5803 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5804 const unsigned int word = spirv[i + j];
5805 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5806 if (i + j + 1 < (int)spirv.size()) {
5807 out << ",";
5808 }
5809 }
5810 out << std::endl;
5811 }
Flavio15017db2017-02-15 14:29:33 -08005812 if (varName != nullptr) {
5813 out << "};";
5814 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005815 out.close();
5816}
5817
John Kessenich140f3df2015-06-26 16:58:36 -06005818//
5819// Set up the glslang traversal
5820//
John Kessenich121853f2017-05-31 17:11:16 -06005821void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005822{
Lei Zhang17535f72016-05-04 15:55:59 -04005823 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005824 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005825}
5826
John Kessenich121853f2017-05-31 17:11:16 -06005827void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5828 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005829{
John Kessenich140f3df2015-06-26 16:58:36 -06005830 TIntermNode* root = intermediate.getTreeRoot();
5831
5832 if (root == 0)
5833 return;
5834
John Kessenich121853f2017-05-31 17:11:16 -06005835 glslang::SpvOptions defaultOptions;
5836 if (options == nullptr)
5837 options = &defaultOptions;
5838
John Kessenich140f3df2015-06-26 16:58:36 -06005839 glslang::GetThreadPoolAllocator().push();
5840
John Kessenich121853f2017-05-31 17:11:16 -06005841 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005842 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005843 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005844 it.dumpSpv(spirv);
5845
5846 glslang::GetThreadPoolAllocator().pop();
5847}
5848
5849}; // end namespace glslang