blob: 50d53d5f02ecfffdf067d613b500a02ba88987ca [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{
John Kessenichfad62972017-07-18 02:35:46 -06002917 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2918 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2919 if (paramPrecision != spv::NoPrecision)
2920 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002921 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002922 };
2923
John Kessenich140f3df2015-06-26 16:58:36 -06002924 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2925 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002926 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002927 continue;
2928
2929 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002930 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002931 //
qining25262b32016-05-06 17:25:16 -04002932 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002933 // function. What it is an address of varies:
2934 //
John Kessenich4bf71552016-09-02 11:20:21 -06002935 // - "in" parameters not marked as "const" can be written to without modifying the calling
2936 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002937 //
2938 // - "const in" parameters can just be the r-value, as no writes need occur.
2939 //
John Kessenich4bf71552016-09-02 11:20:21 -06002940 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2941 // 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 -06002942
2943 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002944 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002945 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2946
John Kessenichfad62972017-07-18 02:35:46 -06002947 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2948 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002949
John Kessenichfad62972017-07-18 02:35:46 -06002950 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06002951 for (int p = 0; p < (int)parameters.size(); ++p) {
2952 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2953 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002954 // can we pass by reference?
2955 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002956 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002957 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002958 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002959 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002960 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002961 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2962 else
John Kessenich4bf71552016-09-02 11:20:21 -06002963 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06002964 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06002965 paramTypes.push_back(typeId);
2966 }
2967
2968 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002969 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2970 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06002971 glslFunction->getName().c_str(), paramTypes,
2972 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002973 if (implicitThis)
2974 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002975
2976 // Track function to emit/call later
2977 functionMap[glslFunction->getName().c_str()] = function;
2978
2979 // Set the parameter id's
2980 for (int p = 0; p < (int)parameters.size(); ++p) {
2981 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2982 // give a name too
2983 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2984 }
2985 }
2986}
2987
2988// Process all the initializers, while skipping the functions and link objects
2989void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2990{
2991 builder.setBuildPoint(shaderEntry->getLastBlock());
2992 for (int i = 0; i < (int)initializers.size(); ++i) {
2993 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2994 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2995
2996 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002997 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002998 initializer->traverse(this);
2999 }
3000 }
3001}
3002
3003// Process all the functions, while skipping initializers.
3004void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3005{
3006 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3007 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003008 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003009 node->traverse(this);
3010 }
3011}
3012
3013void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3014{
qining25262b32016-05-06 17:25:16 -04003015 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003016 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003017 currentFunction = functionMap[node->getName().c_str()];
3018 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003019 builder.setBuildPoint(functionBlock);
3020}
3021
Rex Xu04db3f52015-09-16 11:44:02 +08003022void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003023{
Rex Xufc618912015-09-09 16:42:49 +08003024 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003025
3026 glslang::TSampler sampler = {};
3027 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003028 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003029 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3030 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3031 }
3032
John Kessenich140f3df2015-06-26 16:58:36 -06003033 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3034 builder.clearAccessChain();
3035 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003036
3037 // Special case l-value operands
3038 bool lvalue = false;
3039 switch (node.getOp()) {
3040 case glslang::EOpImageAtomicAdd:
3041 case glslang::EOpImageAtomicMin:
3042 case glslang::EOpImageAtomicMax:
3043 case glslang::EOpImageAtomicAnd:
3044 case glslang::EOpImageAtomicOr:
3045 case glslang::EOpImageAtomicXor:
3046 case glslang::EOpImageAtomicExchange:
3047 case glslang::EOpImageAtomicCompSwap:
3048 if (i == 0)
3049 lvalue = true;
3050 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003051 case glslang::EOpSparseImageLoad:
3052 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3053 lvalue = true;
3054 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003055 case glslang::EOpSparseTexture:
3056 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3057 lvalue = true;
3058 break;
3059 case glslang::EOpSparseTextureClamp:
3060 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3061 lvalue = true;
3062 break;
3063 case glslang::EOpSparseTextureLod:
3064 case glslang::EOpSparseTextureOffset:
3065 if (i == 3)
3066 lvalue = true;
3067 break;
3068 case glslang::EOpSparseTextureFetch:
3069 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3070 lvalue = true;
3071 break;
3072 case glslang::EOpSparseTextureFetchOffset:
3073 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3074 lvalue = true;
3075 break;
3076 case glslang::EOpSparseTextureLodOffset:
3077 case glslang::EOpSparseTextureGrad:
3078 case glslang::EOpSparseTextureOffsetClamp:
3079 if (i == 4)
3080 lvalue = true;
3081 break;
3082 case glslang::EOpSparseTextureGradOffset:
3083 case glslang::EOpSparseTextureGradClamp:
3084 if (i == 5)
3085 lvalue = true;
3086 break;
3087 case glslang::EOpSparseTextureGradOffsetClamp:
3088 if (i == 6)
3089 lvalue = true;
3090 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003091 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003092 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3093 lvalue = true;
3094 break;
3095 case glslang::EOpSparseTextureGatherOffset:
3096 case glslang::EOpSparseTextureGatherOffsets:
3097 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3098 lvalue = true;
3099 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003100#ifdef AMD_EXTENSIONS
3101 case glslang::EOpSparseTextureGatherLod:
3102 if (i == 3)
3103 lvalue = true;
3104 break;
3105 case glslang::EOpSparseTextureGatherLodOffset:
3106 case glslang::EOpSparseTextureGatherLodOffsets:
3107 if (i == 4)
3108 lvalue = true;
3109 break;
3110#endif
Rex Xufc618912015-09-09 16:42:49 +08003111 default:
3112 break;
3113 }
3114
Rex Xu6b86d492015-09-16 17:48:22 +08003115 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003116 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003117 else
John Kessenich32cfd492016-02-02 12:37:46 -07003118 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003119 }
3120}
3121
John Kessenichfc51d282015-08-19 13:34:18 -06003122void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003123{
John Kessenichfc51d282015-08-19 13:34:18 -06003124 builder.clearAccessChain();
3125 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003126 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003127}
John Kessenich140f3df2015-06-26 16:58:36 -06003128
John Kessenichfc51d282015-08-19 13:34:18 -06003129spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3130{
John Kesseniche485c7a2017-05-31 18:50:53 -06003131 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003132 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003133
3134 builder.setLine(node->getLoc().line);
3135
John Kessenich8c8505c2016-07-26 12:50:38 -06003136 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003137
John Kessenichfc51d282015-08-19 13:34:18 -06003138 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003139 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3140 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3141 std::vector<spv::Id> arguments;
3142 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003143 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003144 else
3145 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003146 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003147
3148 spv::Builder::TextureParameters params = { };
3149 params.sampler = arguments[0];
3150
Rex Xu04db3f52015-09-16 11:44:02 +08003151 glslang::TCrackedTextureOp cracked;
3152 node->crackTexture(sampler, cracked);
3153
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003154 const bool isUnsignedResult =
3155 node->getType().getBasicType() == glslang::EbtUint64 ||
3156 node->getType().getBasicType() == glslang::EbtUint;
3157
John Kessenichfc51d282015-08-19 13:34:18 -06003158 // Check for queries
3159 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003160 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3161 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003162 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003163
John Kessenichfc51d282015-08-19 13:34:18 -06003164 switch (node->getOp()) {
3165 case glslang::EOpImageQuerySize:
3166 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003167 if (arguments.size() > 1) {
3168 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003169 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003170 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003171 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003172 case glslang::EOpImageQuerySamples:
3173 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003174 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003175 case glslang::EOpTextureQueryLod:
3176 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003177 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003178 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003179 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003180 case glslang::EOpSparseTexelsResident:
3181 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003182 default:
3183 assert(0);
3184 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003185 }
John Kessenich140f3df2015-06-26 16:58:36 -06003186 }
3187
Rex Xufc618912015-09-09 16:42:49 +08003188 // Check for image functions other than queries
3189 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003190 std::vector<spv::Id> operands;
3191 auto opIt = arguments.begin();
3192 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003193
3194 // Handle subpass operations
3195 // TODO: GLSL should change to have the "MS" only on the type rather than the
3196 // built-in function.
3197 if (cracked.subpass) {
3198 // add on the (0,0) coordinate
3199 spv::Id zero = builder.makeIntConstant(0);
3200 std::vector<spv::Id> comps;
3201 comps.push_back(zero);
3202 comps.push_back(zero);
3203 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3204 if (sampler.ms) {
3205 operands.push_back(spv::ImageOperandsSampleMask);
3206 operands.push_back(*(opIt++));
3207 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003208 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003209 }
3210
John Kessenich56bab042015-09-16 10:54:31 -06003211 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003212 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003213 if (sampler.ms) {
3214 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003215 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003216 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003217 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3218 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003219 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003220 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003221 if (sampler.ms) {
3222 operands.push_back(*(opIt + 1));
3223 operands.push_back(spv::ImageOperandsSampleMask);
3224 operands.push_back(*opIt);
3225 } else
3226 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003227 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003228 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3229 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003230 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003231 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3232 builder.addCapability(spv::CapabilitySparseResidency);
3233 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3234 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3235
3236 if (sampler.ms) {
3237 operands.push_back(spv::ImageOperandsSampleMask);
3238 operands.push_back(*opIt++);
3239 }
3240
3241 // Create the return type that was a special structure
3242 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003243 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003244 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3245 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3246
3247 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3248
3249 // Decode the return type
3250 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3251 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003252 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003253 // Process image atomic operations
3254
3255 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3256 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003257 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003258
John Kessenich8c8505c2016-07-26 12:50:38 -06003259 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003260 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003261
3262 std::vector<spv::Id> operands;
3263 operands.push_back(pointer);
3264 for (; opIt != arguments.end(); ++opIt)
3265 operands.push_back(*opIt);
3266
John Kessenich8c8505c2016-07-26 12:50:38 -06003267 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003268 }
3269 }
3270
3271 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003272 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003273 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3274
John Kessenichfc51d282015-08-19 13:34:18 -06003275 // check for bias argument
3276 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003277#ifdef AMD_EXTENSIONS
3278 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3279#else
Rex Xu71519fe2015-11-11 15:35:47 +08003280 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003281#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003282 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003283#ifdef AMD_EXTENSIONS
3284 if (cracked.gather)
3285 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3286#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003287 if (cracked.offset)
3288 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003289#ifdef AMD_EXTENSIONS
3290 else if (cracked.offsets)
3291 ++nonBiasArgCount;
3292#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003293 if (cracked.grad)
3294 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003295 if (cracked.lodClamp)
3296 ++nonBiasArgCount;
3297 if (sparse)
3298 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003299
3300 if ((int)arguments.size() > nonBiasArgCount)
3301 bias = true;
3302 }
3303
John Kessenicha5c33d62016-06-02 23:45:21 -06003304 // See if the sampler param should really be just the SPV image part
3305 if (cracked.fetch) {
3306 // a fetch needs to have the image extracted first
3307 if (builder.isSampledImage(params.sampler))
3308 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3309 }
3310
Rex Xu225e0fc2016-11-17 17:47:59 +08003311#ifdef AMD_EXTENSIONS
3312 if (cracked.gather) {
3313 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3314 if (bias || cracked.lod ||
3315 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3316 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003317 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003318 }
3319 }
3320#endif
3321
John Kessenichfc51d282015-08-19 13:34:18 -06003322 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003323
John Kessenichfc51d282015-08-19 13:34:18 -06003324 params.coords = arguments[1];
3325 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003326 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003327
3328 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003329 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003330 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003331 ++extraArgs;
3332 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003333 params.Dref = arguments[2];
3334 ++extraArgs;
3335 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003336 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003337 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003338 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003339 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003340 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003341 dRefComp = builder.getNumComponents(params.coords) - 1;
3342 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003343 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3344 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003345
3346 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003347 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003348 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003349 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003350 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3351 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3352 noImplicitLod = true;
3353 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003354
3355 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003356 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003357 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003358 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003359 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003360
3361 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003362 if (cracked.grad) {
3363 params.gradX = arguments[2 + extraArgs];
3364 params.gradY = arguments[3 + extraArgs];
3365 extraArgs += 2;
3366 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003367
3368 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003369 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003370 params.offset = arguments[2 + extraArgs];
3371 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003372 } else if (cracked.offsets) {
3373 params.offsets = arguments[2 + extraArgs];
3374 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003375 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003376
3377 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003378 if (cracked.lodClamp) {
3379 params.lodClamp = arguments[2 + extraArgs];
3380 ++extraArgs;
3381 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003382
3383 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003384 if (sparse) {
3385 params.texelOut = arguments[2 + extraArgs];
3386 ++extraArgs;
3387 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003388
John Kessenich76d4dfc2016-06-16 12:43:23 -06003389 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003390 if (cracked.gather && ! sampler.shadow) {
3391 // default component is 0, if missing, otherwise an argument
3392 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003393 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003394 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003395 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003396 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003397 }
3398
3399 // bias
3400 if (bias) {
3401 params.bias = arguments[2 + extraArgs];
3402 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003403 }
John Kessenichfc51d282015-08-19 13:34:18 -06003404
John Kessenich65336482016-06-16 14:06:26 -06003405 // projective component (might not to move)
3406 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3407 // are divided by the last component of P."
3408 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3409 // unused components will appear after all used components."
3410 if (cracked.proj) {
3411 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3412 int projTargetComp;
3413 switch (sampler.dim) {
3414 case glslang::Esd1D: projTargetComp = 1; break;
3415 case glslang::Esd2D: projTargetComp = 2; break;
3416 case glslang::EsdRect: projTargetComp = 2; break;
3417 default: projTargetComp = projSourceComp; break;
3418 }
3419 // copy the projective coordinate if we have to
3420 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003421 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003422 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3423 projSourceComp);
3424 params.coords = builder.createCompositeInsert(projComp, params.coords,
3425 builder.getTypeId(params.coords), projTargetComp);
3426 }
3427 }
3428
John Kessenich8c8505c2016-07-26 12:50:38 -06003429 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003430}
3431
3432spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3433{
3434 // Grab the function's pointer from the previously created function
3435 spv::Function* function = functionMap[node->getName().c_str()];
3436 if (! function)
3437 return 0;
3438
3439 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3440 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3441
3442 // See comments in makeFunctions() for details about the semantics for parameter passing.
3443 //
3444 // These imply we need a four step process:
3445 // 1. Evaluate the arguments
3446 // 2. Allocate and make copies of in, out, and inout arguments
3447 // 3. Make the call
3448 // 4. Copy back the results
3449
3450 // 1. Evaluate the arguments
3451 std::vector<spv::Builder::AccessChain> lValues;
3452 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003453 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003454 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003455 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003456 // build l-value
3457 builder.clearAccessChain();
3458 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003459 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003460 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003461 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003462 // save l-value
3463 lValues.push_back(builder.getAccessChain());
3464 } else {
3465 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003466 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003467 }
3468 }
3469
3470 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3471 // copy the original into that space.
3472 //
3473 // Also, build up the list of actual arguments to pass in for the call
3474 int lValueCount = 0;
3475 int rValueCount = 0;
3476 std::vector<spv::Id> spvArgs;
3477 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003478 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003479 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003480 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003481 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3482 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003483 builder.setAccessChain(lValues[lValueCount]);
3484 arg = builder.accessChainGetLValue();
3485 ++lValueCount;
3486 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003487 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003488 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3489 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3490 // need to copy the input into output space
3491 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003492 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003493 builder.clearAccessChain();
3494 builder.setAccessChainLValue(arg);
3495 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003496 }
3497 ++lValueCount;
3498 } else {
3499 arg = rValues[rValueCount];
3500 ++rValueCount;
3501 }
3502 spvArgs.push_back(arg);
3503 }
3504
3505 // 3. Make the call.
3506 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003507 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003508
3509 // 4. Copy back out an "out" arguments.
3510 lValueCount = 0;
3511 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003512 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003513 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3514 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3515 spv::Id copy = builder.createLoad(spvArgs[a]);
3516 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003517 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003518 }
3519 ++lValueCount;
3520 }
3521 }
3522
3523 return result;
3524}
3525
3526// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003527spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3528 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003529 spv::Id typeId, spv::Id left, spv::Id right,
3530 glslang::TBasicType typeProxy, bool reduceComparison)
3531{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003532#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003533 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003534 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3535#else
Rex Xucabbb782017-03-24 13:41:14 +08003536 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003537 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003538#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003539 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003540
3541 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003542 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003543 bool comparison = false;
3544
3545 switch (op) {
3546 case glslang::EOpAdd:
3547 case glslang::EOpAddAssign:
3548 if (isFloat)
3549 binOp = spv::OpFAdd;
3550 else
3551 binOp = spv::OpIAdd;
3552 break;
3553 case glslang::EOpSub:
3554 case glslang::EOpSubAssign:
3555 if (isFloat)
3556 binOp = spv::OpFSub;
3557 else
3558 binOp = spv::OpISub;
3559 break;
3560 case glslang::EOpMul:
3561 case glslang::EOpMulAssign:
3562 if (isFloat)
3563 binOp = spv::OpFMul;
3564 else
3565 binOp = spv::OpIMul;
3566 break;
3567 case glslang::EOpVectorTimesScalar:
3568 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003569 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003570 if (builder.isVector(right))
3571 std::swap(left, right);
3572 assert(builder.isScalar(right));
3573 needMatchingVectors = false;
3574 binOp = spv::OpVectorTimesScalar;
3575 } else
3576 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003577 break;
3578 case glslang::EOpVectorTimesMatrix:
3579 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003580 binOp = spv::OpVectorTimesMatrix;
3581 break;
3582 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003583 binOp = spv::OpMatrixTimesVector;
3584 break;
3585 case glslang::EOpMatrixTimesScalar:
3586 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003587 binOp = spv::OpMatrixTimesScalar;
3588 break;
3589 case glslang::EOpMatrixTimesMatrix:
3590 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003591 binOp = spv::OpMatrixTimesMatrix;
3592 break;
3593 case glslang::EOpOuterProduct:
3594 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003595 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003596 break;
3597
3598 case glslang::EOpDiv:
3599 case glslang::EOpDivAssign:
3600 if (isFloat)
3601 binOp = spv::OpFDiv;
3602 else if (isUnsigned)
3603 binOp = spv::OpUDiv;
3604 else
3605 binOp = spv::OpSDiv;
3606 break;
3607 case glslang::EOpMod:
3608 case glslang::EOpModAssign:
3609 if (isFloat)
3610 binOp = spv::OpFMod;
3611 else if (isUnsigned)
3612 binOp = spv::OpUMod;
3613 else
3614 binOp = spv::OpSMod;
3615 break;
3616 case glslang::EOpRightShift:
3617 case glslang::EOpRightShiftAssign:
3618 if (isUnsigned)
3619 binOp = spv::OpShiftRightLogical;
3620 else
3621 binOp = spv::OpShiftRightArithmetic;
3622 break;
3623 case glslang::EOpLeftShift:
3624 case glslang::EOpLeftShiftAssign:
3625 binOp = spv::OpShiftLeftLogical;
3626 break;
3627 case glslang::EOpAnd:
3628 case glslang::EOpAndAssign:
3629 binOp = spv::OpBitwiseAnd;
3630 break;
3631 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003632 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003633 binOp = spv::OpLogicalAnd;
3634 break;
3635 case glslang::EOpInclusiveOr:
3636 case glslang::EOpInclusiveOrAssign:
3637 binOp = spv::OpBitwiseOr;
3638 break;
3639 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003640 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003641 binOp = spv::OpLogicalOr;
3642 break;
3643 case glslang::EOpExclusiveOr:
3644 case glslang::EOpExclusiveOrAssign:
3645 binOp = spv::OpBitwiseXor;
3646 break;
3647 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003648 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003649 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003650 break;
3651
3652 case glslang::EOpLessThan:
3653 case glslang::EOpGreaterThan:
3654 case glslang::EOpLessThanEqual:
3655 case glslang::EOpGreaterThanEqual:
3656 case glslang::EOpEqual:
3657 case glslang::EOpNotEqual:
3658 case glslang::EOpVectorEqual:
3659 case glslang::EOpVectorNotEqual:
3660 comparison = true;
3661 break;
3662 default:
3663 break;
3664 }
3665
John Kessenich7c1aa102015-10-15 13:29:11 -06003666 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003667 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003668 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003669 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003670 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003671
3672 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003673 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003674 builder.promoteScalar(precision, left, right);
3675
qining25262b32016-05-06 17:25:16 -04003676 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3677 addDecoration(result, noContraction);
3678 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003679 }
3680
3681 if (! comparison)
3682 return 0;
3683
John Kessenich7c1aa102015-10-15 13:29:11 -06003684 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003685
John Kessenich4583b612016-08-07 19:14:22 -06003686 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3687 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003688 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003689
3690 switch (op) {
3691 case glslang::EOpLessThan:
3692 if (isFloat)
3693 binOp = spv::OpFOrdLessThan;
3694 else if (isUnsigned)
3695 binOp = spv::OpULessThan;
3696 else
3697 binOp = spv::OpSLessThan;
3698 break;
3699 case glslang::EOpGreaterThan:
3700 if (isFloat)
3701 binOp = spv::OpFOrdGreaterThan;
3702 else if (isUnsigned)
3703 binOp = spv::OpUGreaterThan;
3704 else
3705 binOp = spv::OpSGreaterThan;
3706 break;
3707 case glslang::EOpLessThanEqual:
3708 if (isFloat)
3709 binOp = spv::OpFOrdLessThanEqual;
3710 else if (isUnsigned)
3711 binOp = spv::OpULessThanEqual;
3712 else
3713 binOp = spv::OpSLessThanEqual;
3714 break;
3715 case glslang::EOpGreaterThanEqual:
3716 if (isFloat)
3717 binOp = spv::OpFOrdGreaterThanEqual;
3718 else if (isUnsigned)
3719 binOp = spv::OpUGreaterThanEqual;
3720 else
3721 binOp = spv::OpSGreaterThanEqual;
3722 break;
3723 case glslang::EOpEqual:
3724 case glslang::EOpVectorEqual:
3725 if (isFloat)
3726 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003727 else if (isBool)
3728 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003729 else
3730 binOp = spv::OpIEqual;
3731 break;
3732 case glslang::EOpNotEqual:
3733 case glslang::EOpVectorNotEqual:
3734 if (isFloat)
3735 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003736 else if (isBool)
3737 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 else
3739 binOp = spv::OpINotEqual;
3740 break;
3741 default:
3742 break;
3743 }
3744
qining25262b32016-05-06 17:25:16 -04003745 if (binOp != spv::OpNop) {
3746 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3747 addDecoration(result, noContraction);
3748 return builder.setPrecision(result, precision);
3749 }
John Kessenich140f3df2015-06-26 16:58:36 -06003750
3751 return 0;
3752}
3753
John Kessenich04bb8a02015-12-12 12:28:14 -07003754//
3755// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3756// These can be any of:
3757//
3758// matrix * scalar
3759// scalar * matrix
3760// matrix * matrix linear algebraic
3761// matrix * vector
3762// vector * matrix
3763// matrix * matrix componentwise
3764// matrix op matrix op in {+, -, /}
3765// matrix op scalar op in {+, -, /}
3766// scalar op matrix op in {+, -, /}
3767//
qining25262b32016-05-06 17:25:16 -04003768spv::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 -07003769{
3770 bool firstClass = true;
3771
3772 // First, handle first-class matrix operations (* and matrix/scalar)
3773 switch (op) {
3774 case spv::OpFDiv:
3775 if (builder.isMatrix(left) && builder.isScalar(right)) {
3776 // turn matrix / scalar into a multiply...
3777 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3778 op = spv::OpMatrixTimesScalar;
3779 } else
3780 firstClass = false;
3781 break;
3782 case spv::OpMatrixTimesScalar:
3783 if (builder.isMatrix(right))
3784 std::swap(left, right);
3785 assert(builder.isScalar(right));
3786 break;
3787 case spv::OpVectorTimesMatrix:
3788 assert(builder.isVector(left));
3789 assert(builder.isMatrix(right));
3790 break;
3791 case spv::OpMatrixTimesVector:
3792 assert(builder.isMatrix(left));
3793 assert(builder.isVector(right));
3794 break;
3795 case spv::OpMatrixTimesMatrix:
3796 assert(builder.isMatrix(left));
3797 assert(builder.isMatrix(right));
3798 break;
3799 default:
3800 firstClass = false;
3801 break;
3802 }
3803
qining25262b32016-05-06 17:25:16 -04003804 if (firstClass) {
3805 spv::Id result = builder.createBinOp(op, typeId, left, right);
3806 addDecoration(result, noContraction);
3807 return builder.setPrecision(result, precision);
3808 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003809
LoopDawg592860c2016-06-09 08:57:35 -06003810 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003811 // The result type of all of them is the same type as the (a) matrix operand.
3812 // The algorithm is to:
3813 // - break the matrix(es) into vectors
3814 // - smear any scalar to a vector
3815 // - do vector operations
3816 // - make a matrix out the vector results
3817 switch (op) {
3818 case spv::OpFAdd:
3819 case spv::OpFSub:
3820 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003821 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003822 case spv::OpFMul:
3823 {
3824 // one time set up...
3825 bool leftMat = builder.isMatrix(left);
3826 bool rightMat = builder.isMatrix(right);
3827 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3828 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3829 spv::Id scalarType = builder.getScalarTypeId(typeId);
3830 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3831 std::vector<spv::Id> results;
3832 spv::Id smearVec = spv::NoResult;
3833 if (builder.isScalar(left))
3834 smearVec = builder.smearScalar(precision, left, vecType);
3835 else if (builder.isScalar(right))
3836 smearVec = builder.smearScalar(precision, right, vecType);
3837
3838 // do each vector op
3839 for (unsigned int c = 0; c < numCols; ++c) {
3840 std::vector<unsigned int> indexes;
3841 indexes.push_back(c);
3842 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3843 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003844 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3845 addDecoration(result, noContraction);
3846 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003847 }
3848
3849 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003850 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003851 }
3852 default:
3853 assert(0);
3854 return spv::NoResult;
3855 }
3856}
3857
qining25262b32016-05-06 17:25:16 -04003858spv::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 -06003859{
3860 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003861 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003862 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003863#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003864 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003865 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3866#else
Rex Xucabbb782017-03-24 13:41:14 +08003867 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003868 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003869#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003870
3871 switch (op) {
3872 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003873 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003874 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003875 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003876 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003877 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003878 unaryOp = spv::OpSNegate;
3879 break;
3880
3881 case glslang::EOpLogicalNot:
3882 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003883 unaryOp = spv::OpLogicalNot;
3884 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003885 case glslang::EOpBitwiseNot:
3886 unaryOp = spv::OpNot;
3887 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003888
John Kessenich140f3df2015-06-26 16:58:36 -06003889 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003890 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003891 break;
3892 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003893 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003894 break;
3895 case glslang::EOpTranspose:
3896 unaryOp = spv::OpTranspose;
3897 break;
3898
3899 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003900 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003901 break;
3902 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003903 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003904 break;
3905 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003906 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003907 break;
3908 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003909 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003910 break;
3911 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003912 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003913 break;
3914 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003915 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003916 break;
3917 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003918 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003919 break;
3920 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003921 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003922 break;
3923
3924 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003925 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003926 break;
3927 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003928 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003929 break;
3930 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003931 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003932 break;
3933 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003934 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003935 break;
3936 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003937 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003938 break;
3939 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003940 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003941 break;
3942
3943 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003944 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003945 break;
3946 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003947 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003948 break;
3949
3950 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003951 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003952 break;
3953 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003954 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003955 break;
3956 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003957 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003958 break;
3959 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003960 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003961 break;
3962 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003963 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003964 break;
3965 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003966 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003967 break;
3968
3969 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003970 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003971 break;
3972 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003973 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003974 break;
3975 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003976 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003977 break;
3978 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003979 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003980 break;
3981 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003982 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003983 break;
3984 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003985 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003986 break;
3987
3988 case glslang::EOpIsNan:
3989 unaryOp = spv::OpIsNan;
3990 break;
3991 case glslang::EOpIsInf:
3992 unaryOp = spv::OpIsInf;
3993 break;
LoopDawg592860c2016-06-09 08:57:35 -06003994 case glslang::EOpIsFinite:
3995 unaryOp = spv::OpIsFinite;
3996 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003997
Rex Xucbc426e2015-12-15 16:03:10 +08003998 case glslang::EOpFloatBitsToInt:
3999 case glslang::EOpFloatBitsToUint:
4000 case glslang::EOpIntBitsToFloat:
4001 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004002 case glslang::EOpDoubleBitsToInt64:
4003 case glslang::EOpDoubleBitsToUint64:
4004 case glslang::EOpInt64BitsToDouble:
4005 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004006#ifdef AMD_EXTENSIONS
4007 case glslang::EOpFloat16BitsToInt16:
4008 case glslang::EOpFloat16BitsToUint16:
4009 case glslang::EOpInt16BitsToFloat16:
4010 case glslang::EOpUint16BitsToFloat16:
4011#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004012 unaryOp = spv::OpBitcast;
4013 break;
4014
John Kessenich140f3df2015-06-26 16:58:36 -06004015 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004016 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004017 break;
4018 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004019 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004020 break;
4021 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004022 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004023 break;
4024 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004025 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004026 break;
4027 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004028 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004029 break;
4030 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004031 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004032 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004033 case glslang::EOpPackSnorm4x8:
4034 libCall = spv::GLSLstd450PackSnorm4x8;
4035 break;
4036 case glslang::EOpUnpackSnorm4x8:
4037 libCall = spv::GLSLstd450UnpackSnorm4x8;
4038 break;
4039 case glslang::EOpPackUnorm4x8:
4040 libCall = spv::GLSLstd450PackUnorm4x8;
4041 break;
4042 case glslang::EOpUnpackUnorm4x8:
4043 libCall = spv::GLSLstd450UnpackUnorm4x8;
4044 break;
4045 case glslang::EOpPackDouble2x32:
4046 libCall = spv::GLSLstd450PackDouble2x32;
4047 break;
4048 case glslang::EOpUnpackDouble2x32:
4049 libCall = spv::GLSLstd450UnpackDouble2x32;
4050 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004051
Rex Xu8ff43de2016-04-22 16:51:45 +08004052 case glslang::EOpPackInt2x32:
4053 case glslang::EOpUnpackInt2x32:
4054 case glslang::EOpPackUint2x32:
4055 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004056 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004057 break;
4058
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004059#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004060 case glslang::EOpPackInt2x16:
4061 case glslang::EOpUnpackInt2x16:
4062 case glslang::EOpPackUint2x16:
4063 case glslang::EOpUnpackUint2x16:
4064 case glslang::EOpPackInt4x16:
4065 case glslang::EOpUnpackInt4x16:
4066 case glslang::EOpPackUint4x16:
4067 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004068 case glslang::EOpPackFloat2x16:
4069 case glslang::EOpUnpackFloat2x16:
4070 unaryOp = spv::OpBitcast;
4071 break;
4072#endif
4073
John Kessenich140f3df2015-06-26 16:58:36 -06004074 case glslang::EOpDPdx:
4075 unaryOp = spv::OpDPdx;
4076 break;
4077 case glslang::EOpDPdy:
4078 unaryOp = spv::OpDPdy;
4079 break;
4080 case glslang::EOpFwidth:
4081 unaryOp = spv::OpFwidth;
4082 break;
4083 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004084 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004085 unaryOp = spv::OpDPdxFine;
4086 break;
4087 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004088 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004089 unaryOp = spv::OpDPdyFine;
4090 break;
4091 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004092 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004093 unaryOp = spv::OpFwidthFine;
4094 break;
4095 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004096 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004097 unaryOp = spv::OpDPdxCoarse;
4098 break;
4099 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004100 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004101 unaryOp = spv::OpDPdyCoarse;
4102 break;
4103 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004104 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004105 unaryOp = spv::OpFwidthCoarse;
4106 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004107 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004108 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004109 libCall = spv::GLSLstd450InterpolateAtCentroid;
4110 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004111 case glslang::EOpAny:
4112 unaryOp = spv::OpAny;
4113 break;
4114 case glslang::EOpAll:
4115 unaryOp = spv::OpAll;
4116 break;
4117
4118 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004119 if (isFloat)
4120 libCall = spv::GLSLstd450FAbs;
4121 else
4122 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004123 break;
4124 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004125 if (isFloat)
4126 libCall = spv::GLSLstd450FSign;
4127 else
4128 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004129 break;
4130
John Kessenichfc51d282015-08-19 13:34:18 -06004131 case glslang::EOpAtomicCounterIncrement:
4132 case glslang::EOpAtomicCounterDecrement:
4133 case glslang::EOpAtomicCounter:
4134 {
4135 // Handle all of the atomics in one place, in createAtomicOperation()
4136 std::vector<spv::Id> operands;
4137 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004138 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004139 }
4140
John Kessenichfc51d282015-08-19 13:34:18 -06004141 case glslang::EOpBitFieldReverse:
4142 unaryOp = spv::OpBitReverse;
4143 break;
4144 case glslang::EOpBitCount:
4145 unaryOp = spv::OpBitCount;
4146 break;
4147 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004148 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004149 break;
4150 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004151 if (isUnsigned)
4152 libCall = spv::GLSLstd450FindUMsb;
4153 else
4154 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004155 break;
4156
Rex Xu574ab042016-04-14 16:53:07 +08004157 case glslang::EOpBallot:
4158 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004159 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004160 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004161 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004162#ifdef AMD_EXTENSIONS
4163 case glslang::EOpMinInvocations:
4164 case glslang::EOpMaxInvocations:
4165 case glslang::EOpAddInvocations:
4166 case glslang::EOpMinInvocationsNonUniform:
4167 case glslang::EOpMaxInvocationsNonUniform:
4168 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004169 case glslang::EOpMinInvocationsInclusiveScan:
4170 case glslang::EOpMaxInvocationsInclusiveScan:
4171 case glslang::EOpAddInvocationsInclusiveScan:
4172 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4173 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4174 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4175 case glslang::EOpMinInvocationsExclusiveScan:
4176 case glslang::EOpMaxInvocationsExclusiveScan:
4177 case glslang::EOpAddInvocationsExclusiveScan:
4178 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4179 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4180 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004181#endif
Rex Xu51596642016-09-21 18:56:12 +08004182 {
4183 std::vector<spv::Id> operands;
4184 operands.push_back(operand);
4185 return createInvocationsOperation(op, typeId, operands, typeProxy);
4186 }
Rex Xu9d93a232016-05-05 12:30:44 +08004187
4188#ifdef AMD_EXTENSIONS
4189 case glslang::EOpMbcnt:
4190 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4191 libCall = spv::MbcntAMD;
4192 break;
4193
4194 case glslang::EOpCubeFaceIndex:
4195 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4196 libCall = spv::CubeFaceIndexAMD;
4197 break;
4198
4199 case glslang::EOpCubeFaceCoord:
4200 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4201 libCall = spv::CubeFaceCoordAMD;
4202 break;
4203#endif
Rex Xu338b1852016-05-05 20:38:33 +08004204
John Kessenich140f3df2015-06-26 16:58:36 -06004205 default:
4206 return 0;
4207 }
4208
4209 spv::Id id;
4210 if (libCall >= 0) {
4211 std::vector<spv::Id> args;
4212 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004213 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004214 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004215 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004216 }
John Kessenich140f3df2015-06-26 16:58:36 -06004217
qining25262b32016-05-06 17:25:16 -04004218 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004219 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004220}
4221
John Kessenich7a53f762016-01-20 11:19:27 -07004222// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004223spv::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 -07004224{
4225 // Handle unary operations vector by vector.
4226 // The result type is the same type as the original type.
4227 // The algorithm is to:
4228 // - break the matrix into vectors
4229 // - apply the operation to each vector
4230 // - make a matrix out the vector results
4231
4232 // get the types sorted out
4233 int numCols = builder.getNumColumns(operand);
4234 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004235 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4236 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004237 std::vector<spv::Id> results;
4238
4239 // do each vector op
4240 for (int c = 0; c < numCols; ++c) {
4241 std::vector<unsigned int> indexes;
4242 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004243 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4244 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4245 addDecoration(destVec, noContraction);
4246 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004247 }
4248
4249 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004250 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004251}
4252
Rex Xu73e3ce72016-04-27 18:48:17 +08004253spv::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 -06004254{
4255 spv::Op convOp = spv::OpNop;
4256 spv::Id zero = 0;
4257 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004258 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004259
4260 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4261
4262 switch (op) {
4263 case glslang::EOpConvIntToBool:
4264 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004265 case glslang::EOpConvInt64ToBool:
4266 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004267#ifdef AMD_EXTENSIONS
4268 case glslang::EOpConvInt16ToBool:
4269 case glslang::EOpConvUint16ToBool:
4270#endif
4271 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4272 zero = builder.makeUint64Constant(0);
4273#ifdef AMD_EXTENSIONS
4274 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4275 zero = builder.makeUint16Constant(0);
4276#endif
4277 else
4278 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004279 zero = makeSmearedConstant(zero, vectorSize);
4280 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4281
4282 case glslang::EOpConvFloatToBool:
4283 zero = builder.makeFloatConstant(0.0F);
4284 zero = makeSmearedConstant(zero, vectorSize);
4285 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4286
4287 case glslang::EOpConvDoubleToBool:
4288 zero = builder.makeDoubleConstant(0.0);
4289 zero = makeSmearedConstant(zero, vectorSize);
4290 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4291
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004292#ifdef AMD_EXTENSIONS
4293 case glslang::EOpConvFloat16ToBool:
4294 zero = builder.makeFloat16Constant(0.0F);
4295 zero = makeSmearedConstant(zero, vectorSize);
4296 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4297#endif
4298
John Kessenich140f3df2015-06-26 16:58:36 -06004299 case glslang::EOpConvBoolToFloat:
4300 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004301 zero = builder.makeFloatConstant(0.0F);
4302 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004303 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004304
John Kessenich140f3df2015-06-26 16:58:36 -06004305 case glslang::EOpConvBoolToDouble:
4306 convOp = spv::OpSelect;
4307 zero = builder.makeDoubleConstant(0.0);
4308 one = builder.makeDoubleConstant(1.0);
4309 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004310
4311#ifdef AMD_EXTENSIONS
4312 case glslang::EOpConvBoolToFloat16:
4313 convOp = spv::OpSelect;
4314 zero = builder.makeFloat16Constant(0.0F);
4315 one = builder.makeFloat16Constant(1.0F);
4316 break;
4317#endif
4318
John Kessenich140f3df2015-06-26 16:58:36 -06004319 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004320 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004321#ifdef AMD_EXTENSIONS
4322 case glslang::EOpConvBoolToInt16:
4323#endif
4324 if (op == glslang::EOpConvBoolToInt64)
4325 zero = builder.makeInt64Constant(0);
4326#ifdef AMD_EXTENSIONS
4327 else if (op == glslang::EOpConvBoolToInt16)
4328 zero = builder.makeInt16Constant(0);
4329#endif
4330 else
4331 zero = builder.makeIntConstant(0);
4332
4333 if (op == glslang::EOpConvBoolToInt64)
4334 one = builder.makeInt64Constant(1);
4335#ifdef AMD_EXTENSIONS
4336 else if (op == glslang::EOpConvBoolToInt16)
4337 one = builder.makeInt16Constant(1);
4338#endif
4339 else
4340 one = builder.makeIntConstant(1);
4341
John Kessenich140f3df2015-06-26 16:58:36 -06004342 convOp = spv::OpSelect;
4343 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004344
John Kessenich140f3df2015-06-26 16:58:36 -06004345 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004346 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004347#ifdef AMD_EXTENSIONS
4348 case glslang::EOpConvBoolToUint16:
4349#endif
4350 if (op == glslang::EOpConvBoolToUint64)
4351 zero = builder.makeUint64Constant(0);
4352#ifdef AMD_EXTENSIONS
4353 else if (op == glslang::EOpConvBoolToUint16)
4354 zero = builder.makeUint16Constant(0);
4355#endif
4356 else
4357 zero = builder.makeUintConstant(0);
4358
4359 if (op == glslang::EOpConvBoolToUint64)
4360 one = builder.makeUint64Constant(1);
4361#ifdef AMD_EXTENSIONS
4362 else if (op == glslang::EOpConvBoolToUint16)
4363 one = builder.makeUint16Constant(1);
4364#endif
4365 else
4366 one = builder.makeUintConstant(1);
4367
John Kessenich140f3df2015-06-26 16:58:36 -06004368 convOp = spv::OpSelect;
4369 break;
4370
4371 case glslang::EOpConvIntToFloat:
4372 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004373 case glslang::EOpConvInt64ToFloat:
4374 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004375#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004376 case glslang::EOpConvInt16ToFloat:
4377 case glslang::EOpConvInt16ToDouble:
4378 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004379 case glslang::EOpConvIntToFloat16:
4380 case glslang::EOpConvInt64ToFloat16:
4381#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004382 convOp = spv::OpConvertSToF;
4383 break;
4384
4385 case glslang::EOpConvUintToFloat:
4386 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004387 case glslang::EOpConvUint64ToFloat:
4388 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004389#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004390 case glslang::EOpConvUint16ToFloat:
4391 case glslang::EOpConvUint16ToDouble:
4392 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004393 case glslang::EOpConvUintToFloat16:
4394 case glslang::EOpConvUint64ToFloat16:
4395#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004396 convOp = spv::OpConvertUToF;
4397 break;
4398
4399 case glslang::EOpConvDoubleToFloat:
4400 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004401#ifdef AMD_EXTENSIONS
4402 case glslang::EOpConvDoubleToFloat16:
4403 case glslang::EOpConvFloat16ToDouble:
4404 case glslang::EOpConvFloatToFloat16:
4405 case glslang::EOpConvFloat16ToFloat:
4406#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004407 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004408 if (builder.isMatrixType(destType))
4409 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004410 break;
4411
4412 case glslang::EOpConvFloatToInt:
4413 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004414 case glslang::EOpConvFloatToInt64:
4415 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004416#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004417 case glslang::EOpConvFloatToInt16:
4418 case glslang::EOpConvDoubleToInt16:
4419 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004420 case glslang::EOpConvFloat16ToInt:
4421 case glslang::EOpConvFloat16ToInt64:
4422#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004423 convOp = spv::OpConvertFToS;
4424 break;
4425
4426 case glslang::EOpConvUintToInt:
4427 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004428 case glslang::EOpConvUint64ToInt64:
4429 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004430#ifdef AMD_EXTENSIONS
4431 case glslang::EOpConvUint16ToInt16:
4432 case glslang::EOpConvInt16ToUint16:
4433#endif
qininge24aa5e2016-04-07 15:40:27 -04004434 if (builder.isInSpecConstCodeGenMode()) {
4435 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004436 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4437 zero = builder.makeUint64Constant(0);
4438#ifdef AMD_EXTENSIONS
4439 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4440 zero = builder.makeUint16Constant(0);
4441#endif
4442 else
4443 zero = builder.makeUintConstant(0);
4444
qining189b2032016-04-12 23:16:20 -04004445 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004446 // Use OpIAdd, instead of OpBitcast to do the conversion when
4447 // generating for OpSpecConstantOp instruction.
4448 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4449 }
4450 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004451 convOp = spv::OpBitcast;
4452 break;
4453
4454 case glslang::EOpConvFloatToUint:
4455 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004456 case glslang::EOpConvFloatToUint64:
4457 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004458#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004459 case glslang::EOpConvFloatToUint16:
4460 case glslang::EOpConvDoubleToUint16:
4461 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004462 case glslang::EOpConvFloat16ToUint:
4463 case glslang::EOpConvFloat16ToUint64:
4464#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004465 convOp = spv::OpConvertFToU;
4466 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004467
4468 case glslang::EOpConvIntToInt64:
4469 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004470#ifdef AMD_EXTENSIONS
4471 case glslang::EOpConvIntToInt16:
4472 case glslang::EOpConvInt16ToInt:
4473 case glslang::EOpConvInt64ToInt16:
4474 case glslang::EOpConvInt16ToInt64:
4475#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004476 convOp = spv::OpSConvert;
4477 break;
4478
4479 case glslang::EOpConvUintToUint64:
4480 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004481#ifdef AMD_EXTENSIONS
4482 case glslang::EOpConvUintToUint16:
4483 case glslang::EOpConvUint16ToUint:
4484 case glslang::EOpConvUint64ToUint16:
4485 case glslang::EOpConvUint16ToUint64:
4486#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004487 convOp = spv::OpUConvert;
4488 break;
4489
4490 case glslang::EOpConvIntToUint64:
4491 case glslang::EOpConvInt64ToUint:
4492 case glslang::EOpConvUint64ToInt:
4493 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004494#ifdef AMD_EXTENSIONS
4495 case glslang::EOpConvInt16ToUint:
4496 case glslang::EOpConvUintToInt16:
4497 case glslang::EOpConvInt16ToUint64:
4498 case glslang::EOpConvUint64ToInt16:
4499 case glslang::EOpConvUint16ToInt:
4500 case glslang::EOpConvIntToUint16:
4501 case glslang::EOpConvUint16ToInt64:
4502 case glslang::EOpConvInt64ToUint16:
4503#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004504 // OpSConvert/OpUConvert + OpBitCast
4505 switch (op) {
4506 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004507#ifdef AMD_EXTENSIONS
4508 case glslang::EOpConvInt16ToUint64:
4509#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004510 convOp = spv::OpSConvert;
4511 type = builder.makeIntType(64);
4512 break;
4513 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004514#ifdef AMD_EXTENSIONS
4515 case glslang::EOpConvInt16ToUint:
4516#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004517 convOp = spv::OpSConvert;
4518 type = builder.makeIntType(32);
4519 break;
4520 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004521#ifdef AMD_EXTENSIONS
4522 case glslang::EOpConvUint16ToInt:
4523#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004524 convOp = spv::OpUConvert;
4525 type = builder.makeUintType(32);
4526 break;
4527 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004528#ifdef AMD_EXTENSIONS
4529 case glslang::EOpConvUint16ToInt64:
4530#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004531 convOp = spv::OpUConvert;
4532 type = builder.makeUintType(64);
4533 break;
Rex Xucabbb782017-03-24 13:41:14 +08004534#ifdef AMD_EXTENSIONS
4535 case glslang::EOpConvUintToInt16:
4536 case glslang::EOpConvUint64ToInt16:
4537 convOp = spv::OpUConvert;
4538 type = builder.makeUintType(16);
4539 break;
4540 case glslang::EOpConvIntToUint16:
4541 case glslang::EOpConvInt64ToUint16:
4542 convOp = spv::OpSConvert;
4543 type = builder.makeIntType(16);
4544 break;
4545#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004546 default:
4547 assert(0);
4548 break;
4549 }
4550
4551 if (vectorSize > 0)
4552 type = builder.makeVectorType(type, vectorSize);
4553
4554 operand = builder.createUnaryOp(convOp, type, operand);
4555
4556 if (builder.isInSpecConstCodeGenMode()) {
4557 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004558#ifdef AMD_EXTENSIONS
4559 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4560 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4561 zero = builder.makeUint64Constant(0);
4562 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4563 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4564 zero = builder.makeUint16Constant(0);
4565 else
4566 zero = builder.makeUintConstant(0);
4567#else
4568 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4569 zero = builder.makeUint64Constant(0);
4570 else
4571 zero = builder.makeUintConstant(0);
4572#endif
4573
Rex Xu8ff43de2016-04-22 16:51:45 +08004574 zero = makeSmearedConstant(zero, vectorSize);
4575 // Use OpIAdd, instead of OpBitcast to do the conversion when
4576 // generating for OpSpecConstantOp instruction.
4577 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4578 }
4579 // For normal run-time conversion instruction, use OpBitcast.
4580 convOp = spv::OpBitcast;
4581 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004582 default:
4583 break;
4584 }
4585
4586 spv::Id result = 0;
4587 if (convOp == spv::OpNop)
4588 return result;
4589
4590 if (convOp == spv::OpSelect) {
4591 zero = makeSmearedConstant(zero, vectorSize);
4592 one = makeSmearedConstant(one, vectorSize);
4593 result = builder.createTriOp(convOp, destType, operand, one, zero);
4594 } else
4595 result = builder.createUnaryOp(convOp, destType, operand);
4596
John Kessenich32cfd492016-02-02 12:37:46 -07004597 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004598}
4599
4600spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4601{
4602 if (vectorSize == 0)
4603 return constant;
4604
4605 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4606 std::vector<spv::Id> components;
4607 for (int c = 0; c < vectorSize; ++c)
4608 components.push_back(constant);
4609 return builder.makeCompositeConstant(vectorTypeId, components);
4610}
4611
John Kessenich426394d2015-07-23 10:22:48 -06004612// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004613spv::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 -06004614{
4615 spv::Op opCode = spv::OpNop;
4616
4617 switch (op) {
4618 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004619 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004620 opCode = spv::OpAtomicIAdd;
4621 break;
4622 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004623 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004624 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004625 break;
4626 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004627 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004628 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004629 break;
4630 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004631 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004632 opCode = spv::OpAtomicAnd;
4633 break;
4634 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004635 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004636 opCode = spv::OpAtomicOr;
4637 break;
4638 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004639 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004640 opCode = spv::OpAtomicXor;
4641 break;
4642 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004643 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004644 opCode = spv::OpAtomicExchange;
4645 break;
4646 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004647 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004648 opCode = spv::OpAtomicCompareExchange;
4649 break;
4650 case glslang::EOpAtomicCounterIncrement:
4651 opCode = spv::OpAtomicIIncrement;
4652 break;
4653 case glslang::EOpAtomicCounterDecrement:
4654 opCode = spv::OpAtomicIDecrement;
4655 break;
4656 case glslang::EOpAtomicCounter:
4657 opCode = spv::OpAtomicLoad;
4658 break;
4659 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004660 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004661 break;
4662 }
4663
4664 // Sort out the operands
4665 // - mapping from glslang -> SPV
4666 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004667 // - compare-exchange swaps the value and comparator
4668 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004669 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4670 auto opIt = operands.begin(); // walk the glslang operands
4671 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004672 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4673 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4674 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004675 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4676 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004677 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004678 spvAtomicOperands.push_back(*(opIt + 1));
4679 spvAtomicOperands.push_back(*opIt);
4680 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004681 }
John Kessenich426394d2015-07-23 10:22:48 -06004682
John Kessenich3e60a6f2015-09-14 22:45:16 -06004683 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004684 for (; opIt != operands.end(); ++opIt)
4685 spvAtomicOperands.push_back(*opIt);
4686
4687 return builder.createOp(opCode, typeId, spvAtomicOperands);
4688}
4689
John Kessenich91cef522016-05-05 16:45:40 -06004690// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004691spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004692{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004693#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004694 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004695 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004696#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004697
Rex Xu51596642016-09-21 18:56:12 +08004698 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004699 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004700 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4701
chaocf200da82016-12-20 12:44:35 -08004702 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4703 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004704 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4705 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004706 } else if (op == glslang::EOpAnyInvocation ||
4707 op == glslang::EOpAllInvocations ||
4708 op == glslang::EOpAllInvocationsEqual) {
4709 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4710 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004711 } else {
4712 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004713#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004714 if (op == glslang::EOpMinInvocationsNonUniform ||
4715 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004716 op == glslang::EOpAddInvocationsNonUniform ||
4717 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4718 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4719 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4720 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4721 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4722 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004723 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004724#endif
Rex Xu51596642016-09-21 18:56:12 +08004725
4726 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004727#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004728 switch (op) {
4729 case glslang::EOpMinInvocations:
4730 case glslang::EOpMaxInvocations:
4731 case glslang::EOpAddInvocations:
4732 case glslang::EOpMinInvocationsNonUniform:
4733 case glslang::EOpMaxInvocationsNonUniform:
4734 case glslang::EOpAddInvocationsNonUniform:
4735 groupOperation = spv::GroupOperationReduce;
4736 spvGroupOperands.push_back(groupOperation);
4737 break;
4738 case glslang::EOpMinInvocationsInclusiveScan:
4739 case glslang::EOpMaxInvocationsInclusiveScan:
4740 case glslang::EOpAddInvocationsInclusiveScan:
4741 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4742 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4743 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4744 groupOperation = spv::GroupOperationInclusiveScan;
4745 spvGroupOperands.push_back(groupOperation);
4746 break;
4747 case glslang::EOpMinInvocationsExclusiveScan:
4748 case glslang::EOpMaxInvocationsExclusiveScan:
4749 case glslang::EOpAddInvocationsExclusiveScan:
4750 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4751 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4752 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4753 groupOperation = spv::GroupOperationExclusiveScan;
4754 spvGroupOperands.push_back(groupOperation);
4755 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004756 default:
4757 break;
Rex Xu430ef402016-10-14 17:22:23 +08004758 }
Rex Xu9d93a232016-05-05 12:30:44 +08004759#endif
Rex Xu51596642016-09-21 18:56:12 +08004760 }
4761
4762 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4763 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004764
4765 switch (op) {
4766 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004767 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004768 break;
John Kessenich91cef522016-05-05 16:45:40 -06004769 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004770 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004771 break;
John Kessenich91cef522016-05-05 16:45:40 -06004772 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004773 opCode = spv::OpSubgroupAllEqualKHR;
4774 break;
Rex Xu51596642016-09-21 18:56:12 +08004775 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004776 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004777 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004778 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004779 break;
4780 case glslang::EOpReadFirstInvocation:
4781 opCode = spv::OpSubgroupFirstInvocationKHR;
4782 break;
4783 case glslang::EOpBallot:
4784 {
4785 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4786 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4787 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4788 //
4789 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4790 //
4791 spv::Id uintType = builder.makeUintType(32);
4792 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4793 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4794
4795 std::vector<spv::Id> components;
4796 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4797 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4798
4799 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4800 return builder.createUnaryOp(spv::OpBitcast, typeId,
4801 builder.createCompositeConstruct(uvec2Type, components));
4802 }
4803
Rex Xu9d93a232016-05-05 12:30:44 +08004804#ifdef AMD_EXTENSIONS
4805 case glslang::EOpMinInvocations:
4806 case glslang::EOpMaxInvocations:
4807 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004808 case glslang::EOpMinInvocationsInclusiveScan:
4809 case glslang::EOpMaxInvocationsInclusiveScan:
4810 case glslang::EOpAddInvocationsInclusiveScan:
4811 case glslang::EOpMinInvocationsExclusiveScan:
4812 case glslang::EOpMaxInvocationsExclusiveScan:
4813 case glslang::EOpAddInvocationsExclusiveScan:
4814 if (op == glslang::EOpMinInvocations ||
4815 op == glslang::EOpMinInvocationsInclusiveScan ||
4816 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004817 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004818 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004819 else {
4820 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004821 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004822 else
Rex Xu51596642016-09-21 18:56:12 +08004823 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004824 }
Rex Xu430ef402016-10-14 17:22:23 +08004825 } else if (op == glslang::EOpMaxInvocations ||
4826 op == glslang::EOpMaxInvocationsInclusiveScan ||
4827 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004828 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004829 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004830 else {
4831 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004832 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004833 else
Rex Xu51596642016-09-21 18:56:12 +08004834 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004835 }
4836 } else {
4837 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004838 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004839 else
Rex Xu51596642016-09-21 18:56:12 +08004840 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004841 }
4842
Rex Xu2bbbe062016-08-23 15:41:05 +08004843 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004844 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004845
4846 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004847 case glslang::EOpMinInvocationsNonUniform:
4848 case glslang::EOpMaxInvocationsNonUniform:
4849 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004850 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4851 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4852 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4853 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4854 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4855 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4856 if (op == glslang::EOpMinInvocationsNonUniform ||
4857 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4858 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004859 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004860 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004861 else {
4862 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004863 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004864 else
Rex Xu51596642016-09-21 18:56:12 +08004865 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004866 }
4867 }
Rex Xu430ef402016-10-14 17:22:23 +08004868 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4869 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4870 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004871 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004872 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004873 else {
4874 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004875 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004876 else
Rex Xu51596642016-09-21 18:56:12 +08004877 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004878 }
4879 }
4880 else {
4881 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004882 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004883 else
Rex Xu51596642016-09-21 18:56:12 +08004884 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004885 }
4886
Rex Xu2bbbe062016-08-23 15:41:05 +08004887 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004888 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004889
4890 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004891#endif
John Kessenich91cef522016-05-05 16:45:40 -06004892 default:
4893 logger->missingFunctionality("invocation operation");
4894 return spv::NoResult;
4895 }
Rex Xu51596642016-09-21 18:56:12 +08004896
4897 assert(opCode != spv::OpNop);
4898 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004899}
4900
Rex Xu2bbbe062016-08-23 15:41:05 +08004901// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004902spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004903{
Rex Xub7072052016-09-26 15:53:40 +08004904#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004905 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4906 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004907 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004908 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004909 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4910 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4911 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004912#else
4913 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4914 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004915 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4916 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004917#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004918
4919 // Handle group invocation operations scalar by scalar.
4920 // The result type is the same type as the original type.
4921 // The algorithm is to:
4922 // - break the vector into scalars
4923 // - apply the operation to each scalar
4924 // - make a vector out the scalar results
4925
4926 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004927 int numComponents = builder.getNumComponents(operands[0]);
4928 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004929 std::vector<spv::Id> results;
4930
4931 // do each scalar op
4932 for (int comp = 0; comp < numComponents; ++comp) {
4933 std::vector<unsigned int> indexes;
4934 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004935 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004936 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004937 if (op == spv::OpSubgroupReadInvocationKHR) {
4938 spvGroupOperands.push_back(scalar);
4939 spvGroupOperands.push_back(operands[1]);
4940 } else if (op == spv::OpGroupBroadcast) {
4941 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004942 spvGroupOperands.push_back(scalar);
4943 spvGroupOperands.push_back(operands[1]);
4944 } else {
chaocf200da82016-12-20 12:44:35 -08004945 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004946 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004947 spvGroupOperands.push_back(scalar);
4948 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004949
Rex Xub7072052016-09-26 15:53:40 +08004950 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004951 }
4952
4953 // put the pieces together
4954 return builder.createCompositeConstruct(typeId, results);
4955}
Rex Xu2bbbe062016-08-23 15:41:05 +08004956
John Kessenich5e4b1242015-08-06 22:53:06 -06004957spv::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 -06004958{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004959#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004960 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004961 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4962#else
Rex Xucabbb782017-03-24 13:41:14 +08004963 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004964 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004965#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004966
John Kessenich140f3df2015-06-26 16:58:36 -06004967 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004968 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004969 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004970 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004971 spv::Id typeId0 = 0;
4972 if (consumedOperands > 0)
4973 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004974 spv::Id typeId1 = 0;
4975 if (consumedOperands > 1)
4976 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004977 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004978
4979 switch (op) {
4980 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004981 if (isFloat)
4982 libCall = spv::GLSLstd450FMin;
4983 else if (isUnsigned)
4984 libCall = spv::GLSLstd450UMin;
4985 else
4986 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004987 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004988 break;
4989 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004990 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004991 break;
4992 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004993 if (isFloat)
4994 libCall = spv::GLSLstd450FMax;
4995 else if (isUnsigned)
4996 libCall = spv::GLSLstd450UMax;
4997 else
4998 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004999 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005000 break;
5001 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005002 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005003 break;
5004 case glslang::EOpDot:
5005 opCode = spv::OpDot;
5006 break;
5007 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005008 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005009 break;
5010
5011 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005012 if (isFloat)
5013 libCall = spv::GLSLstd450FClamp;
5014 else if (isUnsigned)
5015 libCall = spv::GLSLstd450UClamp;
5016 else
5017 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005018 builder.promoteScalar(precision, operands.front(), operands[1]);
5019 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005020 break;
5021 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005022 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5023 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005024 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005025 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005026 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005027 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005028 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005029 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005030 break;
5031 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005032 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005033 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005034 break;
5035 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005036 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005037 builder.promoteScalar(precision, operands[0], operands[2]);
5038 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005039 break;
5040
5041 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005042 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005043 break;
5044 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005045 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005046 break;
5047 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005048 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005049 break;
5050 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005051 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005052 break;
5053 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005054 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005055 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005056 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005057 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005058 libCall = spv::GLSLstd450InterpolateAtSample;
5059 break;
5060 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005061 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005062 libCall = spv::GLSLstd450InterpolateAtOffset;
5063 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005064 case glslang::EOpAddCarry:
5065 opCode = spv::OpIAddCarry;
5066 typeId = builder.makeStructResultType(typeId0, typeId0);
5067 consumedOperands = 2;
5068 break;
5069 case glslang::EOpSubBorrow:
5070 opCode = spv::OpISubBorrow;
5071 typeId = builder.makeStructResultType(typeId0, typeId0);
5072 consumedOperands = 2;
5073 break;
5074 case glslang::EOpUMulExtended:
5075 opCode = spv::OpUMulExtended;
5076 typeId = builder.makeStructResultType(typeId0, typeId0);
5077 consumedOperands = 2;
5078 break;
5079 case glslang::EOpIMulExtended:
5080 opCode = spv::OpSMulExtended;
5081 typeId = builder.makeStructResultType(typeId0, typeId0);
5082 consumedOperands = 2;
5083 break;
5084 case glslang::EOpBitfieldExtract:
5085 if (isUnsigned)
5086 opCode = spv::OpBitFieldUExtract;
5087 else
5088 opCode = spv::OpBitFieldSExtract;
5089 break;
5090 case glslang::EOpBitfieldInsert:
5091 opCode = spv::OpBitFieldInsert;
5092 break;
5093
5094 case glslang::EOpFma:
5095 libCall = spv::GLSLstd450Fma;
5096 break;
5097 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005098 {
5099 libCall = spv::GLSLstd450FrexpStruct;
5100 assert(builder.isPointerType(typeId1));
5101 typeId1 = builder.getContainedTypeId(typeId1);
5102#ifdef AMD_EXTENSIONS
5103 int width = builder.getScalarTypeWidth(typeId1);
5104#else
5105 int width = 32;
5106#endif
5107 if (builder.getNumComponents(operands[0]) == 1)
5108 frexpIntType = builder.makeIntegerType(width, true);
5109 else
5110 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5111 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5112 consumedOperands = 1;
5113 }
John Kessenich55e7d112015-11-15 21:33:39 -07005114 break;
5115 case glslang::EOpLdexp:
5116 libCall = spv::GLSLstd450Ldexp;
5117 break;
5118
Rex Xu574ab042016-04-14 16:53:07 +08005119 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005120 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005121
Rex Xu9d93a232016-05-05 12:30:44 +08005122#ifdef AMD_EXTENSIONS
5123 case glslang::EOpSwizzleInvocations:
5124 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5125 libCall = spv::SwizzleInvocationsAMD;
5126 break;
5127 case glslang::EOpSwizzleInvocationsMasked:
5128 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5129 libCall = spv::SwizzleInvocationsMaskedAMD;
5130 break;
5131 case glslang::EOpWriteInvocation:
5132 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5133 libCall = spv::WriteInvocationAMD;
5134 break;
5135
5136 case glslang::EOpMin3:
5137 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5138 if (isFloat)
5139 libCall = spv::FMin3AMD;
5140 else {
5141 if (isUnsigned)
5142 libCall = spv::UMin3AMD;
5143 else
5144 libCall = spv::SMin3AMD;
5145 }
5146 break;
5147 case glslang::EOpMax3:
5148 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5149 if (isFloat)
5150 libCall = spv::FMax3AMD;
5151 else {
5152 if (isUnsigned)
5153 libCall = spv::UMax3AMD;
5154 else
5155 libCall = spv::SMax3AMD;
5156 }
5157 break;
5158 case glslang::EOpMid3:
5159 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5160 if (isFloat)
5161 libCall = spv::FMid3AMD;
5162 else {
5163 if (isUnsigned)
5164 libCall = spv::UMid3AMD;
5165 else
5166 libCall = spv::SMid3AMD;
5167 }
5168 break;
5169
5170 case glslang::EOpInterpolateAtVertex:
5171 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5172 libCall = spv::InterpolateAtVertexAMD;
5173 break;
5174#endif
5175
John Kessenich140f3df2015-06-26 16:58:36 -06005176 default:
5177 return 0;
5178 }
5179
5180 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005181 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005182 // Use an extended instruction from the standard library.
5183 // Construct the call arguments, without modifying the original operands vector.
5184 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5185 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005186 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005187 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005188 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005189 case 0:
5190 // should all be handled by visitAggregate and createNoArgOperation
5191 assert(0);
5192 return 0;
5193 case 1:
5194 // should all be handled by createUnaryOperation
5195 assert(0);
5196 return 0;
5197 case 2:
5198 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5199 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005200 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005201 // anything 3 or over doesn't have l-value operands, so all should be consumed
5202 assert(consumedOperands == operands.size());
5203 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005204 break;
5205 }
5206 }
5207
John Kessenich55e7d112015-11-15 21:33:39 -07005208 // Decode the return types that were structures
5209 switch (op) {
5210 case glslang::EOpAddCarry:
5211 case glslang::EOpSubBorrow:
5212 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5213 id = builder.createCompositeExtract(id, typeId0, 0);
5214 break;
5215 case glslang::EOpUMulExtended:
5216 case glslang::EOpIMulExtended:
5217 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5218 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5219 break;
5220 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005221 {
5222 assert(operands.size() == 2);
5223 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5224 // "exp" is floating-point type (from HLSL intrinsic)
5225 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5226 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5227 builder.createStore(member1, operands[1]);
5228 } else
5229 // "exp" is integer type (from GLSL built-in function)
5230 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5231 id = builder.createCompositeExtract(id, typeId0, 0);
5232 }
John Kessenich55e7d112015-11-15 21:33:39 -07005233 break;
5234 default:
5235 break;
5236 }
5237
John Kessenich32cfd492016-02-02 12:37:46 -07005238 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005239}
5240
Rex Xu9d93a232016-05-05 12:30:44 +08005241// Intrinsics with no arguments (or no return value, and no precision).
5242spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005243{
5244 // TODO: get the barrier operands correct
5245
5246 switch (op) {
5247 case glslang::EOpEmitVertex:
5248 builder.createNoResultOp(spv::OpEmitVertex);
5249 return 0;
5250 case glslang::EOpEndPrimitive:
5251 builder.createNoResultOp(spv::OpEndPrimitive);
5252 return 0;
5253 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005254 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005255 return 0;
5256 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005257 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005258 return 0;
5259 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005260 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005261 return 0;
5262 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005263 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005264 return 0;
5265 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005266 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005267 return 0;
5268 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005269 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005270 return 0;
5271 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005272 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005273 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005274 case glslang::EOpAllMemoryBarrierWithGroupSync:
5275 // Control barrier with non-"None" semantic is also a memory barrier.
5276 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5277 return 0;
5278 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5279 // Control barrier with non-"None" semantic is also a memory barrier.
5280 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5281 return 0;
5282 case glslang::EOpWorkgroupMemoryBarrier:
5283 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5284 return 0;
5285 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5286 // Control barrier with non-"None" semantic is also a memory barrier.
5287 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5288 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005289#ifdef AMD_EXTENSIONS
5290 case glslang::EOpTime:
5291 {
5292 std::vector<spv::Id> args; // Dummy arguments
5293 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5294 return builder.setPrecision(id, precision);
5295 }
5296#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005297 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005298 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005299 return 0;
5300 }
5301}
5302
5303spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5304{
John Kessenich2f273362015-07-18 22:34:27 -06005305 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005306 spv::Id id;
5307 if (symbolValues.end() != iter) {
5308 id = iter->second;
5309 return id;
5310 }
5311
5312 // it was not found, create it
5313 id = createSpvVariable(symbol);
5314 symbolValues[symbol->getId()] = id;
5315
Rex Xuc884b4a2016-06-29 15:03:44 +08005316 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005317 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005318 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005319 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005320 if (symbol->getType().getQualifier().hasSpecConstantId())
5321 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005322 if (symbol->getQualifier().hasIndex())
5323 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5324 if (symbol->getQualifier().hasComponent())
5325 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5326 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005327 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005328 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005329 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005330 if (symbol->getQualifier().hasXfbBuffer())
5331 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5332 if (symbol->getQualifier().hasXfbOffset())
5333 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5334 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005335 // atomic counters use this:
5336 if (symbol->getQualifier().hasOffset())
5337 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005338 }
5339
scygan2c864272016-05-18 18:09:17 +02005340 if (symbol->getQualifier().hasLocation())
5341 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005342 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005343 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005344 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005345 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005346 }
John Kessenich140f3df2015-06-26 16:58:36 -06005347 if (symbol->getQualifier().hasSet())
5348 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005349 else if (IsDescriptorResource(symbol->getType())) {
5350 // default to 0
5351 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5352 }
John Kessenich140f3df2015-06-26 16:58:36 -06005353 if (symbol->getQualifier().hasBinding())
5354 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005355 if (symbol->getQualifier().hasAttachment())
5356 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005357 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005358 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005359 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005360 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005361 if (symbol->getQualifier().hasXfbBuffer())
5362 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5363 }
5364
Rex Xu1da878f2016-02-21 20:59:01 +08005365 if (symbol->getType().isImage()) {
5366 std::vector<spv::Decoration> memory;
5367 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5368 for (unsigned int i = 0; i < memory.size(); ++i)
5369 addDecoration(id, memory[i]);
5370 }
5371
John Kessenich140f3df2015-06-26 16:58:36 -06005372 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005373 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005374 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005375 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005376
John Kessenichecba76f2017-01-06 00:34:48 -07005377#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005378 if (builtIn == spv::BuiltInSampleMask) {
5379 spv::Decoration decoration;
5380 // GL_NV_sample_mask_override_coverage extension
5381 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005382 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005383 else
5384 decoration = (spv::Decoration)spv::DecorationMax;
5385 addDecoration(id, decoration);
5386 if (decoration != spv::DecorationMax) {
5387 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5388 }
5389 }
chaoc771d89f2017-01-13 01:10:53 -08005390 else if (builtIn == spv::BuiltInLayer) {
5391 // SPV_NV_viewport_array2 extension
5392 if (symbol->getQualifier().layoutViewportRelative)
5393 {
5394 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5395 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5396 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5397 }
5398 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5399 {
5400 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5401 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5402 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5403 }
5404 }
5405
chaoc6e5acae2016-12-20 13:28:52 -08005406 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005407 addDecoration(id, spv::DecorationPassthroughNV);
5408 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005409 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5410 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005411#endif
5412
John Kessenich140f3df2015-06-26 16:58:36 -06005413 return id;
5414}
5415
John Kessenich55e7d112015-11-15 21:33:39 -07005416// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005417void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5418{
John Kessenich4016e382016-07-15 11:53:56 -06005419 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005420 builder.addDecoration(id, dec);
5421}
5422
John Kessenich55e7d112015-11-15 21:33:39 -07005423// If 'dec' is valid, add a one-operand decoration to an object
5424void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5425{
John Kessenich4016e382016-07-15 11:53:56 -06005426 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005427 builder.addDecoration(id, dec, value);
5428}
5429
5430// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005431void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5432{
John Kessenich4016e382016-07-15 11:53:56 -06005433 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005434 builder.addMemberDecoration(id, (unsigned)member, dec);
5435}
5436
John Kessenich92187592016-02-01 13:45:25 -07005437// If 'dec' is valid, add a one-operand decoration to a struct member
5438void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5439{
John Kessenich4016e382016-07-15 11:53:56 -06005440 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005441 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5442}
5443
John Kessenich55e7d112015-11-15 21:33:39 -07005444// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005445// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005446//
5447// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5448//
5449// Recursively walk the nodes. The nodes form a tree whose leaves are
5450// regular constants, which themselves are trees that createSpvConstant()
5451// recursively walks. So, this function walks the "top" of the tree:
5452// - emit specialization constant-building instructions for specConstant
5453// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005454spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005455{
John Kessenich7cc0e282016-03-20 00:46:02 -06005456 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005457
qining4f4bb812016-04-03 23:55:17 -04005458 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005459 if (! node.getQualifier().specConstant) {
5460 // hand off to the non-spec-constant path
5461 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5462 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005463 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005464 nextConst, false);
5465 }
5466
5467 // We now know we have a specialization constant to build
5468
John Kessenichd94c0032016-05-30 19:29:40 -06005469 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005470 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5471 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5472 std::vector<spv::Id> dimConstId;
5473 for (int dim = 0; dim < 3; ++dim) {
5474 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5475 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5476 if (specConst)
5477 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5478 }
5479 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5480 }
5481
5482 // An AST node labelled as specialization constant should be a symbol node.
5483 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5484 if (auto* sn = node.getAsSymbolNode()) {
5485 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005486 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5487 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5488 // will set the builder into spec constant op instruction generating mode.
5489 sub_tree->traverse(this);
5490 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005491 } else if (auto* const_union_array = &sn->getConstArray()){
5492 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005493 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5494 builder.addName(id, sn->getName().c_str());
5495 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005496 }
5497 }
qining4f4bb812016-04-03 23:55:17 -04005498
5499 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5500 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005501 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005502 exit(1);
5503 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005504}
5505
John Kessenich140f3df2015-06-26 16:58:36 -06005506// Use 'consts' as the flattened glslang source of scalar constants to recursively
5507// build the aggregate SPIR-V constant.
5508//
5509// If there are not enough elements present in 'consts', 0 will be substituted;
5510// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5511//
qining08408382016-03-21 09:51:37 -04005512spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005513{
5514 // vector of constants for SPIR-V
5515 std::vector<spv::Id> spvConsts;
5516
5517 // Type is used for struct and array constants
5518 spv::Id typeId = convertGlslangToSpvType(glslangType);
5519
5520 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005521 glslang::TType elementType(glslangType, 0);
5522 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005523 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005524 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005525 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005526 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005527 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005528 } else if (glslangType.getStruct()) {
5529 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5530 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005531 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005532 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005533 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5534 bool zero = nextConst >= consts.size();
5535 switch (glslangType.getBasicType()) {
5536 case glslang::EbtInt:
5537 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5538 break;
5539 case glslang::EbtUint:
5540 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5541 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005542 case glslang::EbtInt64:
5543 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5544 break;
5545 case glslang::EbtUint64:
5546 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5547 break;
Rex Xucabbb782017-03-24 13:41:14 +08005548#ifdef AMD_EXTENSIONS
5549 case glslang::EbtInt16:
5550 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5551 break;
5552 case glslang::EbtUint16:
5553 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5554 break;
5555#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005556 case glslang::EbtFloat:
5557 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5558 break;
5559 case glslang::EbtDouble:
5560 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5561 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005562#ifdef AMD_EXTENSIONS
5563 case glslang::EbtFloat16:
5564 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5565 break;
5566#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005567 case glslang::EbtBool:
5568 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5569 break;
5570 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005571 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005572 break;
5573 }
5574 ++nextConst;
5575 }
5576 } else {
5577 // we have a non-aggregate (scalar) constant
5578 bool zero = nextConst >= consts.size();
5579 spv::Id scalar = 0;
5580 switch (glslangType.getBasicType()) {
5581 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005582 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005583 break;
5584 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005585 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005586 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005587 case glslang::EbtInt64:
5588 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5589 break;
5590 case glslang::EbtUint64:
5591 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5592 break;
Rex Xucabbb782017-03-24 13:41:14 +08005593#ifdef AMD_EXTENSIONS
5594 case glslang::EbtInt16:
5595 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5596 break;
5597 case glslang::EbtUint16:
5598 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5599 break;
5600#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005601 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005602 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005603 break;
5604 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005605 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005606 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005607#ifdef AMD_EXTENSIONS
5608 case glslang::EbtFloat16:
5609 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5610 break;
5611#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005612 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005613 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005614 break;
5615 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005616 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005617 break;
5618 }
5619 ++nextConst;
5620 return scalar;
5621 }
5622
5623 return builder.makeCompositeConstant(typeId, spvConsts);
5624}
5625
John Kessenich7c1aa102015-10-15 13:29:11 -06005626// Return true if the node is a constant or symbol whose reading has no
5627// non-trivial observable cost or effect.
5628bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5629{
5630 // don't know what this is
5631 if (node == nullptr)
5632 return false;
5633
5634 // a constant is safe
5635 if (node->getAsConstantUnion() != nullptr)
5636 return true;
5637
5638 // not a symbol means non-trivial
5639 if (node->getAsSymbolNode() == nullptr)
5640 return false;
5641
5642 // a symbol, depends on what's being read
5643 switch (node->getType().getQualifier().storage) {
5644 case glslang::EvqTemporary:
5645 case glslang::EvqGlobal:
5646 case glslang::EvqIn:
5647 case glslang::EvqInOut:
5648 case glslang::EvqConst:
5649 case glslang::EvqConstReadOnly:
5650 case glslang::EvqUniform:
5651 return true;
5652 default:
5653 return false;
5654 }
qining25262b32016-05-06 17:25:16 -04005655}
John Kessenich7c1aa102015-10-15 13:29:11 -06005656
5657// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005658// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005659// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005660// Return true if trivial.
5661bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5662{
5663 if (node == nullptr)
5664 return false;
5665
John Kessenich84cc15f2017-05-24 16:44:47 -06005666 // count non scalars as trivial, as well as anything coming from HLSL
5667 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005668 return true;
5669
John Kessenich7c1aa102015-10-15 13:29:11 -06005670 // symbols and constants are trivial
5671 if (isTrivialLeaf(node))
5672 return true;
5673
5674 // otherwise, it needs to be a simple operation or one or two leaf nodes
5675
5676 // not a simple operation
5677 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5678 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5679 if (binaryNode == nullptr && unaryNode == nullptr)
5680 return false;
5681
5682 // not on leaf nodes
5683 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5684 return false;
5685
5686 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5687 return false;
5688 }
5689
5690 switch (node->getAsOperator()->getOp()) {
5691 case glslang::EOpLogicalNot:
5692 case glslang::EOpConvIntToBool:
5693 case glslang::EOpConvUintToBool:
5694 case glslang::EOpConvFloatToBool:
5695 case glslang::EOpConvDoubleToBool:
5696 case glslang::EOpEqual:
5697 case glslang::EOpNotEqual:
5698 case glslang::EOpLessThan:
5699 case glslang::EOpGreaterThan:
5700 case glslang::EOpLessThanEqual:
5701 case glslang::EOpGreaterThanEqual:
5702 case glslang::EOpIndexDirect:
5703 case glslang::EOpIndexDirectStruct:
5704 case glslang::EOpLogicalXor:
5705 case glslang::EOpAny:
5706 case glslang::EOpAll:
5707 return true;
5708 default:
5709 return false;
5710 }
5711}
5712
5713// Emit short-circuiting code, where 'right' is never evaluated unless
5714// the left side is true (for &&) or false (for ||).
5715spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5716{
5717 spv::Id boolTypeId = builder.makeBoolType();
5718
5719 // emit left operand
5720 builder.clearAccessChain();
5721 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005722 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005723
5724 // Operands to accumulate OpPhi operands
5725 std::vector<spv::Id> phiOperands;
5726 // accumulate left operand's phi information
5727 phiOperands.push_back(leftId);
5728 phiOperands.push_back(builder.getBuildPoint()->getId());
5729
5730 // Make the two kinds of operation symmetric with a "!"
5731 // || => emit "if (! left) result = right"
5732 // && => emit "if ( left) result = right"
5733 //
5734 // TODO: this runtime "not" for || could be avoided by adding functionality
5735 // to 'builder' to have an "else" without an "then"
5736 if (op == glslang::EOpLogicalOr)
5737 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5738
5739 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005740 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005741
5742 // emit right operand as the "then" part of the "if"
5743 builder.clearAccessChain();
5744 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005745 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005746
5747 // accumulate left operand's phi information
5748 phiOperands.push_back(rightId);
5749 phiOperands.push_back(builder.getBuildPoint()->getId());
5750
5751 // finish the "if"
5752 ifBuilder.makeEndIf();
5753
5754 // phi together the two results
5755 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5756}
5757
Rex Xu9d93a232016-05-05 12:30:44 +08005758// Return type Id of the imported set of extended instructions corresponds to the name.
5759// Import this set if it has not been imported yet.
5760spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5761{
5762 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5763 return extBuiltinMap[name];
5764 else {
Rex Xu51596642016-09-21 18:56:12 +08005765 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005766 spv::Id extBuiltins = builder.import(name);
5767 extBuiltinMap[name] = extBuiltins;
5768 return extBuiltins;
5769 }
5770}
5771
John Kessenich140f3df2015-06-26 16:58:36 -06005772}; // end anonymous namespace
5773
5774namespace glslang {
5775
John Kessenich68d78fd2015-07-12 19:28:10 -06005776void GetSpirvVersion(std::string& version)
5777{
John Kessenich9e55f632015-07-15 10:03:39 -06005778 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005779 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005780 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005781 version = buf;
5782}
5783
John Kessenich140f3df2015-06-26 16:58:36 -06005784// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005785void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005786{
5787 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005788 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005789 if (out.fail())
5790 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005791 for (int i = 0; i < (int)spirv.size(); ++i) {
5792 unsigned int word = spirv[i];
5793 out.write((const char*)&word, 4);
5794 }
5795 out.close();
5796}
5797
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005798// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005799void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005800{
5801 std::ofstream out;
5802 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005803 if (out.fail())
5804 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005805 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005806 if (varName != nullptr) {
5807 out << "\t #pragma once" << std::endl;
5808 out << "const uint32_t " << varName << "[] = {" << std::endl;
5809 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005810 const int WORDS_PER_LINE = 8;
5811 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5812 out << "\t";
5813 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5814 const unsigned int word = spirv[i + j];
5815 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5816 if (i + j + 1 < (int)spirv.size()) {
5817 out << ",";
5818 }
5819 }
5820 out << std::endl;
5821 }
Flavio15017db2017-02-15 14:29:33 -08005822 if (varName != nullptr) {
5823 out << "};";
5824 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005825 out.close();
5826}
5827
John Kessenich140f3df2015-06-26 16:58:36 -06005828//
5829// Set up the glslang traversal
5830//
John Kessenich121853f2017-05-31 17:11:16 -06005831void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005832{
Lei Zhang17535f72016-05-04 15:55:59 -04005833 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005834 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005835}
5836
John Kessenich121853f2017-05-31 17:11:16 -06005837void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5838 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005839{
John Kessenich140f3df2015-06-26 16:58:36 -06005840 TIntermNode* root = intermediate.getTreeRoot();
5841
5842 if (root == 0)
5843 return;
5844
John Kessenich121853f2017-05-31 17:11:16 -06005845 glslang::SpvOptions defaultOptions;
5846 if (options == nullptr)
5847 options = &defaultOptions;
5848
John Kessenich140f3df2015-06-26 16:58:36 -06005849 glslang::GetThreadPoolAllocator().push();
5850
John Kessenich121853f2017-05-31 17:11:16 -06005851 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005852 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005853 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005854 it.dumpSpv(spirv);
5855
5856 glslang::GetThreadPoolAllocator().pop();
5857}
5858
5859}; // end namespace glslang