blob: 625dcd7bcff8ed5cb103f0cf0a27df551636b701 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
John Kessenich121853f2017-05-31 17:11:16 -0600104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800125 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600126 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600127 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600128 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
129 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600130 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
131 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
132 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600133 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700134 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600135 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600136 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
137 glslang::TLayoutPacking, const glslang::TQualifier&);
138 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
139 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700140 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700141 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800142 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600143 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700144 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700145 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
147 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100148 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600149
John Kessenich6fccb3c2016-09-19 16:01:41 -0600150 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 void makeFunctions(const glslang::TIntermSequence&);
152 void makeGlobalInitializers(const glslang::TIntermSequence&);
153 void visitFunctions(const glslang::TIntermSequence&);
154 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800155 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600156 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
157 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600158 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
159
qining25262b32016-05-06 17:25:16 -0400160 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
161 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
162 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800163 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800164 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800166 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800167 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800168 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600169 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800170 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
172 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700173 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700175 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400176 spv::Id createSpvConstant(const glslang::TIntermTyped&);
177 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600178 bool isTrivialLeaf(const glslang::TIntermTyped* node);
179 bool isTrivial(const glslang::TIntermTyped* node);
180 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800181 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich121853f2017-05-31 17:11:16 -0600183 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600184 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600185 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700186 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600187 int sequenceDepth;
188
Lei Zhang17535f72016-05-04 15:55:59 -0400189 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400190
John Kessenich140f3df2015-06-26 16:58:36 -0600191 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
192 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700193 bool inEntryPoint;
194 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700195 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700196 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600197 const glslang::TIntermediate* glslangIntermediate;
198 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800199 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600200
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600202 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600203 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700204 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600205 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600206 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600207};
208
209//
210// Helper functions for translating glslang representations to SPIR-V enumerants.
211//
212
213// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700214spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600215{
John Kessenich66e2faf2016-03-12 18:34:36 -0700216 switch (source) {
217 case glslang::EShSourceGlsl:
218 switch (profile) {
219 case ENoProfile:
220 case ECoreProfile:
221 case ECompatibilityProfile:
222 return spv::SourceLanguageGLSL;
223 case EEsProfile:
224 return spv::SourceLanguageESSL;
225 default:
226 return spv::SourceLanguageUnknown;
227 }
228 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600229 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600230 default:
231 return spv::SourceLanguageUnknown;
232 }
233}
234
235// Translate glslang language (stage) to SPIR-V execution model.
236spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
237{
238 switch (stage) {
239 case EShLangVertex: return spv::ExecutionModelVertex;
240 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
241 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
242 case EShLangGeometry: return spv::ExecutionModelGeometry;
243 case EShLangFragment: return spv::ExecutionModelFragment;
244 case EShLangCompute: return spv::ExecutionModelGLCompute;
245 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600247 return spv::ExecutionModelFragment;
248 }
249}
250
John Kessenich140f3df2015-06-26 16:58:36 -0600251// Translate glslang sampler type to SPIR-V dimensionality.
252spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
253{
254 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700255 case glslang::Esd1D: return spv::Dim1D;
256 case glslang::Esd2D: return spv::Dim2D;
257 case glslang::Esd3D: return spv::Dim3D;
258 case glslang::EsdCube: return spv::DimCube;
259 case glslang::EsdRect: return spv::DimRect;
260 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700261 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::Dim2D;
265 }
266}
267
John Kessenichf6640762016-08-01 19:44:00 -0600268// Translate glslang precision to SPIR-V precision decorations.
269spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600270{
John Kessenichf6640762016-08-01 19:44:00 -0600271 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700272 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600273 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::NoPrecision;
276 }
277}
278
John Kessenichf6640762016-08-01 19:44:00 -0600279// Translate glslang type to SPIR-V precision decorations.
280spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
281{
282 return TranslatePrecisionDecoration(type.getQualifier().precision);
283}
284
John Kessenich140f3df2015-06-26 16:58:36 -0600285// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600286spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600287{
288 if (type.getBasicType() == glslang::EbtBlock) {
289 switch (type.getQualifier().storage) {
290 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600291 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 case glslang::EvqVaryingIn: return spv::DecorationBlock;
293 case glslang::EvqVaryingOut: return spv::DecorationBlock;
294 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700295 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600296 break;
297 }
298 }
299
John Kessenich4016e382016-07-15 11:53:56 -0600300 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600301}
302
Rex Xu1da878f2016-02-21 20:59:01 +0800303// Translate glslang type to SPIR-V memory decorations.
304void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
305{
306 if (qualifier.coherent)
307 memory.push_back(spv::DecorationCoherent);
308 if (qualifier.volatil)
309 memory.push_back(spv::DecorationVolatile);
310 if (qualifier.restrict)
311 memory.push_back(spv::DecorationRestrict);
312 if (qualifier.readonly)
313 memory.push_back(spv::DecorationNonWritable);
314 if (qualifier.writeonly)
315 memory.push_back(spv::DecorationNonReadable);
316}
317
John Kessenich140f3df2015-06-26 16:58:36 -0600318// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700319spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600320{
321 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700322 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600323 case glslang::ElmRowMajor:
324 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700327 default:
328 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600329 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600330 }
331 } else {
332 switch (type.getBasicType()) {
333 default:
John Kessenich4016e382016-07-15 11:53:56 -0600334 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 break;
336 case glslang::EbtBlock:
337 switch (type.getQualifier().storage) {
338 case glslang::EvqUniform:
339 case glslang::EvqBuffer:
340 switch (type.getQualifier().layoutPacking) {
341 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
343 default:
John Kessenich4016e382016-07-15 11:53:56 -0600344 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600345 }
346 case glslang::EvqVaryingIn:
347 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700348 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600349 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600350 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700351 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 }
355 }
356}
357
358// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600359// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700360// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800361spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600362{
Rex Xubbceed72016-05-21 09:40:44 +0800363 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700364 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600365 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800366 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700367 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700368 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600369 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800370#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800371 else if (qualifier.explicitInterp) {
372 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800373 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800374 }
Rex Xu9d93a232016-05-05 12:30:44 +0800375#endif
Rex Xubbceed72016-05-21 09:40:44 +0800376 else
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378}
379
380// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600381// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800382// should be applied.
383spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
384{
385 if (qualifier.patch)
386 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700387 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600388 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700389 else if (qualifier.sample) {
390 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700392 } else
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600394}
395
John Kessenich92187592016-02-01 13:45:25 -0700396// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600398{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationInvariant;
401 else
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600403}
404
qining9220dbb2016-05-04 17:34:38 -0400405// If glslang type is noContraction, return SPIR-V NoContraction decoration.
406spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
407{
408 if (qualifier.noContraction)
409 return spv::DecorationNoContraction;
410 else
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400412}
413
David Netoa901ffe2016-06-08 14:11:40 +0100414// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
415// associated capabilities when required. For some built-in variables, a capability
416// is generated only when using the variable in an executable instruction, but not when
417// just declaring a struct member variable with it. This is true for PointSize,
418// ClipDistance, and CullDistance.
419spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600420{
421 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700422 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600423 // Defer adding the capability until the built-in is actually used.
424 if (! memberDeclaration) {
425 switch (glslangIntermediate->getStage()) {
426 case EShLangGeometry:
427 builder.addCapability(spv::CapabilityGeometryPointSize);
428 break;
429 case EShLangTessControl:
430 case EShLangTessEvaluation:
431 builder.addCapability(spv::CapabilityTessellationPointSize);
432 break;
433 default:
434 break;
435 }
John Kessenich92187592016-02-01 13:45:25 -0700436 }
437 return spv::BuiltInPointSize;
438
John Kessenichebb50532016-05-16 19:22:05 -0600439 // These *Distance capabilities logically belong here, but if the member is declared and
440 // then never used, consumers of SPIR-V prefer the capability not be declared.
441 // They are now generated when used, rather than here when declared.
442 // Potentially, the specification should be more clear what the minimum
443 // use needed is to trigger the capability.
444 //
John Kessenich92187592016-02-01 13:45:25 -0700445 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100446 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800447 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700448 return spv::BuiltInClipDistance;
449
450 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100451 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800452 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700453 return spv::BuiltInCullDistance;
454
455 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600456 builder.addCapability(spv::CapabilityMultiViewport);
457 if (glslangIntermediate->getStage() == EShLangVertex ||
458 glslangIntermediate->getStage() == EShLangTessControl ||
459 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800460
John Kessenichba6a3c22017-09-13 13:22:50 -0600461 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
462 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800463 }
John Kessenich92187592016-02-01 13:45:25 -0700464 return spv::BuiltInViewportIndex;
465
John Kessenich5e801132016-02-15 11:09:46 -0700466 case glslang::EbvSampleId:
467 builder.addCapability(spv::CapabilitySampleRateShading);
468 return spv::BuiltInSampleId;
469
470 case glslang::EbvSamplePosition:
471 builder.addCapability(spv::CapabilitySampleRateShading);
472 return spv::BuiltInSamplePosition;
473
474 case glslang::EbvSampleMask:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSampleMask;
477
John Kessenich78a45572016-07-08 14:05:15 -0600478 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600479 builder.addCapability(spv::CapabilityGeometry);
480 if (glslangIntermediate->getStage() == EShLangVertex ||
481 glslangIntermediate->getStage() == EShLangTessControl ||
482 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800483
John Kessenichba6a3c22017-09-13 13:22:50 -0600484 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
485 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 }
John Kessenich78a45572016-07-08 14:05:15 -0600487 return spv::BuiltInLayer;
488
John Kessenich140f3df2015-06-26 16:58:36 -0600489 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600490 case glslang::EbvVertexId: return spv::BuiltInVertexId;
491 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700492 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
493 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800494
John Kessenichda581a22015-10-14 14:10:30 -0600495 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800496 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
497 builder.addCapability(spv::CapabilityDrawParameters);
498 return spv::BuiltInBaseVertex;
499
John Kessenichda581a22015-10-14 14:10:30 -0600500 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800501 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
502 builder.addCapability(spv::CapabilityDrawParameters);
503 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200504
John Kessenichda581a22015-10-14 14:10:30 -0600505 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800506 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
507 builder.addCapability(spv::CapabilityDrawParameters);
508 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200509
510 case glslang::EbvPrimitiveId:
511 if (glslangIntermediate->getStage() == EShLangFragment)
512 builder.addCapability(spv::CapabilityGeometry);
513 return spv::BuiltInPrimitiveId;
514
Rex Xu37cdcee2017-06-29 17:46:34 +0800515 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800516 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
517 builder.addCapability(spv::CapabilityStencilExportEXT);
518 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800519
John Kessenich140f3df2015-06-26 16:58:36 -0600520 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600521 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
522 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
523 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
524 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
525 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
526 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
527 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
529 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
530 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
531 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
532 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
533 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
534 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
535 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800536
Rex Xu574ab042016-04-14 16:53:07 +0800537 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800538 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800539 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
540 return spv::BuiltInSubgroupSize;
541
Rex Xu574ab042016-04-14 16:53:07 +0800542 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800543 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800544 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
545 return spv::BuiltInSubgroupLocalInvocationId;
546
Rex Xu574ab042016-04-14 16:53:07 +0800547 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800548 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
549 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
550 return spv::BuiltInSubgroupEqMaskKHR;
551
Rex Xu574ab042016-04-14 16:53:07 +0800552 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800553 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
554 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
555 return spv::BuiltInSubgroupGeMaskKHR;
556
Rex Xu574ab042016-04-14 16:53:07 +0800557 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800558 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
559 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
560 return spv::BuiltInSubgroupGtMaskKHR;
561
Rex Xu574ab042016-04-14 16:53:07 +0800562 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800563 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
564 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
565 return spv::BuiltInSubgroupLeMaskKHR;
566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupLtMaskKHR;
571
Rex Xu9d93a232016-05-05 12:30:44 +0800572#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800573 case glslang::EbvBaryCoordNoPersp:
574 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
575 return spv::BuiltInBaryCoordNoPerspAMD;
576
577 case glslang::EbvBaryCoordNoPerspCentroid:
578 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
579 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
580
581 case glslang::EbvBaryCoordNoPerspSample:
582 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
583 return spv::BuiltInBaryCoordNoPerspSampleAMD;
584
585 case glslang::EbvBaryCoordSmooth:
586 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
587 return spv::BuiltInBaryCoordSmoothAMD;
588
589 case glslang::EbvBaryCoordSmoothCentroid:
590 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
591 return spv::BuiltInBaryCoordSmoothCentroidAMD;
592
593 case glslang::EbvBaryCoordSmoothSample:
594 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
595 return spv::BuiltInBaryCoordSmoothSampleAMD;
596
597 case glslang::EbvBaryCoordPullModel:
598 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
599 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800600#endif
chaoc771d89f2017-01-13 01:10:53 -0800601
John Kessenich6c8aaac2017-02-27 01:20:51 -0700602 case glslang::EbvDeviceIndex:
603 builder.addExtension(spv::E_SPV_KHR_device_group);
604 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700605 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700606
607 case glslang::EbvViewIndex:
608 builder.addExtension(spv::E_SPV_KHR_multiview);
609 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700610 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700611
chaoc771d89f2017-01-13 01:10:53 -0800612#ifdef NV_EXTENSIONS
613 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800614 if (!memberDeclaration) {
615 builder.addExtension(spv::E_SPV_NV_viewport_array2);
616 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
617 }
chaoc771d89f2017-01-13 01:10:53 -0800618 return spv::BuiltInViewportMaskNV;
619 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800620 if (!memberDeclaration) {
621 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
622 builder.addCapability(spv::CapabilityShaderStereoViewNV);
623 }
chaoc771d89f2017-01-13 01:10:53 -0800624 return spv::BuiltInSecondaryPositionNV;
625 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800626 if (!memberDeclaration) {
627 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
628 builder.addCapability(spv::CapabilityShaderStereoViewNV);
629 }
chaoc771d89f2017-01-13 01:10:53 -0800630 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800631 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800632 if (!memberDeclaration) {
633 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
634 builder.addCapability(spv::CapabilityPerViewAttributesNV);
635 }
chaocdf3956c2017-02-14 14:52:34 -0800636 return spv::BuiltInPositionPerViewNV;
637 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800638 if (!memberDeclaration) {
639 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
640 builder.addCapability(spv::CapabilityPerViewAttributesNV);
641 }
chaocdf3956c2017-02-14 14:52:34 -0800642 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800643#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800644 default:
645 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600646 }
647}
648
Rex Xufc618912015-09-09 16:42:49 +0800649// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700650spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800651{
652 assert(type.getBasicType() == glslang::EbtSampler);
653
John Kessenich5d0fa972016-02-15 11:57:00 -0700654 // Check for capabilities
655 switch (type.getQualifier().layoutFormat) {
656 case glslang::ElfRg32f:
657 case glslang::ElfRg16f:
658 case glslang::ElfR11fG11fB10f:
659 case glslang::ElfR16f:
660 case glslang::ElfRgba16:
661 case glslang::ElfRgb10A2:
662 case glslang::ElfRg16:
663 case glslang::ElfRg8:
664 case glslang::ElfR16:
665 case glslang::ElfR8:
666 case glslang::ElfRgba16Snorm:
667 case glslang::ElfRg16Snorm:
668 case glslang::ElfRg8Snorm:
669 case glslang::ElfR16Snorm:
670 case glslang::ElfR8Snorm:
671
672 case glslang::ElfRg32i:
673 case glslang::ElfRg16i:
674 case glslang::ElfRg8i:
675 case glslang::ElfR16i:
676 case glslang::ElfR8i:
677
678 case glslang::ElfRgb10a2ui:
679 case glslang::ElfRg32ui:
680 case glslang::ElfRg16ui:
681 case glslang::ElfRg8ui:
682 case glslang::ElfR16ui:
683 case glslang::ElfR8ui:
684 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
685 break;
686
687 default:
688 break;
689 }
690
691 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800692 switch (type.getQualifier().layoutFormat) {
693 case glslang::ElfNone: return spv::ImageFormatUnknown;
694 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
695 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
696 case glslang::ElfR32f: return spv::ImageFormatR32f;
697 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
698 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
699 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
700 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
701 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
702 case glslang::ElfR16f: return spv::ImageFormatR16f;
703 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
704 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
705 case glslang::ElfRg16: return spv::ImageFormatRg16;
706 case glslang::ElfRg8: return spv::ImageFormatRg8;
707 case glslang::ElfR16: return spv::ImageFormatR16;
708 case glslang::ElfR8: return spv::ImageFormatR8;
709 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
710 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
711 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
712 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
713 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
714 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
715 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
716 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
717 case glslang::ElfR32i: return spv::ImageFormatR32i;
718 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
719 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
720 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
721 case glslang::ElfR16i: return spv::ImageFormatR16i;
722 case glslang::ElfR8i: return spv::ImageFormatR8i;
723 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
724 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
725 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
726 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
727 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
728 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
729 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
730 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
731 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
732 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600733 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800734 }
735}
736
Rex Xu57e65922017-07-04 23:23:40 +0800737spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
738{
739 switch (selectionControl) {
740 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
741 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
742 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
743 default: return spv::SelectionControlMaskNone;
744 }
745}
746
steve-lunargf1709e72017-05-02 20:14:50 -0600747spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
748{
749 switch (loopControl) {
750 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
751 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
752 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
753 // TODO: DependencyInfinite
754 // TODO: DependencyLength
755 default: return spv::LoopControlMaskNone;
756 }
757}
758
John Kessenicha5c5fb62017-05-05 05:09:58 -0600759// Translate glslang type to SPIR-V storage class.
760spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
761{
762 if (type.getQualifier().isPipeInput())
763 return spv::StorageClassInput;
764 else if (type.getQualifier().isPipeOutput())
765 return spv::StorageClassOutput;
766 else if (type.getBasicType() == glslang::EbtAtomicUint)
767 return spv::StorageClassAtomicCounter;
768 else if (type.containsOpaque())
769 return spv::StorageClassUniformConstant;
770 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
771 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
772 return spv::StorageClassStorageBuffer;
773 } else if (type.getQualifier().isUniformOrBuffer()) {
774 if (type.getQualifier().layoutPushConstant)
775 return spv::StorageClassPushConstant;
776 if (type.getBasicType() == glslang::EbtBlock)
777 return spv::StorageClassUniform;
778 else
779 return spv::StorageClassUniformConstant;
780 } else {
781 switch (type.getQualifier().storage) {
782 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
783 case glslang::EvqGlobal: return spv::StorageClassPrivate;
784 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
785 case glslang::EvqTemporary: return spv::StorageClassFunction;
786 default:
787 assert(0);
788 return spv::StorageClassFunction;
789 }
790 }
791}
792
qining25262b32016-05-06 17:25:16 -0400793// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700794// descriptor set.
795bool IsDescriptorResource(const glslang::TType& type)
796{
John Kessenichf7497e22016-03-08 21:36:22 -0700797 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700798 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700799 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700800
801 // non block...
802 // basically samplerXXX/subpass/sampler/texture are all included
803 // if they are the global-scope-class, not the function parameter
804 // (or local, if they ever exist) class.
805 if (type.getBasicType() == glslang::EbtSampler)
806 return type.getQualifier().isUniformOrBuffer();
807
808 // None of the above.
809 return false;
810}
811
John Kesseniche0b6cad2015-12-24 10:30:13 -0700812void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
813{
814 if (child.layoutMatrix == glslang::ElmNone)
815 child.layoutMatrix = parent.layoutMatrix;
816
817 if (parent.invariant)
818 child.invariant = true;
819 if (parent.nopersp)
820 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800821#ifdef AMD_EXTENSIONS
822 if (parent.explicitInterp)
823 child.explicitInterp = true;
824#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700825 if (parent.flat)
826 child.flat = true;
827 if (parent.centroid)
828 child.centroid = true;
829 if (parent.patch)
830 child.patch = true;
831 if (parent.sample)
832 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800833 if (parent.coherent)
834 child.coherent = true;
835 if (parent.volatil)
836 child.volatil = true;
837 if (parent.restrict)
838 child.restrict = true;
839 if (parent.readonly)
840 child.readonly = true;
841 if (parent.writeonly)
842 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700843}
844
John Kessenichf2b7f332016-09-01 17:05:23 -0600845bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700846{
John Kessenich7b9fa252016-01-21 18:56:57 -0700847 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600848 // - struct members might inherit from a struct declaration
849 // (note that non-block structs don't explicitly inherit,
850 // only implicitly, meaning no decoration involved)
851 // - affect decorations on the struct members
852 // (note smooth does not, and expecting something like volatile
853 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700854 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600855 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700856}
857
John Kessenich140f3df2015-06-26 16:58:36 -0600858//
859// Implement the TGlslangToSpvTraverser class.
860//
861
John Kessenich121853f2017-05-31 17:11:16 -0600862TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
863 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
864 : TIntermTraverser(true, false, true),
865 options(options),
866 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600867 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400868 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700869 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600870 glslangIntermediate(glslangIntermediate)
871{
872 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
873
874 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600875 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
876 glslangIntermediate->getVersion());
877
John Kessenich121853f2017-05-31 17:11:16 -0600878 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600879 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600880 builder.setSourceFile(glslangIntermediate->getSourceFile());
881
882 // Set the source shader's text. If for SPV version 1.0, include
883 // a preamble in comments stating the OpModuleProcessed instructions.
884 // Otherwise, emit those as actual instructions.
885 std::string text;
886 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
887 for (int p = 0; p < (int)processes.size(); ++p) {
888 if (glslangIntermediate->getSpv().spv < 0x00010100) {
889 text.append("// OpModuleProcessed ");
890 text.append(processes[p]);
891 text.append("\n");
892 } else
893 builder.addModuleProcessed(processes[p]);
894 }
895 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
896 text.append("#line 1\n");
897 text.append(glslangIntermediate->getSourceText());
898 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600899 }
John Kessenich140f3df2015-06-26 16:58:36 -0600900 stdBuiltins = builder.import("GLSL.std.450");
901 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600902 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
903 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600904
905 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600906 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
907 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600908 builder.addSourceExtension(it->c_str());
909
910 // Add the top-level modes for this shader.
911
John Kessenich92187592016-02-01 13:45:25 -0700912 if (glslangIntermediate->getXfbMode()) {
913 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600914 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700915 }
John Kessenich140f3df2015-06-26 16:58:36 -0600916
917 unsigned int mode;
918 switch (glslangIntermediate->getStage()) {
919 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600920 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600921 break;
922
steve-lunarge7412492017-03-23 11:56:07 -0600923 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600924 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600925 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600926
steve-lunarge7412492017-03-23 11:56:07 -0600927 glslang::TLayoutGeometry primitive;
928
929 if (glslangIntermediate->getStage() == EShLangTessControl) {
930 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
931 primitive = glslangIntermediate->getOutputPrimitive();
932 } else {
933 primitive = glslangIntermediate->getInputPrimitive();
934 }
935
936 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700937 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
938 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
939 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600940 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600941 }
John Kessenich4016e382016-07-15 11:53:56 -0600942 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600943 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
944
John Kesseniche6903322015-10-13 16:29:02 -0600945 switch (glslangIntermediate->getVertexSpacing()) {
946 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
947 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
948 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600949 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600950 }
John Kessenich4016e382016-07-15 11:53:56 -0600951 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600952 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
953
954 switch (glslangIntermediate->getVertexOrder()) {
955 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
956 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600957 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600958 }
John Kessenich4016e382016-07-15 11:53:56 -0600959 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600960 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
961
962 if (glslangIntermediate->getPointMode())
963 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600964 break;
965
966 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600967 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600968 switch (glslangIntermediate->getInputPrimitive()) {
969 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
970 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
971 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700972 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600973 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600974 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600975 }
John Kessenich4016e382016-07-15 11:53:56 -0600976 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600977 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600978
John Kessenich140f3df2015-06-26 16:58:36 -0600979 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
980
981 switch (glslangIntermediate->getOutputPrimitive()) {
982 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
983 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
984 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600985 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600986 }
John Kessenich4016e382016-07-15 11:53:56 -0600987 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600988 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
989 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
990 break;
991
992 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600993 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600994 if (glslangIntermediate->getPixelCenterInteger())
995 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600996
John Kessenich140f3df2015-06-26 16:58:36 -0600997 if (glslangIntermediate->getOriginUpperLeft())
998 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600999 else
1000 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001001
1002 if (glslangIntermediate->getEarlyFragmentTests())
1003 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1004
chaocc1204522017-06-30 17:14:30 -07001005 if (glslangIntermediate->getPostDepthCoverage()) {
1006 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1007 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1008 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1009 }
1010
John Kesseniche6903322015-10-13 16:29:02 -06001011 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001012 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1013 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001014 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001015 }
John Kessenich4016e382016-07-15 11:53:56 -06001016 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001017 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1018
1019 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1020 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001021 break;
1022
1023 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001024 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001025 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1026 glslangIntermediate->getLocalSize(1),
1027 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001028 break;
1029
1030 default:
1031 break;
1032 }
John Kessenich140f3df2015-06-26 16:58:36 -06001033}
1034
John Kessenichfca82622016-11-26 13:23:20 -07001035// Finish creating SPV, after the traversal is complete.
1036void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001037{
John Kessenich517fe7a2016-11-26 13:31:47 -07001038 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001039 builder.setBuildPoint(shaderEntry->getLastBlock());
1040 builder.leaveFunction();
1041 }
1042
John Kessenich7ba63412015-12-20 17:37:07 -07001043 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001044 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1045 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001046
qiningda397332016-03-09 19:54:03 -05001047 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001048}
1049
John Kessenichfca82622016-11-26 13:23:20 -07001050// Write the SPV into 'out'.
1051void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001052{
John Kessenichfca82622016-11-26 13:23:20 -07001053 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001054}
1055
1056//
1057// Implement the traversal functions.
1058//
1059// Return true from interior nodes to have the external traversal
1060// continue on to children. Return false if children were
1061// already processed.
1062//
1063
1064//
qining25262b32016-05-06 17:25:16 -04001065// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001066// - uniform/input reads
1067// - output writes
1068// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1069// - something simple that degenerates into the last bullet
1070//
1071void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1072{
qining75d1d802016-04-06 14:42:01 -04001073 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1074 if (symbol->getType().getQualifier().isSpecConstant())
1075 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1076
John Kessenich140f3df2015-06-26 16:58:36 -06001077 // getSymbolId() will set up all the IO decorations on the first call.
1078 // Formal function parameters were mapped during makeFunctions().
1079 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001080
1081 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1082 if (builder.isPointer(id)) {
1083 spv::StorageClass sc = builder.getStorageClass(id);
1084 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1085 iOSet.insert(id);
1086 }
1087
1088 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001089 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001090 // Prepare to generate code for the access
1091
1092 // L-value chains will be computed left to right. We're on the symbol now,
1093 // which is the left-most part of the access chain, so now is "clear" time,
1094 // followed by setting the base.
1095 builder.clearAccessChain();
1096
1097 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001098 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001099 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001100 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001101 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001102 // These are also pure R-values.
1103 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001104 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001105 builder.setAccessChainRValue(id);
1106 else
1107 builder.setAccessChainLValue(id);
1108 }
1109}
1110
1111bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1112{
John Kesseniche485c7a2017-05-31 18:50:53 -06001113 builder.setLine(node->getLoc().line);
1114
qining40887662016-04-03 22:20:42 -04001115 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1116 if (node->getType().getQualifier().isSpecConstant())
1117 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1118
John Kessenich140f3df2015-06-26 16:58:36 -06001119 // First, handle special cases
1120 switch (node->getOp()) {
1121 case glslang::EOpAssign:
1122 case glslang::EOpAddAssign:
1123 case glslang::EOpSubAssign:
1124 case glslang::EOpMulAssign:
1125 case glslang::EOpVectorTimesMatrixAssign:
1126 case glslang::EOpVectorTimesScalarAssign:
1127 case glslang::EOpMatrixTimesScalarAssign:
1128 case glslang::EOpMatrixTimesMatrixAssign:
1129 case glslang::EOpDivAssign:
1130 case glslang::EOpModAssign:
1131 case glslang::EOpAndAssign:
1132 case glslang::EOpInclusiveOrAssign:
1133 case glslang::EOpExclusiveOrAssign:
1134 case glslang::EOpLeftShiftAssign:
1135 case glslang::EOpRightShiftAssign:
1136 // A bin-op assign "a += b" means the same thing as "a = a + b"
1137 // where a is evaluated before b. For a simple assignment, GLSL
1138 // says to evaluate the left before the right. So, always, left
1139 // node then right node.
1140 {
1141 // get the left l-value, save it away
1142 builder.clearAccessChain();
1143 node->getLeft()->traverse(this);
1144 spv::Builder::AccessChain lValue = builder.getAccessChain();
1145
1146 // evaluate the right
1147 builder.clearAccessChain();
1148 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001149 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001150
1151 if (node->getOp() != glslang::EOpAssign) {
1152 // the left is also an r-value
1153 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001154 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001155
1156 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001157 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001158 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001159 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1160 node->getType().getBasicType());
1161
1162 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001163 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001164 }
1165
1166 // store the result
1167 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001168 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001169
1170 // assignments are expressions having an rValue after they are evaluated...
1171 builder.clearAccessChain();
1172 builder.setAccessChainRValue(rValue);
1173 }
1174 return false;
1175 case glslang::EOpIndexDirect:
1176 case glslang::EOpIndexDirectStruct:
1177 {
1178 // Get the left part of the access chain.
1179 node->getLeft()->traverse(this);
1180
1181 // Add the next element in the chain
1182
David Netoa901ffe2016-06-08 14:11:40 +01001183 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001184 if (! node->getLeft()->getType().isArray() &&
1185 node->getLeft()->getType().isVector() &&
1186 node->getOp() == glslang::EOpIndexDirect) {
1187 // This is essentially a hard-coded vector swizzle of size 1,
1188 // so short circuit the access-chain stuff with a swizzle.
1189 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001190 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001191 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001192 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001193 int spvIndex = glslangIndex;
1194 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1195 node->getOp() == glslang::EOpIndexDirectStruct)
1196 {
1197 // This may be, e.g., an anonymous block-member selection, which generally need
1198 // index remapping due to hidden members in anonymous blocks.
1199 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1200 assert(remapper.size() > 0);
1201 spvIndex = remapper[glslangIndex];
1202 }
John Kessenichebb50532016-05-16 19:22:05 -06001203
David Netoa901ffe2016-06-08 14:11:40 +01001204 // normal case for indexing array or structure or block
1205 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1206
1207 // Add capabilities here for accessing PointSize and clip/cull distance.
1208 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001209 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001210 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001211 }
1212 }
1213 return false;
1214 case glslang::EOpIndexIndirect:
1215 {
1216 // Structure or array or vector indirection.
1217 // Will use native SPIR-V access-chain for struct and array indirection;
1218 // matrices are arrays of vectors, so will also work for a matrix.
1219 // Will use the access chain's 'component' for variable index into a vector.
1220
1221 // This adapter is building access chains left to right.
1222 // Set up the access chain to the left.
1223 node->getLeft()->traverse(this);
1224
1225 // save it so that computing the right side doesn't trash it
1226 spv::Builder::AccessChain partial = builder.getAccessChain();
1227
1228 // compute the next index in the chain
1229 builder.clearAccessChain();
1230 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001231 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001232
1233 // restore the saved access chain
1234 builder.setAccessChain(partial);
1235
1236 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001237 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001238 else
John Kessenichfa668da2015-09-13 14:46:30 -06001239 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001240 }
1241 return false;
1242 case glslang::EOpVectorSwizzle:
1243 {
1244 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001245 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001246 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001247 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001248 }
1249 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001250 case glslang::EOpMatrixSwizzle:
1251 logger->missingFunctionality("matrix swizzle");
1252 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001253 case glslang::EOpLogicalOr:
1254 case glslang::EOpLogicalAnd:
1255 {
1256
1257 // These may require short circuiting, but can sometimes be done as straight
1258 // binary operations. The right operand must be short circuited if it has
1259 // side effects, and should probably be if it is complex.
1260 if (isTrivial(node->getRight()->getAsTyped()))
1261 break; // handle below as a normal binary operation
1262 // otherwise, we need to do dynamic short circuiting on the right operand
1263 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1264 builder.clearAccessChain();
1265 builder.setAccessChainRValue(result);
1266 }
1267 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001268 default:
1269 break;
1270 }
1271
1272 // Assume generic binary op...
1273
John Kessenich32cfd492016-02-02 12:37:46 -07001274 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001275 builder.clearAccessChain();
1276 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001277 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001278
John Kessenich32cfd492016-02-02 12:37:46 -07001279 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001280 builder.clearAccessChain();
1281 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001282 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001283
John Kessenich32cfd492016-02-02 12:37:46 -07001284 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001285 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001286 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001287 convertGlslangToSpvType(node->getType()), left, right,
1288 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001289
John Kessenich50e57562015-12-21 21:21:11 -07001290 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001291 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001292 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001293 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001294 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001295 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001296 return false;
1297 }
John Kessenich140f3df2015-06-26 16:58:36 -06001298}
1299
1300bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1301{
John Kesseniche485c7a2017-05-31 18:50:53 -06001302 builder.setLine(node->getLoc().line);
1303
qining40887662016-04-03 22:20:42 -04001304 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1305 if (node->getType().getQualifier().isSpecConstant())
1306 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1307
John Kessenichfc51d282015-08-19 13:34:18 -06001308 spv::Id result = spv::NoResult;
1309
1310 // try texturing first
1311 result = createImageTextureFunctionCall(node);
1312 if (result != spv::NoResult) {
1313 builder.clearAccessChain();
1314 builder.setAccessChainRValue(result);
1315
1316 return false; // done with this node
1317 }
1318
1319 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001320
1321 if (node->getOp() == glslang::EOpArrayLength) {
1322 // Quite special; won't want to evaluate the operand.
1323
1324 // Normal .length() would have been constant folded by the front-end.
1325 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001326 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001327 assert(node->getOperand()->getType().isRuntimeSizedArray());
1328 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1329 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001330 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1331 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001332
1333 builder.clearAccessChain();
1334 builder.setAccessChainRValue(length);
1335
1336 return false;
1337 }
1338
John Kessenichfc51d282015-08-19 13:34:18 -06001339 // Start by evaluating the operand
1340
John Kessenich8c8505c2016-07-26 12:50:38 -06001341 // Does it need a swizzle inversion? If so, evaluation is inverted;
1342 // operate first on the swizzle base, then apply the swizzle.
1343 spv::Id invertedType = spv::NoType;
1344 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1345 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1346 invertedType = getInvertedSwizzleType(*node->getOperand());
1347
John Kessenich140f3df2015-06-26 16:58:36 -06001348 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001349 if (invertedType != spv::NoType)
1350 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1351 else
1352 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001353
Rex Xufc618912015-09-09 16:42:49 +08001354 spv::Id operand = spv::NoResult;
1355
1356 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1357 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001358 node->getOp() == glslang::EOpAtomicCounter ||
1359 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001360 operand = builder.accessChainGetLValue(); // Special case l-value operands
1361 else
John Kessenich32cfd492016-02-02 12:37:46 -07001362 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001363
John Kessenichf6640762016-08-01 19:44:00 -06001364 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001365 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001366
1367 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001368 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001369 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001370
1371 // if not, then possibly an operation
1372 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001373 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001374
1375 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001376 if (invertedType)
1377 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1378
John Kessenich140f3df2015-06-26 16:58:36 -06001379 builder.clearAccessChain();
1380 builder.setAccessChainRValue(result);
1381
1382 return false; // done with this node
1383 }
1384
1385 // it must be a special case, check...
1386 switch (node->getOp()) {
1387 case glslang::EOpPostIncrement:
1388 case glslang::EOpPostDecrement:
1389 case glslang::EOpPreIncrement:
1390 case glslang::EOpPreDecrement:
1391 {
1392 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001393 spv::Id one = 0;
1394 if (node->getBasicType() == glslang::EbtFloat)
1395 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001396 else if (node->getBasicType() == glslang::EbtDouble)
1397 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001398#ifdef AMD_EXTENSIONS
1399 else if (node->getBasicType() == glslang::EbtFloat16)
1400 one = builder.makeFloat16Constant(1.0F);
1401#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001402 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1403 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001404#ifdef AMD_EXTENSIONS
1405 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1406 one = builder.makeInt16Constant(1);
1407#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001408 else
1409 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001410 glslang::TOperator op;
1411 if (node->getOp() == glslang::EOpPreIncrement ||
1412 node->getOp() == glslang::EOpPostIncrement)
1413 op = glslang::EOpAdd;
1414 else
1415 op = glslang::EOpSub;
1416
John Kessenichf6640762016-08-01 19:44:00 -06001417 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001418 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001419 convertGlslangToSpvType(node->getType()), operand, one,
1420 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001421 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001422
1423 // The result of operation is always stored, but conditionally the
1424 // consumed result. The consumed result is always an r-value.
1425 builder.accessChainStore(result);
1426 builder.clearAccessChain();
1427 if (node->getOp() == glslang::EOpPreIncrement ||
1428 node->getOp() == glslang::EOpPreDecrement)
1429 builder.setAccessChainRValue(result);
1430 else
1431 builder.setAccessChainRValue(operand);
1432 }
1433
1434 return false;
1435
1436 case glslang::EOpEmitStreamVertex:
1437 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1438 return false;
1439 case glslang::EOpEndStreamPrimitive:
1440 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1441 return false;
1442
1443 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001444 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001445 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001446 }
John Kessenich140f3df2015-06-26 16:58:36 -06001447}
1448
1449bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1450{
qining27e04a02016-04-14 16:40:20 -04001451 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1452 if (node->getType().getQualifier().isSpecConstant())
1453 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1454
John Kessenichfc51d282015-08-19 13:34:18 -06001455 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001456 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1457 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001458
1459 // try texturing
1460 result = createImageTextureFunctionCall(node);
1461 if (result != spv::NoResult) {
1462 builder.clearAccessChain();
1463 builder.setAccessChainRValue(result);
1464
1465 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001466#ifdef AMD_EXTENSIONS
1467 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1468#else
John Kessenich56bab042015-09-16 10:54:31 -06001469 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001470#endif
Rex Xufc618912015-09-09 16:42:49 +08001471 // "imageStore" is a special case, which has no result
1472 return false;
1473 }
John Kessenichfc51d282015-08-19 13:34:18 -06001474
John Kessenich140f3df2015-06-26 16:58:36 -06001475 glslang::TOperator binOp = glslang::EOpNull;
1476 bool reduceComparison = true;
1477 bool isMatrix = false;
1478 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001479 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001480
1481 assert(node->getOp());
1482
John Kessenichf6640762016-08-01 19:44:00 -06001483 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001484
1485 switch (node->getOp()) {
1486 case glslang::EOpSequence:
1487 {
1488 if (preVisit)
1489 ++sequenceDepth;
1490 else
1491 --sequenceDepth;
1492
1493 if (sequenceDepth == 1) {
1494 // If this is the parent node of all the functions, we want to see them
1495 // early, so all call points have actual SPIR-V functions to reference.
1496 // In all cases, still let the traverser visit the children for us.
1497 makeFunctions(node->getAsAggregate()->getSequence());
1498
John Kessenich6fccb3c2016-09-19 16:01:41 -06001499 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001500 // anything else gets there, so visit out of order, doing them all now.
1501 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1502
John Kessenich6a60c2f2016-12-08 21:01:59 -07001503 // 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 -06001504 // so do them manually.
1505 visitFunctions(node->getAsAggregate()->getSequence());
1506
1507 return false;
1508 }
1509
1510 return true;
1511 }
1512 case glslang::EOpLinkerObjects:
1513 {
1514 if (visit == glslang::EvPreVisit)
1515 linkageOnly = true;
1516 else
1517 linkageOnly = false;
1518
1519 return true;
1520 }
1521 case glslang::EOpComma:
1522 {
1523 // processing from left to right naturally leaves the right-most
1524 // lying around in the access chain
1525 glslang::TIntermSequence& glslangOperands = node->getSequence();
1526 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1527 glslangOperands[i]->traverse(this);
1528
1529 return false;
1530 }
1531 case glslang::EOpFunction:
1532 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001533 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001534 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001535 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001536 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001537 } else {
1538 handleFunctionEntry(node);
1539 }
1540 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001541 if (inEntryPoint)
1542 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001543 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001544 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001545 }
1546
1547 return true;
1548 case glslang::EOpParameters:
1549 // Parameters will have been consumed by EOpFunction processing, but not
1550 // the body, so we still visited the function node's children, making this
1551 // child redundant.
1552 return false;
1553 case glslang::EOpFunctionCall:
1554 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001555 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001556 if (node->isUserDefined())
1557 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001558 // 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 -07001559 if (result) {
1560 builder.clearAccessChain();
1561 builder.setAccessChainRValue(result);
1562 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001563 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001564
1565 return false;
1566 }
1567 case glslang::EOpConstructMat2x2:
1568 case glslang::EOpConstructMat2x3:
1569 case glslang::EOpConstructMat2x4:
1570 case glslang::EOpConstructMat3x2:
1571 case glslang::EOpConstructMat3x3:
1572 case glslang::EOpConstructMat3x4:
1573 case glslang::EOpConstructMat4x2:
1574 case glslang::EOpConstructMat4x3:
1575 case glslang::EOpConstructMat4x4:
1576 case glslang::EOpConstructDMat2x2:
1577 case glslang::EOpConstructDMat2x3:
1578 case glslang::EOpConstructDMat2x4:
1579 case glslang::EOpConstructDMat3x2:
1580 case glslang::EOpConstructDMat3x3:
1581 case glslang::EOpConstructDMat3x4:
1582 case glslang::EOpConstructDMat4x2:
1583 case glslang::EOpConstructDMat4x3:
1584 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001585 case glslang::EOpConstructIMat2x2:
1586 case glslang::EOpConstructIMat2x3:
1587 case glslang::EOpConstructIMat2x4:
1588 case glslang::EOpConstructIMat3x2:
1589 case glslang::EOpConstructIMat3x3:
1590 case glslang::EOpConstructIMat3x4:
1591 case glslang::EOpConstructIMat4x2:
1592 case glslang::EOpConstructIMat4x3:
1593 case glslang::EOpConstructIMat4x4:
1594 case glslang::EOpConstructUMat2x2:
1595 case glslang::EOpConstructUMat2x3:
1596 case glslang::EOpConstructUMat2x4:
1597 case glslang::EOpConstructUMat3x2:
1598 case glslang::EOpConstructUMat3x3:
1599 case glslang::EOpConstructUMat3x4:
1600 case glslang::EOpConstructUMat4x2:
1601 case glslang::EOpConstructUMat4x3:
1602 case glslang::EOpConstructUMat4x4:
1603 case glslang::EOpConstructBMat2x2:
1604 case glslang::EOpConstructBMat2x3:
1605 case glslang::EOpConstructBMat2x4:
1606 case glslang::EOpConstructBMat3x2:
1607 case glslang::EOpConstructBMat3x3:
1608 case glslang::EOpConstructBMat3x4:
1609 case glslang::EOpConstructBMat4x2:
1610 case glslang::EOpConstructBMat4x3:
1611 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001612#ifdef AMD_EXTENSIONS
1613 case glslang::EOpConstructF16Mat2x2:
1614 case glslang::EOpConstructF16Mat2x3:
1615 case glslang::EOpConstructF16Mat2x4:
1616 case glslang::EOpConstructF16Mat3x2:
1617 case glslang::EOpConstructF16Mat3x3:
1618 case glslang::EOpConstructF16Mat3x4:
1619 case glslang::EOpConstructF16Mat4x2:
1620 case glslang::EOpConstructF16Mat4x3:
1621 case glslang::EOpConstructF16Mat4x4:
1622#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001623 isMatrix = true;
1624 // fall through
1625 case glslang::EOpConstructFloat:
1626 case glslang::EOpConstructVec2:
1627 case glslang::EOpConstructVec3:
1628 case glslang::EOpConstructVec4:
1629 case glslang::EOpConstructDouble:
1630 case glslang::EOpConstructDVec2:
1631 case glslang::EOpConstructDVec3:
1632 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001633#ifdef AMD_EXTENSIONS
1634 case glslang::EOpConstructFloat16:
1635 case glslang::EOpConstructF16Vec2:
1636 case glslang::EOpConstructF16Vec3:
1637 case glslang::EOpConstructF16Vec4:
1638#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001639 case glslang::EOpConstructBool:
1640 case glslang::EOpConstructBVec2:
1641 case glslang::EOpConstructBVec3:
1642 case glslang::EOpConstructBVec4:
1643 case glslang::EOpConstructInt:
1644 case glslang::EOpConstructIVec2:
1645 case glslang::EOpConstructIVec3:
1646 case glslang::EOpConstructIVec4:
1647 case glslang::EOpConstructUint:
1648 case glslang::EOpConstructUVec2:
1649 case glslang::EOpConstructUVec3:
1650 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001651 case glslang::EOpConstructInt64:
1652 case glslang::EOpConstructI64Vec2:
1653 case glslang::EOpConstructI64Vec3:
1654 case glslang::EOpConstructI64Vec4:
1655 case glslang::EOpConstructUint64:
1656 case glslang::EOpConstructU64Vec2:
1657 case glslang::EOpConstructU64Vec3:
1658 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001659#ifdef AMD_EXTENSIONS
1660 case glslang::EOpConstructInt16:
1661 case glslang::EOpConstructI16Vec2:
1662 case glslang::EOpConstructI16Vec3:
1663 case glslang::EOpConstructI16Vec4:
1664 case glslang::EOpConstructUint16:
1665 case glslang::EOpConstructU16Vec2:
1666 case glslang::EOpConstructU16Vec3:
1667 case glslang::EOpConstructU16Vec4:
1668#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001669 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001670 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001671 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001672 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001673 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001674 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001676 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001677 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001678 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001679 std::vector<spv::Id> constituents;
1680 for (int c = 0; c < (int)arguments.size(); ++c)
1681 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001682 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001683 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001684 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001685 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001686 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001687
1688 builder.clearAccessChain();
1689 builder.setAccessChainRValue(constructed);
1690
1691 return false;
1692 }
1693
1694 // These six are component-wise compares with component-wise results.
1695 // Forward on to createBinaryOperation(), requesting a vector result.
1696 case glslang::EOpLessThan:
1697 case glslang::EOpGreaterThan:
1698 case glslang::EOpLessThanEqual:
1699 case glslang::EOpGreaterThanEqual:
1700 case glslang::EOpVectorEqual:
1701 case glslang::EOpVectorNotEqual:
1702 {
1703 // Map the operation to a binary
1704 binOp = node->getOp();
1705 reduceComparison = false;
1706 switch (node->getOp()) {
1707 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1708 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1709 default: binOp = node->getOp(); break;
1710 }
1711
1712 break;
1713 }
1714 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001715 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001716 binOp = glslang::EOpMul;
1717 break;
1718 case glslang::EOpOuterProduct:
1719 // two vectors multiplied to make a matrix
1720 binOp = glslang::EOpOuterProduct;
1721 break;
1722 case glslang::EOpDot:
1723 {
qining25262b32016-05-06 17:25:16 -04001724 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001725 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001726 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001727 binOp = glslang::EOpMul;
1728 break;
1729 }
1730 case glslang::EOpMod:
1731 // when an aggregate, this is the floating-point mod built-in function,
1732 // which can be emitted by the one in createBinaryOperation()
1733 binOp = glslang::EOpMod;
1734 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001735 case glslang::EOpEmitVertex:
1736 case glslang::EOpEndPrimitive:
1737 case glslang::EOpBarrier:
1738 case glslang::EOpMemoryBarrier:
1739 case glslang::EOpMemoryBarrierAtomicCounter:
1740 case glslang::EOpMemoryBarrierBuffer:
1741 case glslang::EOpMemoryBarrierImage:
1742 case glslang::EOpMemoryBarrierShared:
1743 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001744 case glslang::EOpAllMemoryBarrierWithGroupSync:
1745 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1746 case glslang::EOpWorkgroupMemoryBarrier:
1747 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001748 noReturnValue = true;
1749 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1750 break;
1751
John Kessenich426394d2015-07-23 10:22:48 -06001752 case glslang::EOpAtomicAdd:
1753 case glslang::EOpAtomicMin:
1754 case glslang::EOpAtomicMax:
1755 case glslang::EOpAtomicAnd:
1756 case glslang::EOpAtomicOr:
1757 case glslang::EOpAtomicXor:
1758 case glslang::EOpAtomicExchange:
1759 case glslang::EOpAtomicCompSwap:
1760 atomic = true;
1761 break;
1762
John Kessenich0d0c6d32017-07-23 16:08:26 -06001763 case glslang::EOpAtomicCounterAdd:
1764 case glslang::EOpAtomicCounterSubtract:
1765 case glslang::EOpAtomicCounterMin:
1766 case glslang::EOpAtomicCounterMax:
1767 case glslang::EOpAtomicCounterAnd:
1768 case glslang::EOpAtomicCounterOr:
1769 case glslang::EOpAtomicCounterXor:
1770 case glslang::EOpAtomicCounterExchange:
1771 case glslang::EOpAtomicCounterCompSwap:
1772 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1773 builder.addCapability(spv::CapabilityAtomicStorageOps);
1774 atomic = true;
1775 break;
1776
John Kessenich140f3df2015-06-26 16:58:36 -06001777 default:
1778 break;
1779 }
1780
1781 //
1782 // See if it maps to a regular operation.
1783 //
John Kessenich140f3df2015-06-26 16:58:36 -06001784 if (binOp != glslang::EOpNull) {
1785 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1786 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1787 assert(left && right);
1788
1789 builder.clearAccessChain();
1790 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001791 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001792
1793 builder.clearAccessChain();
1794 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001795 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001796
John Kesseniche485c7a2017-05-31 18:50:53 -06001797 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001798 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001799 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001800 left->getType().getBasicType(), reduceComparison);
1801
1802 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001803 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001804 builder.clearAccessChain();
1805 builder.setAccessChainRValue(result);
1806
1807 return false;
1808 }
1809
John Kessenich426394d2015-07-23 10:22:48 -06001810 //
1811 // Create the list of operands.
1812 //
John Kessenich140f3df2015-06-26 16:58:36 -06001813 glslang::TIntermSequence& glslangOperands = node->getSequence();
1814 std::vector<spv::Id> operands;
1815 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001816 // special case l-value operands; there are just a few
1817 bool lvalue = false;
1818 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001819 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001820 case glslang::EOpModf:
1821 if (arg == 1)
1822 lvalue = true;
1823 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001824 case glslang::EOpInterpolateAtSample:
1825 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001826#ifdef AMD_EXTENSIONS
1827 case glslang::EOpInterpolateAtVertex:
1828#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001829 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001830 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001831
1832 // Does it need a swizzle inversion? If so, evaluation is inverted;
1833 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001834 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001835 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1836 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1837 }
Rex Xu7a26c172015-12-08 17:12:09 +08001838 break;
Rex Xud4782c12015-09-06 16:30:11 +08001839 case glslang::EOpAtomicAdd:
1840 case glslang::EOpAtomicMin:
1841 case glslang::EOpAtomicMax:
1842 case glslang::EOpAtomicAnd:
1843 case glslang::EOpAtomicOr:
1844 case glslang::EOpAtomicXor:
1845 case glslang::EOpAtomicExchange:
1846 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001847 case glslang::EOpAtomicCounterAdd:
1848 case glslang::EOpAtomicCounterSubtract:
1849 case glslang::EOpAtomicCounterMin:
1850 case glslang::EOpAtomicCounterMax:
1851 case glslang::EOpAtomicCounterAnd:
1852 case glslang::EOpAtomicCounterOr:
1853 case glslang::EOpAtomicCounterXor:
1854 case glslang::EOpAtomicCounterExchange:
1855 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001856 if (arg == 0)
1857 lvalue = true;
1858 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001859 case glslang::EOpAddCarry:
1860 case glslang::EOpSubBorrow:
1861 if (arg == 2)
1862 lvalue = true;
1863 break;
1864 case glslang::EOpUMulExtended:
1865 case glslang::EOpIMulExtended:
1866 if (arg >= 2)
1867 lvalue = true;
1868 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001869 default:
1870 break;
1871 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001872 builder.clearAccessChain();
1873 if (invertedType != spv::NoType && arg == 0)
1874 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1875 else
1876 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001877 if (lvalue)
1878 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001879 else {
1880 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001881 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001882 }
John Kessenich140f3df2015-06-26 16:58:36 -06001883 }
John Kessenich426394d2015-07-23 10:22:48 -06001884
John Kesseniche485c7a2017-05-31 18:50:53 -06001885 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001886 if (atomic) {
1887 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001888 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001889 } else {
1890 // Pass through to generic operations.
1891 switch (glslangOperands.size()) {
1892 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001893 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001894 break;
1895 case 1:
qining25262b32016-05-06 17:25:16 -04001896 result = createUnaryOperation(
1897 node->getOp(), precision,
1898 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001899 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001900 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001901 break;
1902 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001903 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001904 break;
1905 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001906 if (invertedType)
1907 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001908 }
1909
1910 if (noReturnValue)
1911 return false;
1912
1913 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001914 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001915 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001916 } else {
1917 builder.clearAccessChain();
1918 builder.setAccessChainRValue(result);
1919 return false;
1920 }
1921}
1922
John Kessenich433e9ff2017-01-26 20:31:11 -07001923// This path handles both if-then-else and ?:
1924// The if-then-else has a node type of void, while
1925// ?: has either a void or a non-void node type
1926//
1927// Leaving the result, when not void:
1928// GLSL only has r-values as the result of a :?, but
1929// if we have an l-value, that can be more efficient if it will
1930// become the base of a complex r-value expression, because the
1931// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001932bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1933{
John Kessenich433e9ff2017-01-26 20:31:11 -07001934 // See if it simple and safe to generate OpSelect instead of using control flow.
1935 // Crucially, side effects must be avoided, and there are performance trade-offs.
1936 // Return true if good idea (and safe) for OpSelect, false otherwise.
1937 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001938 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1939 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001940 return false;
1941
1942 if (node->getTrueBlock() == nullptr ||
1943 node->getFalseBlock() == nullptr)
1944 return false;
1945
1946 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1947 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1948
1949 // return true if a single operand to ? : is okay for OpSelect
1950 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001951 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001952 };
1953
1954 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1955 operandOkay(node->getFalseBlock()->getAsTyped());
1956 };
1957
1958 // Emit OpSelect for this selection.
1959 const auto handleAsOpSelect = [&]() {
1960 node->getCondition()->traverse(this);
1961 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1962 node->getTrueBlock()->traverse(this);
1963 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1964 node->getFalseBlock()->traverse(this);
1965 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1966
John Kesseniche485c7a2017-05-31 18:50:53 -06001967 builder.setLine(node->getLoc().line);
1968
John Kesseniche434ad92017-03-30 10:09:28 -06001969 // smear condition to vector, if necessary (AST is always scalar)
1970 if (builder.isVector(trueValue))
1971 condition = builder.smearScalar(spv::NoPrecision, condition,
1972 builder.makeVectorType(builder.makeBoolType(),
1973 builder.getNumComponents(trueValue)));
1974
1975 spv::Id select = builder.createTriOp(spv::OpSelect,
1976 convertGlslangToSpvType(node->getType()), condition,
1977 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001978 builder.clearAccessChain();
1979 builder.setAccessChainRValue(select);
1980 };
1981
1982 // Try for OpSelect
1983
1984 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001985 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1986 if (node->getType().getQualifier().isSpecConstant())
1987 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1988
John Kessenich433e9ff2017-01-26 20:31:11 -07001989 handleAsOpSelect();
1990 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001991 }
1992
Rex Xu57e65922017-07-04 23:23:40 +08001993 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07001994 // Don't handle results as temporaries, because there will be two names
1995 // and better to leave SSA to later passes.
1996 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1997 ? spv::NoResult
1998 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1999
John Kessenich140f3df2015-06-26 16:58:36 -06002000 // emit the condition before doing anything with selection
2001 node->getCondition()->traverse(this);
2002
Rex Xu57e65922017-07-04 23:23:40 +08002003 // Selection control:
2004 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2005
John Kessenich140f3df2015-06-26 16:58:36 -06002006 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002007 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002008
John Kessenich433e9ff2017-01-26 20:31:11 -07002009 // emit the "then" statement
2010 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002011 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002012 if (result != spv::NoResult)
2013 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002014 }
2015
John Kessenich433e9ff2017-01-26 20:31:11 -07002016 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002017 ifBuilder.makeBeginElse();
2018 // emit the "else" statement
2019 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002020 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002021 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002022 }
2023
John Kessenich433e9ff2017-01-26 20:31:11 -07002024 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002025 ifBuilder.makeEndIf();
2026
John Kessenich433e9ff2017-01-26 20:31:11 -07002027 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002028 // GLSL only has r-values as the result of a :?, but
2029 // if we have an l-value, that can be more efficient if it will
2030 // become the base of a complex r-value expression, because the
2031 // next layer copies r-values into memory to use the access-chain mechanism
2032 builder.clearAccessChain();
2033 builder.setAccessChainLValue(result);
2034 }
2035
2036 return false;
2037}
2038
2039bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2040{
2041 // emit and get the condition before doing anything with switch
2042 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002043 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002044
Rex Xu57e65922017-07-04 23:23:40 +08002045 // Selection control:
2046 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2047
John Kessenich140f3df2015-06-26 16:58:36 -06002048 // browse the children to sort out code segments
2049 int defaultSegment = -1;
2050 std::vector<TIntermNode*> codeSegments;
2051 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2052 std::vector<int> caseValues;
2053 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2054 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2055 TIntermNode* child = *c;
2056 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002057 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002058 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002059 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002060 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2061 } else
2062 codeSegments.push_back(child);
2063 }
2064
qining25262b32016-05-06 17:25:16 -04002065 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002066 // statements between the last case and the end of the switch statement
2067 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2068 (int)codeSegments.size() == defaultSegment)
2069 codeSegments.push_back(nullptr);
2070
2071 // make the switch statement
2072 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002073 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002074
2075 // emit all the code in the segments
2076 breakForLoop.push(false);
2077 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2078 builder.nextSwitchSegment(segmentBlocks, s);
2079 if (codeSegments[s])
2080 codeSegments[s]->traverse(this);
2081 else
2082 builder.addSwitchBreak();
2083 }
2084 breakForLoop.pop();
2085
2086 builder.endSwitch(segmentBlocks);
2087
2088 return false;
2089}
2090
2091void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2092{
2093 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002094 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002095
2096 builder.clearAccessChain();
2097 builder.setAccessChainRValue(constant);
2098}
2099
2100bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2101{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002102 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002103 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002104
2105 // Loop control:
2106 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2107
2108 // TODO: dependency length
2109
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002110 // Spec requires back edges to target header blocks, and every header block
2111 // must dominate its merge block. Make a header block first to ensure these
2112 // conditions are met. By definition, it will contain OpLoopMerge, followed
2113 // by a block-ending branch. But we don't want to put any other body/test
2114 // instructions in it, since the body/test may have arbitrary instructions,
2115 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002116 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002117 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002118 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002119 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002120 spv::Block& test = builder.makeNewBlock();
2121 builder.createBranch(&test);
2122
2123 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002124 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002125 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002126 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2127
2128 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002129 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002130 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002131 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002132 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002133 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002134
2135 builder.setBuildPoint(&blocks.continue_target);
2136 if (node->getTerminal())
2137 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002138 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002139 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002140 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002141 builder.createBranch(&blocks.body);
2142
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002143 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002144 builder.setBuildPoint(&blocks.body);
2145 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002146 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002147 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002148 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002149
2150 builder.setBuildPoint(&blocks.continue_target);
2151 if (node->getTerminal())
2152 node->getTerminal()->traverse(this);
2153 if (node->getTest()) {
2154 node->getTest()->traverse(this);
2155 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002156 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002157 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002158 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002159 // TODO: unless there was a break/return/discard instruction
2160 // somewhere in the body, this is an infinite loop, so we should
2161 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002162 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002163 }
John Kessenich140f3df2015-06-26 16:58:36 -06002164 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002165 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002166 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002167 return false;
2168}
2169
2170bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2171{
2172 if (node->getExpression())
2173 node->getExpression()->traverse(this);
2174
John Kesseniche485c7a2017-05-31 18:50:53 -06002175 builder.setLine(node->getLoc().line);
2176
John Kessenich140f3df2015-06-26 16:58:36 -06002177 switch (node->getFlowOp()) {
2178 case glslang::EOpKill:
2179 builder.makeDiscard();
2180 break;
2181 case glslang::EOpBreak:
2182 if (breakForLoop.top())
2183 builder.createLoopExit();
2184 else
2185 builder.addSwitchBreak();
2186 break;
2187 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002188 builder.createLoopContinue();
2189 break;
2190 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002191 if (node->getExpression()) {
2192 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2193 spv::Id returnId = accessChainLoad(glslangReturnType);
2194 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2195 builder.clearAccessChain();
2196 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2197 builder.setAccessChainLValue(copyId);
2198 multiTypeStore(glslangReturnType, returnId);
2199 returnId = builder.createLoad(copyId);
2200 }
2201 builder.makeReturn(false, returnId);
2202 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002203 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002204
2205 builder.clearAccessChain();
2206 break;
2207
2208 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002209 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002210 break;
2211 }
2212
2213 return false;
2214}
2215
2216spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2217{
qining25262b32016-05-06 17:25:16 -04002218 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002219 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002220 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002221 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002222 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002223 }
2224
2225 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002226 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002227 spv::Id spvType = convertGlslangToSpvType(node->getType());
2228
Rex Xuf89ad982017-04-07 23:22:33 +08002229#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002230 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2231 node->getType().containsBasicType(glslang::EbtInt16) ||
2232 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002233 if (contains16BitType) {
2234 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2235 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2236 builder.addCapability(spv::CapabilityStorageInputOutput16);
2237 } else if (storageClass == spv::StorageClassPushConstant) {
2238 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2239 builder.addCapability(spv::CapabilityStoragePushConstant16);
2240 } else if (storageClass == spv::StorageClassUniform) {
2241 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2242 builder.addCapability(spv::CapabilityStorageUniform16);
2243 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2244 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2245 }
2246 }
2247#endif
2248
John Kessenich140f3df2015-06-26 16:58:36 -06002249 const char* name = node->getName().c_str();
2250 if (glslang::IsAnonymous(name))
2251 name = "";
2252
2253 return builder.createVariable(storageClass, spvType, name);
2254}
2255
2256// Return type Id of the sampled type.
2257spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2258{
2259 switch (sampler.type) {
2260 case glslang::EbtFloat: return builder.makeFloatType(32);
2261 case glslang::EbtInt: return builder.makeIntType(32);
2262 case glslang::EbtUint: return builder.makeUintType(32);
2263 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002264 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002265 return builder.makeFloatType(32);
2266 }
2267}
2268
John Kessenich8c8505c2016-07-26 12:50:38 -06002269// If node is a swizzle operation, return the type that should be used if
2270// the swizzle base is first consumed by another operation, before the swizzle
2271// is applied.
2272spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2273{
John Kessenichecba76f2017-01-06 00:34:48 -07002274 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002275 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2276 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2277 else
2278 return spv::NoType;
2279}
2280
2281// When inverting a swizzle with a parent op, this function
2282// will apply the swizzle operation to a completed parent operation.
2283spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2284{
2285 std::vector<unsigned> swizzle;
2286 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2287 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2288}
2289
John Kessenich8c8505c2016-07-26 12:50:38 -06002290// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2291void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2292{
2293 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2294 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2295 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2296}
2297
John Kessenich3ac051e2015-12-20 11:29:16 -07002298// Convert from a glslang type to an SPV type, by calling into a
2299// recursive version of this function. This establishes the inherited
2300// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002301spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2302{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002303 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002304}
2305
2306// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002307// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002308// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002309spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002310{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002311 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002312
2313 switch (type.getBasicType()) {
2314 case glslang::EbtVoid:
2315 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002316 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002317 break;
2318 case glslang::EbtFloat:
2319 spvType = builder.makeFloatType(32);
2320 break;
2321 case glslang::EbtDouble:
2322 spvType = builder.makeFloatType(64);
2323 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002324#ifdef AMD_EXTENSIONS
2325 case glslang::EbtFloat16:
2326 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002327 spvType = builder.makeFloatType(16);
2328 break;
2329#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002330 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002331 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2332 // a 32-bit int where non-0 means true.
2333 if (explicitLayout != glslang::ElpNone)
2334 spvType = builder.makeUintType(32);
2335 else
2336 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002337 break;
2338 case glslang::EbtInt:
2339 spvType = builder.makeIntType(32);
2340 break;
2341 case glslang::EbtUint:
2342 spvType = builder.makeUintType(32);
2343 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002344 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002345 spvType = builder.makeIntType(64);
2346 break;
2347 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002348 spvType = builder.makeUintType(64);
2349 break;
Rex Xucabbb782017-03-24 13:41:14 +08002350#ifdef AMD_EXTENSIONS
2351 case glslang::EbtInt16:
2352 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2353 spvType = builder.makeIntType(16);
2354 break;
2355 case glslang::EbtUint16:
2356 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2357 spvType = builder.makeUintType(16);
2358 break;
2359#endif
John Kessenich426394d2015-07-23 10:22:48 -06002360 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002361 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002362 spvType = builder.makeUintType(32);
2363 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002364 case glslang::EbtSampler:
2365 {
2366 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002367 if (sampler.sampler) {
2368 // pure sampler
2369 spvType = builder.makeSamplerType();
2370 } else {
2371 // an image is present, make its type
2372 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2373 sampler.image ? 2 : 1, TranslateImageFormat(type));
2374 if (sampler.combined) {
2375 // already has both image and sampler, make the combined type
2376 spvType = builder.makeSampledImageType(spvType);
2377 }
John Kessenich55e7d112015-11-15 21:33:39 -07002378 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002379 }
John Kessenich140f3df2015-06-26 16:58:36 -06002380 break;
2381 case glslang::EbtStruct:
2382 case glslang::EbtBlock:
2383 {
2384 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002385 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002386
2387 // Try to share structs for different layouts, but not yet for other
2388 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002389 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002390 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002391 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002392 break;
2393
2394 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002395 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002396 memberRemapper[glslangMembers].resize(glslangMembers->size());
2397 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002398 }
2399 break;
2400 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002401 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002402 break;
2403 }
2404
2405 if (type.isMatrix())
2406 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2407 else {
2408 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2409 if (type.getVectorSize() > 1)
2410 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2411 }
2412
2413 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002414 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2415
John Kessenichc9a80832015-09-12 12:17:44 -06002416 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002417 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002418 // We need to decorate array strides for types needing explicit layout, except blocks.
2419 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002420 // Use a dummy glslang type for querying internal strides of
2421 // arrays of arrays, but using just a one-dimensional array.
2422 glslang::TType simpleArrayType(type, 0); // deference type of the array
2423 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2424 simpleArrayType.getArraySizes().dereference();
2425
2426 // Will compute the higher-order strides here, rather than making a whole
2427 // pile of types and doing repetitive recursion on their contents.
2428 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2429 }
John Kessenichf8842e52016-01-04 19:22:56 -07002430
2431 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002432 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002433 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002434 if (stride > 0)
2435 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002436 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002437 }
2438 } else {
2439 // single-dimensional array, and don't yet have stride
2440
John Kessenichf8842e52016-01-04 19:22:56 -07002441 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002442 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2443 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002444 }
John Kessenich31ed4832015-09-09 17:51:38 -06002445
John Kessenichc9a80832015-09-12 12:17:44 -06002446 // Do the outer dimension, which might not be known for a runtime-sized array
2447 if (type.isRuntimeSizedArray()) {
2448 spvType = builder.makeRuntimeArray(spvType);
2449 } else {
2450 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002451 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002452 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002453 if (stride > 0)
2454 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002455 }
2456
2457 return spvType;
2458}
2459
John Kessenich0e737842017-03-24 18:38:16 -06002460// TODO: this functionality should exist at a higher level, in creating the AST
2461//
2462// Identify interface members that don't have their required extension turned on.
2463//
2464bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2465{
2466 auto& extensions = glslangIntermediate->getRequestedExtensions();
2467
Rex Xubcf291a2017-03-29 23:01:36 +08002468 if (member.getFieldName() == "gl_ViewportMask" &&
2469 extensions.find("GL_NV_viewport_array2") == extensions.end())
2470 return true;
2471 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2472 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2473 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002474 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2475 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2476 return true;
2477 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2478 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2479 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002480 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2481 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2482 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002483
2484 return false;
2485};
2486
John Kessenich6090df02016-06-30 21:18:02 -06002487// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2488// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2489// Mutually recursive with convertGlslangToSpvType().
2490spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2491 const glslang::TTypeList* glslangMembers,
2492 glslang::TLayoutPacking explicitLayout,
2493 const glslang::TQualifier& qualifier)
2494{
2495 // Create a vector of struct types for SPIR-V to consume
2496 std::vector<spv::Id> spvMembers;
2497 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 -06002498 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2499 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2500 if (glslangMember.hiddenMember()) {
2501 ++memberDelta;
2502 if (type.getBasicType() == glslang::EbtBlock)
2503 memberRemapper[glslangMembers][i] = -1;
2504 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002505 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002506 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002507 if (filterMember(glslangMember))
2508 continue;
2509 }
John Kessenich6090df02016-06-30 21:18:02 -06002510 // modify just this child's view of the qualifier
2511 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2512 InheritQualifiers(memberQualifier, qualifier);
2513
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002514 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002515 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002516 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002517
2518 // recurse
2519 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2520 }
2521 }
2522
2523 // Make the SPIR-V type
2524 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002525 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002526 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2527
2528 // Decorate it
2529 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2530
2531 return spvType;
2532}
2533
2534void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2535 const glslang::TTypeList* glslangMembers,
2536 glslang::TLayoutPacking explicitLayout,
2537 const glslang::TQualifier& qualifier,
2538 spv::Id spvType)
2539{
2540 // Name and decorate the non-hidden members
2541 int offset = -1;
2542 int locationOffset = 0; // for use within the members of this struct
2543 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2544 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2545 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002546 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002547 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002548 if (filterMember(glslangMember))
2549 continue;
2550 }
John Kessenich6090df02016-06-30 21:18:02 -06002551
2552 // modify just this child's view of the qualifier
2553 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2554 InheritQualifiers(memberQualifier, qualifier);
2555
2556 // using -1 above to indicate a hidden member
2557 if (member >= 0) {
2558 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2559 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2560 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2561 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002562 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2563 type.getQualifier().storage == glslang::EvqVaryingOut) {
2564 if (type.getBasicType() == glslang::EbtBlock ||
2565 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002566 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2567 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2568 }
2569 }
2570 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2571
Rex Xu286ca432017-07-27 14:33:16 +08002572 if (type.getBasicType() == glslang::EbtBlock &&
2573 qualifier.storage == glslang::EvqBuffer) {
2574 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002575 std::vector<spv::Decoration> memory;
2576 TranslateMemoryDecoration(memberQualifier, memory);
2577 for (unsigned int i = 0; i < memory.size(); ++i)
2578 addMemberDecoration(spvType, member, memory[i]);
2579 }
2580
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002581 // Location assignment was already completed correctly by the front end,
2582 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002583 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002584 // ill-specified and decisions have been made to not allow this.
2585 if (! type.isArray() && memberQualifier.hasLocation())
2586 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002587
John Kessenich2f47bc92016-06-30 21:47:35 -06002588 if (qualifier.hasLocation()) // track for upcoming inheritance
2589 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2590
John Kessenich6090df02016-06-30 21:18:02 -06002591 // component, XFB, others
2592 if (glslangMember.getQualifier().hasComponent())
2593 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2594 if (glslangMember.getQualifier().hasXfbOffset())
2595 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2596 else if (explicitLayout != glslang::ElpNone) {
2597 // figure out what to do with offset, which is accumulating
2598 int nextOffset;
2599 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2600 if (offset >= 0)
2601 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2602 offset = nextOffset;
2603 }
2604
2605 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2606 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2607
2608 // built-in variable decorations
2609 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002610 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002611 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002612
2613#ifdef NV_EXTENSIONS
2614 if (builtIn == spv::BuiltInLayer) {
2615 // SPV_NV_viewport_array2 extension
2616 if (glslangMember.getQualifier().layoutViewportRelative){
2617 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2618 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2619 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2620 }
2621 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2622 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2623 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2624 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2625 }
2626 }
chaocdf3956c2017-02-14 14:52:34 -08002627 if (glslangMember.getQualifier().layoutPassthrough) {
2628 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2629 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2630 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2631 }
chaoc771d89f2017-01-13 01:10:53 -08002632#endif
John Kessenich6090df02016-06-30 21:18:02 -06002633 }
2634 }
2635
2636 // Decorate the structure
2637 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002638 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002639 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2640 builder.addCapability(spv::CapabilityGeometryStreams);
2641 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2642 }
2643 if (glslangIntermediate->getXfbMode()) {
2644 builder.addCapability(spv::CapabilityTransformFeedback);
2645 if (type.getQualifier().hasXfbStride())
2646 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2647 if (type.getQualifier().hasXfbBuffer())
2648 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2649 }
2650}
2651
John Kessenich6c292d32016-02-15 20:58:50 -07002652// Turn the expression forming the array size into an id.
2653// This is not quite trivial, because of specialization constants.
2654// Sometimes, a raw constant is turned into an Id, and sometimes
2655// a specialization constant expression is.
2656spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2657{
2658 // First, see if this is sized with a node, meaning a specialization constant:
2659 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2660 if (specNode != nullptr) {
2661 builder.clearAccessChain();
2662 specNode->traverse(this);
2663 return accessChainLoad(specNode->getAsTyped()->getType());
2664 }
qining25262b32016-05-06 17:25:16 -04002665
John Kessenich6c292d32016-02-15 20:58:50 -07002666 // Otherwise, need a compile-time (front end) size, get it:
2667 int size = arraySizes.getDimSize(dim);
2668 assert(size > 0);
2669 return builder.makeUintConstant(size);
2670}
2671
John Kessenich103bef92016-02-08 21:38:15 -07002672// Wrap the builder's accessChainLoad to:
2673// - localize handling of RelaxedPrecision
2674// - use the SPIR-V inferred type instead of another conversion of the glslang type
2675// (avoids unnecessary work and possible type punning for structures)
2676// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002677spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2678{
John Kessenich103bef92016-02-08 21:38:15 -07002679 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2680 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2681
2682 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002683 if (type.getBasicType() == glslang::EbtBool) {
2684 if (builder.isScalarType(nominalTypeId)) {
2685 // Conversion for bool
2686 spv::Id boolType = builder.makeBoolType();
2687 if (nominalTypeId != boolType)
2688 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2689 } else if (builder.isVectorType(nominalTypeId)) {
2690 // Conversion for bvec
2691 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2692 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2693 if (nominalTypeId != bvecType)
2694 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2695 }
2696 }
John Kessenich103bef92016-02-08 21:38:15 -07002697
2698 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002699}
2700
Rex Xu27253232016-02-23 17:51:09 +08002701// Wrap the builder's accessChainStore to:
2702// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002703//
2704// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002705void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2706{
2707 // Need to convert to abstract types when necessary
2708 if (type.getBasicType() == glslang::EbtBool) {
2709 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2710
2711 if (builder.isScalarType(nominalTypeId)) {
2712 // Conversion for bool
2713 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002714 if (nominalTypeId != boolType) {
2715 // keep these outside arguments, for determinant order-of-evaluation
2716 spv::Id one = builder.makeUintConstant(1);
2717 spv::Id zero = builder.makeUintConstant(0);
2718 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2719 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002720 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002721 } else if (builder.isVectorType(nominalTypeId)) {
2722 // Conversion for bvec
2723 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2724 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002725 if (nominalTypeId != bvecType) {
2726 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002727 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2728 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2729 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002730 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002731 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2732 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002733 }
2734 }
2735
2736 builder.accessChainStore(rvalue);
2737}
2738
John Kessenich4bf71552016-09-02 11:20:21 -06002739// For storing when types match at the glslang level, but not might match at the
2740// SPIR-V level.
2741//
2742// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002743// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002744// as in a member-decorated way.
2745//
2746// NOTE: This function can handle any store request; if it's not special it
2747// simplifies to a simple OpStore.
2748//
2749// Implicitly uses the existing builder.accessChain as the storage target.
2750void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2751{
John Kessenichb3e24e42016-09-11 12:33:43 -06002752 // we only do the complex path here if it's an aggregate
2753 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002754 accessChainStore(type, rValue);
2755 return;
2756 }
2757
John Kessenichb3e24e42016-09-11 12:33:43 -06002758 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002759 spv::Id rType = builder.getTypeId(rValue);
2760 spv::Id lValue = builder.accessChainGetLValue();
2761 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2762 if (lType == rType) {
2763 accessChainStore(type, rValue);
2764 return;
2765 }
2766
John Kessenichb3e24e42016-09-11 12:33:43 -06002767 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002768 // where the two types were the same type in GLSL. This requires member
2769 // by member copy, recursively.
2770
John Kessenichb3e24e42016-09-11 12:33:43 -06002771 // If an array, copy element by element.
2772 if (type.isArray()) {
2773 glslang::TType glslangElementType(type, 0);
2774 spv::Id elementRType = builder.getContainedTypeId(rType);
2775 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2776 // get the source member
2777 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002778
John Kessenichb3e24e42016-09-11 12:33:43 -06002779 // set up the target storage
2780 builder.clearAccessChain();
2781 builder.setAccessChainLValue(lValue);
2782 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002783
John Kessenichb3e24e42016-09-11 12:33:43 -06002784 // store the member
2785 multiTypeStore(glslangElementType, elementRValue);
2786 }
2787 } else {
2788 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002789
John Kessenichb3e24e42016-09-11 12:33:43 -06002790 // loop over structure members
2791 const glslang::TTypeList& members = *type.getStruct();
2792 for (int m = 0; m < (int)members.size(); ++m) {
2793 const glslang::TType& glslangMemberType = *members[m].type;
2794
2795 // get the source member
2796 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2797 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2798
2799 // set up the target storage
2800 builder.clearAccessChain();
2801 builder.setAccessChainLValue(lValue);
2802 builder.accessChainPush(builder.makeIntConstant(m));
2803
2804 // store the member
2805 multiTypeStore(glslangMemberType, memberRValue);
2806 }
John Kessenich4bf71552016-09-02 11:20:21 -06002807 }
2808}
2809
John Kessenichf85e8062015-12-19 13:57:10 -07002810// Decide whether or not this type should be
2811// decorated with offsets and strides, and if so
2812// whether std140 or std430 rules should be applied.
2813glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002814{
John Kessenichf85e8062015-12-19 13:57:10 -07002815 // has to be a block
2816 if (type.getBasicType() != glslang::EbtBlock)
2817 return glslang::ElpNone;
2818
2819 // has to be a uniform or buffer block
2820 if (type.getQualifier().storage != glslang::EvqUniform &&
2821 type.getQualifier().storage != glslang::EvqBuffer)
2822 return glslang::ElpNone;
2823
2824 // return the layout to use
2825 switch (type.getQualifier().layoutPacking) {
2826 case glslang::ElpStd140:
2827 case glslang::ElpStd430:
2828 return type.getQualifier().layoutPacking;
2829 default:
2830 return glslang::ElpNone;
2831 }
John Kessenich31ed4832015-09-09 17:51:38 -06002832}
2833
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002834// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002835int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002836{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002837 int size;
John Kessenich49987892015-12-29 17:11:44 -07002838 int stride;
2839 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002840
2841 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002842}
2843
John Kessenich49987892015-12-29 17:11:44 -07002844// 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 -07002845// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002846int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002847{
John Kessenich49987892015-12-29 17:11:44 -07002848 glslang::TType elementType;
2849 elementType.shallowCopy(matrixType);
2850 elementType.clearArraySizes();
2851
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002852 int size;
John Kessenich49987892015-12-29 17:11:44 -07002853 int stride;
2854 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2855
2856 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002857}
2858
John Kessenich5e4b1242015-08-06 22:53:06 -06002859// Given a member type of a struct, realign the current offset for it, and compute
2860// the next (not yet aligned) offset for the next member, which will get aligned
2861// on the next call.
2862// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2863// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2864// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002865void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002866 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002867{
2868 // this will get a positive value when deemed necessary
2869 nextOffset = -1;
2870
John Kessenich5e4b1242015-08-06 22:53:06 -06002871 // override anything in currentOffset with user-set offset
2872 if (memberType.getQualifier().hasOffset())
2873 currentOffset = memberType.getQualifier().layoutOffset;
2874
2875 // It could be that current linker usage in glslang updated all the layoutOffset,
2876 // in which case the following code does not matter. But, that's not quite right
2877 // once cross-compilation unit GLSL validation is done, as the original user
2878 // settings are needed in layoutOffset, and then the following will come into play.
2879
John Kessenichf85e8062015-12-19 13:57:10 -07002880 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002881 if (! memberType.getQualifier().hasOffset())
2882 currentOffset = -1;
2883
2884 return;
2885 }
2886
John Kessenichf85e8062015-12-19 13:57:10 -07002887 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002888 if (currentOffset < 0)
2889 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002890
John Kessenich5e4b1242015-08-06 22:53:06 -06002891 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2892 // but possibly not yet correctly aligned.
2893
2894 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002895 int dummyStride;
2896 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002897
2898 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002899 // TODO: make this consistent in early phases of code:
2900 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2901 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2902 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002903 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002904 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002905 int dummySize;
2906 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2907 if (componentAlignment <= 4)
2908 memberAlignment = componentAlignment;
2909 }
2910
2911 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002912 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002913
2914 // Bump up to vec4 if there is a bad straddle
2915 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2916 glslang::RoundToPow2(currentOffset, 16);
2917
John Kessenich5e4b1242015-08-06 22:53:06 -06002918 nextOffset = currentOffset + memberSize;
2919}
2920
David Netoa901ffe2016-06-08 14:11:40 +01002921void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002922{
David Netoa901ffe2016-06-08 14:11:40 +01002923 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2924 switch (glslangBuiltIn)
2925 {
2926 case glslang::EbvClipDistance:
2927 case glslang::EbvCullDistance:
2928 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002929#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002930 case glslang::EbvViewportMaskNV:
2931 case glslang::EbvSecondaryPositionNV:
2932 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002933 case glslang::EbvPositionPerViewNV:
2934 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002935#endif
David Netoa901ffe2016-06-08 14:11:40 +01002936 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2937 // Alternately, we could just call this for any glslang built-in, since the
2938 // capability already guards against duplicates.
2939 TranslateBuiltInDecoration(glslangBuiltIn, false);
2940 break;
2941 default:
2942 // Capabilities were already generated when the struct was declared.
2943 break;
2944 }
John Kessenichebb50532016-05-16 19:22:05 -06002945}
2946
John Kessenich6fccb3c2016-09-19 16:01:41 -06002947bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002948{
John Kessenicheee9d532016-09-19 18:09:30 -06002949 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002950}
2951
2952// Make all the functions, skeletally, without actually visiting their bodies.
2953void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2954{
John Kessenichfad62972017-07-18 02:35:46 -06002955 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2956 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2957 if (paramPrecision != spv::NoPrecision)
2958 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002959 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002960 };
2961
John Kessenich140f3df2015-06-26 16:58:36 -06002962 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2963 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002964 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002965 continue;
2966
2967 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002968 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002969 //
qining25262b32016-05-06 17:25:16 -04002970 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002971 // function. What it is an address of varies:
2972 //
John Kessenich4bf71552016-09-02 11:20:21 -06002973 // - "in" parameters not marked as "const" can be written to without modifying the calling
2974 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002975 //
2976 // - "const in" parameters can just be the r-value, as no writes need occur.
2977 //
John Kessenich4bf71552016-09-02 11:20:21 -06002978 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2979 // 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 -06002980
2981 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002982 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002983 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2984
John Kessenichfad62972017-07-18 02:35:46 -06002985 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2986 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002987
John Kessenichfad62972017-07-18 02:35:46 -06002988 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06002989 for (int p = 0; p < (int)parameters.size(); ++p) {
2990 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2991 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002992 // can we pass by reference?
2993 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002994 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002995 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002996 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002997 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002998 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002999 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3000 else
John Kessenich4bf71552016-09-02 11:20:21 -06003001 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003002 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003003 paramTypes.push_back(typeId);
3004 }
3005
3006 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003007 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3008 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003009 glslFunction->getName().c_str(), paramTypes,
3010 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003011 if (implicitThis)
3012 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003013
3014 // Track function to emit/call later
3015 functionMap[glslFunction->getName().c_str()] = function;
3016
3017 // Set the parameter id's
3018 for (int p = 0; p < (int)parameters.size(); ++p) {
3019 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3020 // give a name too
3021 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3022 }
3023 }
3024}
3025
3026// Process all the initializers, while skipping the functions and link objects
3027void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3028{
3029 builder.setBuildPoint(shaderEntry->getLastBlock());
3030 for (int i = 0; i < (int)initializers.size(); ++i) {
3031 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3032 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3033
3034 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003035 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003036 initializer->traverse(this);
3037 }
3038 }
3039}
3040
3041// Process all the functions, while skipping initializers.
3042void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3043{
3044 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3045 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003046 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003047 node->traverse(this);
3048 }
3049}
3050
3051void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3052{
qining25262b32016-05-06 17:25:16 -04003053 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003054 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003055 currentFunction = functionMap[node->getName().c_str()];
3056 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003057 builder.setBuildPoint(functionBlock);
3058}
3059
Rex Xu04db3f52015-09-16 11:44:02 +08003060void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003061{
Rex Xufc618912015-09-09 16:42:49 +08003062 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003063
3064 glslang::TSampler sampler = {};
3065 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003066 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003067 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3068 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3069 }
3070
John Kessenich140f3df2015-06-26 16:58:36 -06003071 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3072 builder.clearAccessChain();
3073 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003074
3075 // Special case l-value operands
3076 bool lvalue = false;
3077 switch (node.getOp()) {
3078 case glslang::EOpImageAtomicAdd:
3079 case glslang::EOpImageAtomicMin:
3080 case glslang::EOpImageAtomicMax:
3081 case glslang::EOpImageAtomicAnd:
3082 case glslang::EOpImageAtomicOr:
3083 case glslang::EOpImageAtomicXor:
3084 case glslang::EOpImageAtomicExchange:
3085 case glslang::EOpImageAtomicCompSwap:
3086 if (i == 0)
3087 lvalue = true;
3088 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003089 case glslang::EOpSparseImageLoad:
3090 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3091 lvalue = true;
3092 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003093 case glslang::EOpSparseTexture:
3094 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3095 lvalue = true;
3096 break;
3097 case glslang::EOpSparseTextureClamp:
3098 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3099 lvalue = true;
3100 break;
3101 case glslang::EOpSparseTextureLod:
3102 case glslang::EOpSparseTextureOffset:
3103 if (i == 3)
3104 lvalue = true;
3105 break;
3106 case glslang::EOpSparseTextureFetch:
3107 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3108 lvalue = true;
3109 break;
3110 case glslang::EOpSparseTextureFetchOffset:
3111 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3112 lvalue = true;
3113 break;
3114 case glslang::EOpSparseTextureLodOffset:
3115 case glslang::EOpSparseTextureGrad:
3116 case glslang::EOpSparseTextureOffsetClamp:
3117 if (i == 4)
3118 lvalue = true;
3119 break;
3120 case glslang::EOpSparseTextureGradOffset:
3121 case glslang::EOpSparseTextureGradClamp:
3122 if (i == 5)
3123 lvalue = true;
3124 break;
3125 case glslang::EOpSparseTextureGradOffsetClamp:
3126 if (i == 6)
3127 lvalue = true;
3128 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003129 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003130 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3131 lvalue = true;
3132 break;
3133 case glslang::EOpSparseTextureGatherOffset:
3134 case glslang::EOpSparseTextureGatherOffsets:
3135 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3136 lvalue = true;
3137 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003138#ifdef AMD_EXTENSIONS
3139 case glslang::EOpSparseTextureGatherLod:
3140 if (i == 3)
3141 lvalue = true;
3142 break;
3143 case glslang::EOpSparseTextureGatherLodOffset:
3144 case glslang::EOpSparseTextureGatherLodOffsets:
3145 if (i == 4)
3146 lvalue = true;
3147 break;
Rex Xu129799a2017-07-05 17:23:28 +08003148 case glslang::EOpSparseImageLoadLod:
3149 if (i == 3)
3150 lvalue = true;
3151 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003152#endif
Rex Xufc618912015-09-09 16:42:49 +08003153 default:
3154 break;
3155 }
3156
Rex Xu6b86d492015-09-16 17:48:22 +08003157 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003158 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003159 else
John Kessenich32cfd492016-02-02 12:37:46 -07003160 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003161 }
3162}
3163
John Kessenichfc51d282015-08-19 13:34:18 -06003164void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003165{
John Kessenichfc51d282015-08-19 13:34:18 -06003166 builder.clearAccessChain();
3167 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003168 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003169}
John Kessenich140f3df2015-06-26 16:58:36 -06003170
John Kessenichfc51d282015-08-19 13:34:18 -06003171spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3172{
John Kesseniche485c7a2017-05-31 18:50:53 -06003173 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003174 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003175
3176 builder.setLine(node->getLoc().line);
3177
John Kessenich8c8505c2016-07-26 12:50:38 -06003178 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003179
John Kessenichfc51d282015-08-19 13:34:18 -06003180 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003181 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3182 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3183 std::vector<spv::Id> arguments;
3184 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003185 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003186 else
3187 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003188 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003189
3190 spv::Builder::TextureParameters params = { };
3191 params.sampler = arguments[0];
3192
Rex Xu04db3f52015-09-16 11:44:02 +08003193 glslang::TCrackedTextureOp cracked;
3194 node->crackTexture(sampler, cracked);
3195
amhagan05506bb2017-06-13 16:53:02 -04003196 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003197
John Kessenichfc51d282015-08-19 13:34:18 -06003198 // Check for queries
3199 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003200 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3201 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003202 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003203
John Kessenichfc51d282015-08-19 13:34:18 -06003204 switch (node->getOp()) {
3205 case glslang::EOpImageQuerySize:
3206 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003207 if (arguments.size() > 1) {
3208 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003209 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003210 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003211 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003212 case glslang::EOpImageQuerySamples:
3213 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003214 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003215 case glslang::EOpTextureQueryLod:
3216 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003217 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003218 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003219 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003220 case glslang::EOpSparseTexelsResident:
3221 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003222 default:
3223 assert(0);
3224 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003225 }
John Kessenich140f3df2015-06-26 16:58:36 -06003226 }
3227
Rex Xufc618912015-09-09 16:42:49 +08003228 // Check for image functions other than queries
3229 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003230 std::vector<spv::Id> operands;
3231 auto opIt = arguments.begin();
3232 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003233
3234 // Handle subpass operations
3235 // TODO: GLSL should change to have the "MS" only on the type rather than the
3236 // built-in function.
3237 if (cracked.subpass) {
3238 // add on the (0,0) coordinate
3239 spv::Id zero = builder.makeIntConstant(0);
3240 std::vector<spv::Id> comps;
3241 comps.push_back(zero);
3242 comps.push_back(zero);
3243 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3244 if (sampler.ms) {
3245 operands.push_back(spv::ImageOperandsSampleMask);
3246 operands.push_back(*(opIt++));
3247 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003248 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003249 }
3250
John Kessenich56bab042015-09-16 10:54:31 -06003251 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003252#ifdef AMD_EXTENSIONS
3253 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3254#else
John Kessenich56bab042015-09-16 10:54:31 -06003255 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003256#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003257 if (sampler.ms) {
3258 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003259 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003260#ifdef AMD_EXTENSIONS
3261 } else if (cracked.lod) {
3262 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3263 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3264
3265 operands.push_back(spv::ImageOperandsLodMask);
3266 operands.push_back(*opIt);
3267#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003268 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003269 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3270 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003271 return builder.createOp(spv::OpImageRead, resultType(), operands);
Rex Xu129799a2017-07-05 17:23:28 +08003272#ifdef AMD_EXTENSIONS
3273 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3274#else
John Kessenich56bab042015-09-16 10:54:31 -06003275 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003276#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003277 if (sampler.ms) {
3278 operands.push_back(*(opIt + 1));
3279 operands.push_back(spv::ImageOperandsSampleMask);
3280 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003281#ifdef AMD_EXTENSIONS
3282 } else if (cracked.lod) {
3283 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3284 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3285
3286 operands.push_back(*(opIt + 1));
3287 operands.push_back(spv::ImageOperandsLodMask);
3288 operands.push_back(*opIt);
3289#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003290 } else
3291 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003292 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003293 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3294 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003295 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003296#ifdef AMD_EXTENSIONS
3297 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3298#else
Rex Xu5eafa472016-02-19 22:24:03 +08003299 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003300#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003301 builder.addCapability(spv::CapabilitySparseResidency);
3302 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3303 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3304
3305 if (sampler.ms) {
3306 operands.push_back(spv::ImageOperandsSampleMask);
3307 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003308#ifdef AMD_EXTENSIONS
3309 } else if (cracked.lod) {
3310 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3311 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3312
3313 operands.push_back(spv::ImageOperandsLodMask);
3314 operands.push_back(*opIt++);
3315#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003316 }
3317
3318 // Create the return type that was a special structure
3319 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003320 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003321 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3322 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3323
3324 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3325
3326 // Decode the return type
3327 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3328 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003329 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003330 // Process image atomic operations
3331
3332 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3333 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003334 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003335
John Kessenich8c8505c2016-07-26 12:50:38 -06003336 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003337 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003338
3339 std::vector<spv::Id> operands;
3340 operands.push_back(pointer);
3341 for (; opIt != arguments.end(); ++opIt)
3342 operands.push_back(*opIt);
3343
John Kessenich8c8505c2016-07-26 12:50:38 -06003344 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003345 }
3346 }
3347
amhagan05506bb2017-06-13 16:53:02 -04003348#ifdef AMD_EXTENSIONS
3349 // Check for fragment mask functions other than queries
3350 if (cracked.fragMask) {
3351 assert(sampler.ms);
3352
3353 auto opIt = arguments.begin();
3354 std::vector<spv::Id> operands;
3355
3356 // Extract the image if necessary
3357 if (builder.isSampledImage(params.sampler))
3358 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3359
3360 operands.push_back(params.sampler);
3361 ++opIt;
3362
3363 if (sampler.isSubpass()) {
3364 // add on the (0,0) coordinate
3365 spv::Id zero = builder.makeIntConstant(0);
3366 std::vector<spv::Id> comps;
3367 comps.push_back(zero);
3368 comps.push_back(zero);
3369 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3370 }
3371
3372 for (; opIt != arguments.end(); ++opIt)
3373 operands.push_back(*opIt);
3374
3375 spv::Op fragMaskOp = spv::OpNop;
3376 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3377 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3378 else if (node->getOp() == glslang::EOpFragmentFetch)
3379 fragMaskOp = spv::OpFragmentFetchAMD;
3380
3381 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3382 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3383 return builder.createOp(fragMaskOp, resultType(), operands);
3384 }
3385#endif
3386
Rex Xufc618912015-09-09 16:42:49 +08003387 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003388 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003389 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3390
John Kessenichfc51d282015-08-19 13:34:18 -06003391 // check for bias argument
3392 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003393#ifdef AMD_EXTENSIONS
3394 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3395#else
Rex Xu71519fe2015-11-11 15:35:47 +08003396 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003397#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003398 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003399#ifdef AMD_EXTENSIONS
3400 if (cracked.gather)
3401 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3402#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003403 if (cracked.offset)
3404 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003405#ifdef AMD_EXTENSIONS
3406 else if (cracked.offsets)
3407 ++nonBiasArgCount;
3408#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003409 if (cracked.grad)
3410 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003411 if (cracked.lodClamp)
3412 ++nonBiasArgCount;
3413 if (sparse)
3414 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003415
3416 if ((int)arguments.size() > nonBiasArgCount)
3417 bias = true;
3418 }
3419
John Kessenicha5c33d62016-06-02 23:45:21 -06003420 // See if the sampler param should really be just the SPV image part
3421 if (cracked.fetch) {
3422 // a fetch needs to have the image extracted first
3423 if (builder.isSampledImage(params.sampler))
3424 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3425 }
3426
Rex Xu225e0fc2016-11-17 17:47:59 +08003427#ifdef AMD_EXTENSIONS
3428 if (cracked.gather) {
3429 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3430 if (bias || cracked.lod ||
3431 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3432 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003433 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003434 }
3435 }
3436#endif
3437
John Kessenichfc51d282015-08-19 13:34:18 -06003438 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003439
John Kessenichfc51d282015-08-19 13:34:18 -06003440 params.coords = arguments[1];
3441 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003442 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003443
3444 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003445 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003446 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003447 ++extraArgs;
3448 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003449 params.Dref = arguments[2];
3450 ++extraArgs;
3451 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003452 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003453 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003454 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003455 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003456 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003457 dRefComp = builder.getNumComponents(params.coords) - 1;
3458 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003459 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3460 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003461
3462 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003463 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003464 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003465 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003466 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3467 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3468 noImplicitLod = true;
3469 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003470
3471 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003472 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003473 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003474 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003475 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003476
3477 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003478 if (cracked.grad) {
3479 params.gradX = arguments[2 + extraArgs];
3480 params.gradY = arguments[3 + extraArgs];
3481 extraArgs += 2;
3482 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003483
3484 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003485 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003486 params.offset = arguments[2 + extraArgs];
3487 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003488 } else if (cracked.offsets) {
3489 params.offsets = arguments[2 + extraArgs];
3490 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003491 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003492
3493 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003494 if (cracked.lodClamp) {
3495 params.lodClamp = arguments[2 + extraArgs];
3496 ++extraArgs;
3497 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003498
3499 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003500 if (sparse) {
3501 params.texelOut = arguments[2 + extraArgs];
3502 ++extraArgs;
3503 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003504
John Kessenich76d4dfc2016-06-16 12:43:23 -06003505 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003506 if (cracked.gather && ! sampler.shadow) {
3507 // default component is 0, if missing, otherwise an argument
3508 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003509 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003510 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003511 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003512 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003513 }
3514
3515 // bias
3516 if (bias) {
3517 params.bias = arguments[2 + extraArgs];
3518 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003519 }
John Kessenichfc51d282015-08-19 13:34:18 -06003520
John Kessenich65336482016-06-16 14:06:26 -06003521 // projective component (might not to move)
3522 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3523 // are divided by the last component of P."
3524 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3525 // unused components will appear after all used components."
3526 if (cracked.proj) {
3527 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3528 int projTargetComp;
3529 switch (sampler.dim) {
3530 case glslang::Esd1D: projTargetComp = 1; break;
3531 case glslang::Esd2D: projTargetComp = 2; break;
3532 case glslang::EsdRect: projTargetComp = 2; break;
3533 default: projTargetComp = projSourceComp; break;
3534 }
3535 // copy the projective coordinate if we have to
3536 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003537 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003538 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3539 projSourceComp);
3540 params.coords = builder.createCompositeInsert(projComp, params.coords,
3541 builder.getTypeId(params.coords), projTargetComp);
3542 }
3543 }
3544
John Kessenich8c8505c2016-07-26 12:50:38 -06003545 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003546}
3547
3548spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3549{
3550 // Grab the function's pointer from the previously created function
3551 spv::Function* function = functionMap[node->getName().c_str()];
3552 if (! function)
3553 return 0;
3554
3555 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3556 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3557
LoopDawg76117922017-09-06 14:59:06 -06003558 // Encapsulate lvalue logic, used in two places below, for safety.
3559 const auto isLValue = [](int qualifier, const glslang::TType& paramType) -> bool {
3560 return qualifier != glslang::EvqConstReadOnly || paramType.containsOpaque();
3561 };
3562
John Kessenich140f3df2015-06-26 16:58:36 -06003563 // See comments in makeFunctions() for details about the semantics for parameter passing.
3564 //
3565 // These imply we need a four step process:
3566 // 1. Evaluate the arguments
3567 // 2. Allocate and make copies of in, out, and inout arguments
3568 // 3. Make the call
3569 // 4. Copy back the results
3570
3571 // 1. Evaluate the arguments
3572 std::vector<spv::Builder::AccessChain> lValues;
3573 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003574 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003575 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003576 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003577 // build l-value
3578 builder.clearAccessChain();
3579 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003580 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003581 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
LoopDawg76117922017-09-06 14:59:06 -06003582 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003583 // save l-value
3584 lValues.push_back(builder.getAccessChain());
3585 } else {
3586 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003587 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003588 }
3589 }
3590
3591 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3592 // copy the original into that space.
3593 //
3594 // Also, build up the list of actual arguments to pass in for the call
3595 int lValueCount = 0;
3596 int rValueCount = 0;
3597 std::vector<spv::Id> spvArgs;
3598 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003599 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003600 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003601 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003602 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3603 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003604 builder.setAccessChain(lValues[lValueCount]);
3605 arg = builder.accessChainGetLValue();
3606 ++lValueCount;
LoopDawg76117922017-09-06 14:59:06 -06003607 } else if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003608 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003609 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3610 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3611 // need to copy the input into output space
3612 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003613 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003614 builder.clearAccessChain();
3615 builder.setAccessChainLValue(arg);
3616 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003617 }
3618 ++lValueCount;
3619 } else {
3620 arg = rValues[rValueCount];
3621 ++rValueCount;
3622 }
3623 spvArgs.push_back(arg);
3624 }
3625
3626 // 3. Make the call.
3627 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003628 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003629
3630 // 4. Copy back out an "out" arguments.
3631 lValueCount = 0;
3632 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003633 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
LoopDawg76117922017-09-06 14:59:06 -06003634 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003635 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3636 spv::Id copy = builder.createLoad(spvArgs[a]);
3637 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003638 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003639 }
3640 ++lValueCount;
3641 }
3642 }
3643
3644 return result;
3645}
3646
3647// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003648spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3649 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003650 spv::Id typeId, spv::Id left, spv::Id right,
3651 glslang::TBasicType typeProxy, bool reduceComparison)
3652{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003653#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003654 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003655 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3656#else
Rex Xucabbb782017-03-24 13:41:14 +08003657 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003658 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003659#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003660 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003661
3662 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003663 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003664 bool comparison = false;
3665
3666 switch (op) {
3667 case glslang::EOpAdd:
3668 case glslang::EOpAddAssign:
3669 if (isFloat)
3670 binOp = spv::OpFAdd;
3671 else
3672 binOp = spv::OpIAdd;
3673 break;
3674 case glslang::EOpSub:
3675 case glslang::EOpSubAssign:
3676 if (isFloat)
3677 binOp = spv::OpFSub;
3678 else
3679 binOp = spv::OpISub;
3680 break;
3681 case glslang::EOpMul:
3682 case glslang::EOpMulAssign:
3683 if (isFloat)
3684 binOp = spv::OpFMul;
3685 else
3686 binOp = spv::OpIMul;
3687 break;
3688 case glslang::EOpVectorTimesScalar:
3689 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003690 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003691 if (builder.isVector(right))
3692 std::swap(left, right);
3693 assert(builder.isScalar(right));
3694 needMatchingVectors = false;
3695 binOp = spv::OpVectorTimesScalar;
3696 } else
3697 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003698 break;
3699 case glslang::EOpVectorTimesMatrix:
3700 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003701 binOp = spv::OpVectorTimesMatrix;
3702 break;
3703 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003704 binOp = spv::OpMatrixTimesVector;
3705 break;
3706 case glslang::EOpMatrixTimesScalar:
3707 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003708 binOp = spv::OpMatrixTimesScalar;
3709 break;
3710 case glslang::EOpMatrixTimesMatrix:
3711 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003712 binOp = spv::OpMatrixTimesMatrix;
3713 break;
3714 case glslang::EOpOuterProduct:
3715 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003716 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003717 break;
3718
3719 case glslang::EOpDiv:
3720 case glslang::EOpDivAssign:
3721 if (isFloat)
3722 binOp = spv::OpFDiv;
3723 else if (isUnsigned)
3724 binOp = spv::OpUDiv;
3725 else
3726 binOp = spv::OpSDiv;
3727 break;
3728 case glslang::EOpMod:
3729 case glslang::EOpModAssign:
3730 if (isFloat)
3731 binOp = spv::OpFMod;
3732 else if (isUnsigned)
3733 binOp = spv::OpUMod;
3734 else
3735 binOp = spv::OpSMod;
3736 break;
3737 case glslang::EOpRightShift:
3738 case glslang::EOpRightShiftAssign:
3739 if (isUnsigned)
3740 binOp = spv::OpShiftRightLogical;
3741 else
3742 binOp = spv::OpShiftRightArithmetic;
3743 break;
3744 case glslang::EOpLeftShift:
3745 case glslang::EOpLeftShiftAssign:
3746 binOp = spv::OpShiftLeftLogical;
3747 break;
3748 case glslang::EOpAnd:
3749 case glslang::EOpAndAssign:
3750 binOp = spv::OpBitwiseAnd;
3751 break;
3752 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003753 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003754 binOp = spv::OpLogicalAnd;
3755 break;
3756 case glslang::EOpInclusiveOr:
3757 case glslang::EOpInclusiveOrAssign:
3758 binOp = spv::OpBitwiseOr;
3759 break;
3760 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003761 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 binOp = spv::OpLogicalOr;
3763 break;
3764 case glslang::EOpExclusiveOr:
3765 case glslang::EOpExclusiveOrAssign:
3766 binOp = spv::OpBitwiseXor;
3767 break;
3768 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003769 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003770 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003771 break;
3772
3773 case glslang::EOpLessThan:
3774 case glslang::EOpGreaterThan:
3775 case glslang::EOpLessThanEqual:
3776 case glslang::EOpGreaterThanEqual:
3777 case glslang::EOpEqual:
3778 case glslang::EOpNotEqual:
3779 case glslang::EOpVectorEqual:
3780 case glslang::EOpVectorNotEqual:
3781 comparison = true;
3782 break;
3783 default:
3784 break;
3785 }
3786
John Kessenich7c1aa102015-10-15 13:29:11 -06003787 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003788 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003789 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003790 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003791 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003792
3793 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003794 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003795 builder.promoteScalar(precision, left, right);
3796
qining25262b32016-05-06 17:25:16 -04003797 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3798 addDecoration(result, noContraction);
3799 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003800 }
3801
3802 if (! comparison)
3803 return 0;
3804
John Kessenich7c1aa102015-10-15 13:29:11 -06003805 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003806
John Kessenich4583b612016-08-07 19:14:22 -06003807 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3808 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003809 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003810
3811 switch (op) {
3812 case glslang::EOpLessThan:
3813 if (isFloat)
3814 binOp = spv::OpFOrdLessThan;
3815 else if (isUnsigned)
3816 binOp = spv::OpULessThan;
3817 else
3818 binOp = spv::OpSLessThan;
3819 break;
3820 case glslang::EOpGreaterThan:
3821 if (isFloat)
3822 binOp = spv::OpFOrdGreaterThan;
3823 else if (isUnsigned)
3824 binOp = spv::OpUGreaterThan;
3825 else
3826 binOp = spv::OpSGreaterThan;
3827 break;
3828 case glslang::EOpLessThanEqual:
3829 if (isFloat)
3830 binOp = spv::OpFOrdLessThanEqual;
3831 else if (isUnsigned)
3832 binOp = spv::OpULessThanEqual;
3833 else
3834 binOp = spv::OpSLessThanEqual;
3835 break;
3836 case glslang::EOpGreaterThanEqual:
3837 if (isFloat)
3838 binOp = spv::OpFOrdGreaterThanEqual;
3839 else if (isUnsigned)
3840 binOp = spv::OpUGreaterThanEqual;
3841 else
3842 binOp = spv::OpSGreaterThanEqual;
3843 break;
3844 case glslang::EOpEqual:
3845 case glslang::EOpVectorEqual:
3846 if (isFloat)
3847 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003848 else if (isBool)
3849 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003850 else
3851 binOp = spv::OpIEqual;
3852 break;
3853 case glslang::EOpNotEqual:
3854 case glslang::EOpVectorNotEqual:
3855 if (isFloat)
3856 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003857 else if (isBool)
3858 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003859 else
3860 binOp = spv::OpINotEqual;
3861 break;
3862 default:
3863 break;
3864 }
3865
qining25262b32016-05-06 17:25:16 -04003866 if (binOp != spv::OpNop) {
3867 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3868 addDecoration(result, noContraction);
3869 return builder.setPrecision(result, precision);
3870 }
John Kessenich140f3df2015-06-26 16:58:36 -06003871
3872 return 0;
3873}
3874
John Kessenich04bb8a02015-12-12 12:28:14 -07003875//
3876// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3877// These can be any of:
3878//
3879// matrix * scalar
3880// scalar * matrix
3881// matrix * matrix linear algebraic
3882// matrix * vector
3883// vector * matrix
3884// matrix * matrix componentwise
3885// matrix op matrix op in {+, -, /}
3886// matrix op scalar op in {+, -, /}
3887// scalar op matrix op in {+, -, /}
3888//
qining25262b32016-05-06 17:25:16 -04003889spv::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 -07003890{
3891 bool firstClass = true;
3892
3893 // First, handle first-class matrix operations (* and matrix/scalar)
3894 switch (op) {
3895 case spv::OpFDiv:
3896 if (builder.isMatrix(left) && builder.isScalar(right)) {
3897 // turn matrix / scalar into a multiply...
3898 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3899 op = spv::OpMatrixTimesScalar;
3900 } else
3901 firstClass = false;
3902 break;
3903 case spv::OpMatrixTimesScalar:
3904 if (builder.isMatrix(right))
3905 std::swap(left, right);
3906 assert(builder.isScalar(right));
3907 break;
3908 case spv::OpVectorTimesMatrix:
3909 assert(builder.isVector(left));
3910 assert(builder.isMatrix(right));
3911 break;
3912 case spv::OpMatrixTimesVector:
3913 assert(builder.isMatrix(left));
3914 assert(builder.isVector(right));
3915 break;
3916 case spv::OpMatrixTimesMatrix:
3917 assert(builder.isMatrix(left));
3918 assert(builder.isMatrix(right));
3919 break;
3920 default:
3921 firstClass = false;
3922 break;
3923 }
3924
qining25262b32016-05-06 17:25:16 -04003925 if (firstClass) {
3926 spv::Id result = builder.createBinOp(op, typeId, left, right);
3927 addDecoration(result, noContraction);
3928 return builder.setPrecision(result, precision);
3929 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003930
LoopDawg592860c2016-06-09 08:57:35 -06003931 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003932 // The result type of all of them is the same type as the (a) matrix operand.
3933 // The algorithm is to:
3934 // - break the matrix(es) into vectors
3935 // - smear any scalar to a vector
3936 // - do vector operations
3937 // - make a matrix out the vector results
3938 switch (op) {
3939 case spv::OpFAdd:
3940 case spv::OpFSub:
3941 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003942 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003943 case spv::OpFMul:
3944 {
3945 // one time set up...
3946 bool leftMat = builder.isMatrix(left);
3947 bool rightMat = builder.isMatrix(right);
3948 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3949 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3950 spv::Id scalarType = builder.getScalarTypeId(typeId);
3951 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3952 std::vector<spv::Id> results;
3953 spv::Id smearVec = spv::NoResult;
3954 if (builder.isScalar(left))
3955 smearVec = builder.smearScalar(precision, left, vecType);
3956 else if (builder.isScalar(right))
3957 smearVec = builder.smearScalar(precision, right, vecType);
3958
3959 // do each vector op
3960 for (unsigned int c = 0; c < numCols; ++c) {
3961 std::vector<unsigned int> indexes;
3962 indexes.push_back(c);
3963 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3964 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003965 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3966 addDecoration(result, noContraction);
3967 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003968 }
3969
3970 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003971 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003972 }
3973 default:
3974 assert(0);
3975 return spv::NoResult;
3976 }
3977}
3978
qining25262b32016-05-06 17:25:16 -04003979spv::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 -06003980{
3981 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003982 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003983 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003984#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003985 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003986 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3987#else
Rex Xucabbb782017-03-24 13:41:14 +08003988 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003989 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003990#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003991
3992 switch (op) {
3993 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003994 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003995 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003996 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003997 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003998 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003999 unaryOp = spv::OpSNegate;
4000 break;
4001
4002 case glslang::EOpLogicalNot:
4003 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004004 unaryOp = spv::OpLogicalNot;
4005 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004006 case glslang::EOpBitwiseNot:
4007 unaryOp = spv::OpNot;
4008 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004009
John Kessenich140f3df2015-06-26 16:58:36 -06004010 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004011 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004012 break;
4013 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004015 break;
4016 case glslang::EOpTranspose:
4017 unaryOp = spv::OpTranspose;
4018 break;
4019
4020 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004021 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004022 break;
4023 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004024 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004025 break;
4026 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004027 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004028 break;
4029 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004030 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004031 break;
4032 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004033 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004034 break;
4035 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004036 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004037 break;
4038 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004039 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004040 break;
4041 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004042 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004043 break;
4044
4045 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004046 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004047 break;
4048 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004049 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004050 break;
4051 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004052 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004053 break;
4054 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004055 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004056 break;
4057 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004058 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004059 break;
4060 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004061 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004062 break;
4063
4064 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 break;
4067 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
4070
4071 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004072 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004073 break;
4074 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004075 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004076 break;
4077 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004079 break;
4080 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004081 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004082 break;
4083 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089
4090 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004091 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004092 break;
4093 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004094 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004095 break;
4096 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004100 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004101 break;
4102 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004103 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004104 break;
4105 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004106 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004107 break;
4108
4109 case glslang::EOpIsNan:
4110 unaryOp = spv::OpIsNan;
4111 break;
4112 case glslang::EOpIsInf:
4113 unaryOp = spv::OpIsInf;
4114 break;
LoopDawg592860c2016-06-09 08:57:35 -06004115 case glslang::EOpIsFinite:
4116 unaryOp = spv::OpIsFinite;
4117 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004118
Rex Xucbc426e2015-12-15 16:03:10 +08004119 case glslang::EOpFloatBitsToInt:
4120 case glslang::EOpFloatBitsToUint:
4121 case glslang::EOpIntBitsToFloat:
4122 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004123 case glslang::EOpDoubleBitsToInt64:
4124 case glslang::EOpDoubleBitsToUint64:
4125 case glslang::EOpInt64BitsToDouble:
4126 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004127#ifdef AMD_EXTENSIONS
4128 case glslang::EOpFloat16BitsToInt16:
4129 case glslang::EOpFloat16BitsToUint16:
4130 case glslang::EOpInt16BitsToFloat16:
4131 case glslang::EOpUint16BitsToFloat16:
4132#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004133 unaryOp = spv::OpBitcast;
4134 break;
4135
John Kessenich140f3df2015-06-26 16:58:36 -06004136 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004137 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004138 break;
4139 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004140 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004141 break;
4142 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004143 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004144 break;
4145 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004146 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004147 break;
4148 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004149 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004150 break;
4151 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004152 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004153 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004154 case glslang::EOpPackSnorm4x8:
4155 libCall = spv::GLSLstd450PackSnorm4x8;
4156 break;
4157 case glslang::EOpUnpackSnorm4x8:
4158 libCall = spv::GLSLstd450UnpackSnorm4x8;
4159 break;
4160 case glslang::EOpPackUnorm4x8:
4161 libCall = spv::GLSLstd450PackUnorm4x8;
4162 break;
4163 case glslang::EOpUnpackUnorm4x8:
4164 libCall = spv::GLSLstd450UnpackUnorm4x8;
4165 break;
4166 case glslang::EOpPackDouble2x32:
4167 libCall = spv::GLSLstd450PackDouble2x32;
4168 break;
4169 case glslang::EOpUnpackDouble2x32:
4170 libCall = spv::GLSLstd450UnpackDouble2x32;
4171 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004172
Rex Xu8ff43de2016-04-22 16:51:45 +08004173 case glslang::EOpPackInt2x32:
4174 case glslang::EOpUnpackInt2x32:
4175 case glslang::EOpPackUint2x32:
4176 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004177 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004178 break;
4179
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004180#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004181 case glslang::EOpPackInt2x16:
4182 case glslang::EOpUnpackInt2x16:
4183 case glslang::EOpPackUint2x16:
4184 case glslang::EOpUnpackUint2x16:
4185 case glslang::EOpPackInt4x16:
4186 case glslang::EOpUnpackInt4x16:
4187 case glslang::EOpPackUint4x16:
4188 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004189 case glslang::EOpPackFloat2x16:
4190 case glslang::EOpUnpackFloat2x16:
4191 unaryOp = spv::OpBitcast;
4192 break;
4193#endif
4194
John Kessenich140f3df2015-06-26 16:58:36 -06004195 case glslang::EOpDPdx:
4196 unaryOp = spv::OpDPdx;
4197 break;
4198 case glslang::EOpDPdy:
4199 unaryOp = spv::OpDPdy;
4200 break;
4201 case glslang::EOpFwidth:
4202 unaryOp = spv::OpFwidth;
4203 break;
4204 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004205 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004206 unaryOp = spv::OpDPdxFine;
4207 break;
4208 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004209 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004210 unaryOp = spv::OpDPdyFine;
4211 break;
4212 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004213 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004214 unaryOp = spv::OpFwidthFine;
4215 break;
4216 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004217 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004218 unaryOp = spv::OpDPdxCoarse;
4219 break;
4220 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004221 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004222 unaryOp = spv::OpDPdyCoarse;
4223 break;
4224 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004225 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004226 unaryOp = spv::OpFwidthCoarse;
4227 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004228 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004229 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004230 libCall = spv::GLSLstd450InterpolateAtCentroid;
4231 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004232 case glslang::EOpAny:
4233 unaryOp = spv::OpAny;
4234 break;
4235 case glslang::EOpAll:
4236 unaryOp = spv::OpAll;
4237 break;
4238
4239 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004240 if (isFloat)
4241 libCall = spv::GLSLstd450FAbs;
4242 else
4243 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004244 break;
4245 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004246 if (isFloat)
4247 libCall = spv::GLSLstd450FSign;
4248 else
4249 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004250 break;
4251
John Kessenichfc51d282015-08-19 13:34:18 -06004252 case glslang::EOpAtomicCounterIncrement:
4253 case glslang::EOpAtomicCounterDecrement:
4254 case glslang::EOpAtomicCounter:
4255 {
4256 // Handle all of the atomics in one place, in createAtomicOperation()
4257 std::vector<spv::Id> operands;
4258 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004259 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004260 }
4261
John Kessenichfc51d282015-08-19 13:34:18 -06004262 case glslang::EOpBitFieldReverse:
4263 unaryOp = spv::OpBitReverse;
4264 break;
4265 case glslang::EOpBitCount:
4266 unaryOp = spv::OpBitCount;
4267 break;
4268 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004269 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004270 break;
4271 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004272 if (isUnsigned)
4273 libCall = spv::GLSLstd450FindUMsb;
4274 else
4275 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004276 break;
4277
Rex Xu574ab042016-04-14 16:53:07 +08004278 case glslang::EOpBallot:
4279 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004280 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004281 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004282 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004283#ifdef AMD_EXTENSIONS
4284 case glslang::EOpMinInvocations:
4285 case glslang::EOpMaxInvocations:
4286 case glslang::EOpAddInvocations:
4287 case glslang::EOpMinInvocationsNonUniform:
4288 case glslang::EOpMaxInvocationsNonUniform:
4289 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004290 case glslang::EOpMinInvocationsInclusiveScan:
4291 case glslang::EOpMaxInvocationsInclusiveScan:
4292 case glslang::EOpAddInvocationsInclusiveScan:
4293 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4294 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4295 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4296 case glslang::EOpMinInvocationsExclusiveScan:
4297 case glslang::EOpMaxInvocationsExclusiveScan:
4298 case glslang::EOpAddInvocationsExclusiveScan:
4299 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4300 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4301 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004302#endif
Rex Xu51596642016-09-21 18:56:12 +08004303 {
4304 std::vector<spv::Id> operands;
4305 operands.push_back(operand);
4306 return createInvocationsOperation(op, typeId, operands, typeProxy);
4307 }
Rex Xu9d93a232016-05-05 12:30:44 +08004308
4309#ifdef AMD_EXTENSIONS
4310 case glslang::EOpMbcnt:
4311 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4312 libCall = spv::MbcntAMD;
4313 break;
4314
4315 case glslang::EOpCubeFaceIndex:
4316 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4317 libCall = spv::CubeFaceIndexAMD;
4318 break;
4319
4320 case glslang::EOpCubeFaceCoord:
4321 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4322 libCall = spv::CubeFaceCoordAMD;
4323 break;
4324#endif
Rex Xu338b1852016-05-05 20:38:33 +08004325
John Kessenich140f3df2015-06-26 16:58:36 -06004326 default:
4327 return 0;
4328 }
4329
4330 spv::Id id;
4331 if (libCall >= 0) {
4332 std::vector<spv::Id> args;
4333 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004334 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004335 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004336 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004337 }
John Kessenich140f3df2015-06-26 16:58:36 -06004338
qining25262b32016-05-06 17:25:16 -04004339 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004340 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004341}
4342
John Kessenich7a53f762016-01-20 11:19:27 -07004343// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004344spv::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 -07004345{
4346 // Handle unary operations vector by vector.
4347 // The result type is the same type as the original type.
4348 // The algorithm is to:
4349 // - break the matrix into vectors
4350 // - apply the operation to each vector
4351 // - make a matrix out the vector results
4352
4353 // get the types sorted out
4354 int numCols = builder.getNumColumns(operand);
4355 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004356 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4357 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004358 std::vector<spv::Id> results;
4359
4360 // do each vector op
4361 for (int c = 0; c < numCols; ++c) {
4362 std::vector<unsigned int> indexes;
4363 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004364 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4365 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4366 addDecoration(destVec, noContraction);
4367 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004368 }
4369
4370 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004371 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004372}
4373
Rex Xu73e3ce72016-04-27 18:48:17 +08004374spv::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 -06004375{
4376 spv::Op convOp = spv::OpNop;
4377 spv::Id zero = 0;
4378 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004379 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004380
4381 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4382
4383 switch (op) {
4384 case glslang::EOpConvIntToBool:
4385 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004386 case glslang::EOpConvInt64ToBool:
4387 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004388#ifdef AMD_EXTENSIONS
4389 case glslang::EOpConvInt16ToBool:
4390 case glslang::EOpConvUint16ToBool:
4391#endif
4392 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4393 zero = builder.makeUint64Constant(0);
4394#ifdef AMD_EXTENSIONS
4395 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4396 zero = builder.makeUint16Constant(0);
4397#endif
4398 else
4399 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004400 zero = makeSmearedConstant(zero, vectorSize);
4401 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4402
4403 case glslang::EOpConvFloatToBool:
4404 zero = builder.makeFloatConstant(0.0F);
4405 zero = makeSmearedConstant(zero, vectorSize);
4406 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4407
4408 case glslang::EOpConvDoubleToBool:
4409 zero = builder.makeDoubleConstant(0.0);
4410 zero = makeSmearedConstant(zero, vectorSize);
4411 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4412
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004413#ifdef AMD_EXTENSIONS
4414 case glslang::EOpConvFloat16ToBool:
4415 zero = builder.makeFloat16Constant(0.0F);
4416 zero = makeSmearedConstant(zero, vectorSize);
4417 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4418#endif
4419
John Kessenich140f3df2015-06-26 16:58:36 -06004420 case glslang::EOpConvBoolToFloat:
4421 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004422 zero = builder.makeFloatConstant(0.0F);
4423 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004424 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004425
John Kessenich140f3df2015-06-26 16:58:36 -06004426 case glslang::EOpConvBoolToDouble:
4427 convOp = spv::OpSelect;
4428 zero = builder.makeDoubleConstant(0.0);
4429 one = builder.makeDoubleConstant(1.0);
4430 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004431
4432#ifdef AMD_EXTENSIONS
4433 case glslang::EOpConvBoolToFloat16:
4434 convOp = spv::OpSelect;
4435 zero = builder.makeFloat16Constant(0.0F);
4436 one = builder.makeFloat16Constant(1.0F);
4437 break;
4438#endif
4439
John Kessenich140f3df2015-06-26 16:58:36 -06004440 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004441 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004442#ifdef AMD_EXTENSIONS
4443 case glslang::EOpConvBoolToInt16:
4444#endif
4445 if (op == glslang::EOpConvBoolToInt64)
4446 zero = builder.makeInt64Constant(0);
4447#ifdef AMD_EXTENSIONS
4448 else if (op == glslang::EOpConvBoolToInt16)
4449 zero = builder.makeInt16Constant(0);
4450#endif
4451 else
4452 zero = builder.makeIntConstant(0);
4453
4454 if (op == glslang::EOpConvBoolToInt64)
4455 one = builder.makeInt64Constant(1);
4456#ifdef AMD_EXTENSIONS
4457 else if (op == glslang::EOpConvBoolToInt16)
4458 one = builder.makeInt16Constant(1);
4459#endif
4460 else
4461 one = builder.makeIntConstant(1);
4462
John Kessenich140f3df2015-06-26 16:58:36 -06004463 convOp = spv::OpSelect;
4464 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004465
John Kessenich140f3df2015-06-26 16:58:36 -06004466 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004467 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004468#ifdef AMD_EXTENSIONS
4469 case glslang::EOpConvBoolToUint16:
4470#endif
4471 if (op == glslang::EOpConvBoolToUint64)
4472 zero = builder.makeUint64Constant(0);
4473#ifdef AMD_EXTENSIONS
4474 else if (op == glslang::EOpConvBoolToUint16)
4475 zero = builder.makeUint16Constant(0);
4476#endif
4477 else
4478 zero = builder.makeUintConstant(0);
4479
4480 if (op == glslang::EOpConvBoolToUint64)
4481 one = builder.makeUint64Constant(1);
4482#ifdef AMD_EXTENSIONS
4483 else if (op == glslang::EOpConvBoolToUint16)
4484 one = builder.makeUint16Constant(1);
4485#endif
4486 else
4487 one = builder.makeUintConstant(1);
4488
John Kessenich140f3df2015-06-26 16:58:36 -06004489 convOp = spv::OpSelect;
4490 break;
4491
4492 case glslang::EOpConvIntToFloat:
4493 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004494 case glslang::EOpConvInt64ToFloat:
4495 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004496#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004497 case glslang::EOpConvInt16ToFloat:
4498 case glslang::EOpConvInt16ToDouble:
4499 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004500 case glslang::EOpConvIntToFloat16:
4501 case glslang::EOpConvInt64ToFloat16:
4502#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004503 convOp = spv::OpConvertSToF;
4504 break;
4505
4506 case glslang::EOpConvUintToFloat:
4507 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004508 case glslang::EOpConvUint64ToFloat:
4509 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004510#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004511 case glslang::EOpConvUint16ToFloat:
4512 case glslang::EOpConvUint16ToDouble:
4513 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004514 case glslang::EOpConvUintToFloat16:
4515 case glslang::EOpConvUint64ToFloat16:
4516#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004517 convOp = spv::OpConvertUToF;
4518 break;
4519
4520 case glslang::EOpConvDoubleToFloat:
4521 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004522#ifdef AMD_EXTENSIONS
4523 case glslang::EOpConvDoubleToFloat16:
4524 case glslang::EOpConvFloat16ToDouble:
4525 case glslang::EOpConvFloatToFloat16:
4526 case glslang::EOpConvFloat16ToFloat:
4527#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004528 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004529 if (builder.isMatrixType(destType))
4530 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004531 break;
4532
4533 case glslang::EOpConvFloatToInt:
4534 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004535 case glslang::EOpConvFloatToInt64:
4536 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004537#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004538 case glslang::EOpConvFloatToInt16:
4539 case glslang::EOpConvDoubleToInt16:
4540 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004541 case glslang::EOpConvFloat16ToInt:
4542 case glslang::EOpConvFloat16ToInt64:
4543#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004544 convOp = spv::OpConvertFToS;
4545 break;
4546
4547 case glslang::EOpConvUintToInt:
4548 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004549 case glslang::EOpConvUint64ToInt64:
4550 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004551#ifdef AMD_EXTENSIONS
4552 case glslang::EOpConvUint16ToInt16:
4553 case glslang::EOpConvInt16ToUint16:
4554#endif
qininge24aa5e2016-04-07 15:40:27 -04004555 if (builder.isInSpecConstCodeGenMode()) {
4556 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004557 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4558 zero = builder.makeUint64Constant(0);
4559#ifdef AMD_EXTENSIONS
4560 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4561 zero = builder.makeUint16Constant(0);
4562#endif
4563 else
4564 zero = builder.makeUintConstant(0);
4565
qining189b2032016-04-12 23:16:20 -04004566 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004567 // Use OpIAdd, instead of OpBitcast to do the conversion when
4568 // generating for OpSpecConstantOp instruction.
4569 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4570 }
4571 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004572 convOp = spv::OpBitcast;
4573 break;
4574
4575 case glslang::EOpConvFloatToUint:
4576 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004577 case glslang::EOpConvFloatToUint64:
4578 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004579#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004580 case glslang::EOpConvFloatToUint16:
4581 case glslang::EOpConvDoubleToUint16:
4582 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004583 case glslang::EOpConvFloat16ToUint:
4584 case glslang::EOpConvFloat16ToUint64:
4585#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004586 convOp = spv::OpConvertFToU;
4587 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004588
4589 case glslang::EOpConvIntToInt64:
4590 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004591#ifdef AMD_EXTENSIONS
4592 case glslang::EOpConvIntToInt16:
4593 case glslang::EOpConvInt16ToInt:
4594 case glslang::EOpConvInt64ToInt16:
4595 case glslang::EOpConvInt16ToInt64:
4596#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004597 convOp = spv::OpSConvert;
4598 break;
4599
4600 case glslang::EOpConvUintToUint64:
4601 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004602#ifdef AMD_EXTENSIONS
4603 case glslang::EOpConvUintToUint16:
4604 case glslang::EOpConvUint16ToUint:
4605 case glslang::EOpConvUint64ToUint16:
4606 case glslang::EOpConvUint16ToUint64:
4607#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004608 convOp = spv::OpUConvert;
4609 break;
4610
4611 case glslang::EOpConvIntToUint64:
4612 case glslang::EOpConvInt64ToUint:
4613 case glslang::EOpConvUint64ToInt:
4614 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004615#ifdef AMD_EXTENSIONS
4616 case glslang::EOpConvInt16ToUint:
4617 case glslang::EOpConvUintToInt16:
4618 case glslang::EOpConvInt16ToUint64:
4619 case glslang::EOpConvUint64ToInt16:
4620 case glslang::EOpConvUint16ToInt:
4621 case glslang::EOpConvIntToUint16:
4622 case glslang::EOpConvUint16ToInt64:
4623 case glslang::EOpConvInt64ToUint16:
4624#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004625 // OpSConvert/OpUConvert + OpBitCast
4626 switch (op) {
4627 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004628#ifdef AMD_EXTENSIONS
4629 case glslang::EOpConvInt16ToUint64:
4630#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004631 convOp = spv::OpSConvert;
4632 type = builder.makeIntType(64);
4633 break;
4634 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004635#ifdef AMD_EXTENSIONS
4636 case glslang::EOpConvInt16ToUint:
4637#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004638 convOp = spv::OpSConvert;
4639 type = builder.makeIntType(32);
4640 break;
4641 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004642#ifdef AMD_EXTENSIONS
4643 case glslang::EOpConvUint16ToInt:
4644#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004645 convOp = spv::OpUConvert;
4646 type = builder.makeUintType(32);
4647 break;
4648 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004649#ifdef AMD_EXTENSIONS
4650 case glslang::EOpConvUint16ToInt64:
4651#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004652 convOp = spv::OpUConvert;
4653 type = builder.makeUintType(64);
4654 break;
Rex Xucabbb782017-03-24 13:41:14 +08004655#ifdef AMD_EXTENSIONS
4656 case glslang::EOpConvUintToInt16:
4657 case glslang::EOpConvUint64ToInt16:
4658 convOp = spv::OpUConvert;
4659 type = builder.makeUintType(16);
4660 break;
4661 case glslang::EOpConvIntToUint16:
4662 case glslang::EOpConvInt64ToUint16:
4663 convOp = spv::OpSConvert;
4664 type = builder.makeIntType(16);
4665 break;
4666#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004667 default:
4668 assert(0);
4669 break;
4670 }
4671
4672 if (vectorSize > 0)
4673 type = builder.makeVectorType(type, vectorSize);
4674
4675 operand = builder.createUnaryOp(convOp, type, operand);
4676
4677 if (builder.isInSpecConstCodeGenMode()) {
4678 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004679#ifdef AMD_EXTENSIONS
4680 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4681 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4682 zero = builder.makeUint64Constant(0);
4683 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4684 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4685 zero = builder.makeUint16Constant(0);
4686 else
4687 zero = builder.makeUintConstant(0);
4688#else
4689 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4690 zero = builder.makeUint64Constant(0);
4691 else
4692 zero = builder.makeUintConstant(0);
4693#endif
4694
Rex Xu8ff43de2016-04-22 16:51:45 +08004695 zero = makeSmearedConstant(zero, vectorSize);
4696 // Use OpIAdd, instead of OpBitcast to do the conversion when
4697 // generating for OpSpecConstantOp instruction.
4698 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4699 }
4700 // For normal run-time conversion instruction, use OpBitcast.
4701 convOp = spv::OpBitcast;
4702 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004703 default:
4704 break;
4705 }
4706
4707 spv::Id result = 0;
4708 if (convOp == spv::OpNop)
4709 return result;
4710
4711 if (convOp == spv::OpSelect) {
4712 zero = makeSmearedConstant(zero, vectorSize);
4713 one = makeSmearedConstant(one, vectorSize);
4714 result = builder.createTriOp(convOp, destType, operand, one, zero);
4715 } else
4716 result = builder.createUnaryOp(convOp, destType, operand);
4717
John Kessenich32cfd492016-02-02 12:37:46 -07004718 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004719}
4720
4721spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4722{
4723 if (vectorSize == 0)
4724 return constant;
4725
4726 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4727 std::vector<spv::Id> components;
4728 for (int c = 0; c < vectorSize; ++c)
4729 components.push_back(constant);
4730 return builder.makeCompositeConstant(vectorTypeId, components);
4731}
4732
John Kessenich426394d2015-07-23 10:22:48 -06004733// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004734spv::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 -06004735{
4736 spv::Op opCode = spv::OpNop;
4737
4738 switch (op) {
4739 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004740 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004741 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004742 opCode = spv::OpAtomicIAdd;
4743 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004744 case glslang::EOpAtomicCounterSubtract:
4745 opCode = spv::OpAtomicISub;
4746 break;
John Kessenich426394d2015-07-23 10:22:48 -06004747 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004748 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004749 case glslang::EOpAtomicCounterMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004750 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004751 break;
4752 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004753 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004754 case glslang::EOpAtomicCounterMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004755 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004756 break;
4757 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004758 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004759 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004760 opCode = spv::OpAtomicAnd;
4761 break;
4762 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004763 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004764 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004765 opCode = spv::OpAtomicOr;
4766 break;
4767 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004768 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004769 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004770 opCode = spv::OpAtomicXor;
4771 break;
4772 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004773 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004774 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004775 opCode = spv::OpAtomicExchange;
4776 break;
4777 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004778 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004779 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004780 opCode = spv::OpAtomicCompareExchange;
4781 break;
4782 case glslang::EOpAtomicCounterIncrement:
4783 opCode = spv::OpAtomicIIncrement;
4784 break;
4785 case glslang::EOpAtomicCounterDecrement:
4786 opCode = spv::OpAtomicIDecrement;
4787 break;
4788 case glslang::EOpAtomicCounter:
4789 opCode = spv::OpAtomicLoad;
4790 break;
4791 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004792 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004793 break;
4794 }
4795
4796 // Sort out the operands
4797 // - mapping from glslang -> SPV
4798 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004799 // - compare-exchange swaps the value and comparator
4800 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004801 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4802 auto opIt = operands.begin(); // walk the glslang operands
4803 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004804 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4805 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4806 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004807 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4808 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004809 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004810 spvAtomicOperands.push_back(*(opIt + 1));
4811 spvAtomicOperands.push_back(*opIt);
4812 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004813 }
John Kessenich426394d2015-07-23 10:22:48 -06004814
John Kessenich3e60a6f2015-09-14 22:45:16 -06004815 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004816 for (; opIt != operands.end(); ++opIt)
4817 spvAtomicOperands.push_back(*opIt);
4818
4819 return builder.createOp(opCode, typeId, spvAtomicOperands);
4820}
4821
John Kessenich91cef522016-05-05 16:45:40 -06004822// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004823spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004824{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004825#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004826 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004827 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004828#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004829
Rex Xu51596642016-09-21 18:56:12 +08004830 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004831 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004832 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4833
chaocf200da82016-12-20 12:44:35 -08004834 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4835 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004836 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4837 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004838 } else if (op == glslang::EOpAnyInvocation ||
4839 op == glslang::EOpAllInvocations ||
4840 op == glslang::EOpAllInvocationsEqual) {
4841 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4842 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004843 } else {
4844 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004845#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004846 if (op == glslang::EOpMinInvocationsNonUniform ||
4847 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004848 op == glslang::EOpAddInvocationsNonUniform ||
4849 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4850 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4851 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4852 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4853 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4854 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004855 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004856#endif
Rex Xu51596642016-09-21 18:56:12 +08004857
4858 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004859#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004860 switch (op) {
4861 case glslang::EOpMinInvocations:
4862 case glslang::EOpMaxInvocations:
4863 case glslang::EOpAddInvocations:
4864 case glslang::EOpMinInvocationsNonUniform:
4865 case glslang::EOpMaxInvocationsNonUniform:
4866 case glslang::EOpAddInvocationsNonUniform:
4867 groupOperation = spv::GroupOperationReduce;
4868 spvGroupOperands.push_back(groupOperation);
4869 break;
4870 case glslang::EOpMinInvocationsInclusiveScan:
4871 case glslang::EOpMaxInvocationsInclusiveScan:
4872 case glslang::EOpAddInvocationsInclusiveScan:
4873 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4874 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4875 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4876 groupOperation = spv::GroupOperationInclusiveScan;
4877 spvGroupOperands.push_back(groupOperation);
4878 break;
4879 case glslang::EOpMinInvocationsExclusiveScan:
4880 case glslang::EOpMaxInvocationsExclusiveScan:
4881 case glslang::EOpAddInvocationsExclusiveScan:
4882 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4883 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4884 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4885 groupOperation = spv::GroupOperationExclusiveScan;
4886 spvGroupOperands.push_back(groupOperation);
4887 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004888 default:
4889 break;
Rex Xu430ef402016-10-14 17:22:23 +08004890 }
Rex Xu9d93a232016-05-05 12:30:44 +08004891#endif
Rex Xu51596642016-09-21 18:56:12 +08004892 }
4893
4894 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4895 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004896
4897 switch (op) {
4898 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004899 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004900 break;
John Kessenich91cef522016-05-05 16:45:40 -06004901 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004902 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004903 break;
John Kessenich91cef522016-05-05 16:45:40 -06004904 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004905 opCode = spv::OpSubgroupAllEqualKHR;
4906 break;
Rex Xu51596642016-09-21 18:56:12 +08004907 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004908 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004909 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004910 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004911 break;
4912 case glslang::EOpReadFirstInvocation:
4913 opCode = spv::OpSubgroupFirstInvocationKHR;
4914 break;
4915 case glslang::EOpBallot:
4916 {
4917 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4918 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4919 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4920 //
4921 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4922 //
4923 spv::Id uintType = builder.makeUintType(32);
4924 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4925 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4926
4927 std::vector<spv::Id> components;
4928 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4929 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4930
4931 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4932 return builder.createUnaryOp(spv::OpBitcast, typeId,
4933 builder.createCompositeConstruct(uvec2Type, components));
4934 }
4935
Rex Xu9d93a232016-05-05 12:30:44 +08004936#ifdef AMD_EXTENSIONS
4937 case glslang::EOpMinInvocations:
4938 case glslang::EOpMaxInvocations:
4939 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004940 case glslang::EOpMinInvocationsInclusiveScan:
4941 case glslang::EOpMaxInvocationsInclusiveScan:
4942 case glslang::EOpAddInvocationsInclusiveScan:
4943 case glslang::EOpMinInvocationsExclusiveScan:
4944 case glslang::EOpMaxInvocationsExclusiveScan:
4945 case glslang::EOpAddInvocationsExclusiveScan:
4946 if (op == glslang::EOpMinInvocations ||
4947 op == glslang::EOpMinInvocationsInclusiveScan ||
4948 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004949 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004950 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004951 else {
4952 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004953 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004954 else
Rex Xu51596642016-09-21 18:56:12 +08004955 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004956 }
Rex Xu430ef402016-10-14 17:22:23 +08004957 } else if (op == glslang::EOpMaxInvocations ||
4958 op == glslang::EOpMaxInvocationsInclusiveScan ||
4959 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004960 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004961 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004962 else {
4963 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004964 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004965 else
Rex Xu51596642016-09-21 18:56:12 +08004966 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004967 }
4968 } else {
4969 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004970 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004971 else
Rex Xu51596642016-09-21 18:56:12 +08004972 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004973 }
4974
Rex Xu2bbbe062016-08-23 15:41:05 +08004975 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004976 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004977
4978 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004979 case glslang::EOpMinInvocationsNonUniform:
4980 case glslang::EOpMaxInvocationsNonUniform:
4981 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004982 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4983 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4984 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4985 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4986 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4987 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4988 if (op == glslang::EOpMinInvocationsNonUniform ||
4989 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4990 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004991 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004992 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004993 else {
4994 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004995 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004996 else
Rex Xu51596642016-09-21 18:56:12 +08004997 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004998 }
4999 }
Rex Xu430ef402016-10-14 17:22:23 +08005000 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5001 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5002 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005003 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005004 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005005 else {
5006 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005007 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005008 else
Rex Xu51596642016-09-21 18:56:12 +08005009 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005010 }
5011 }
5012 else {
5013 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005014 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005015 else
Rex Xu51596642016-09-21 18:56:12 +08005016 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005017 }
5018
Rex Xu2bbbe062016-08-23 15:41:05 +08005019 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005020 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005021
5022 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005023#endif
John Kessenich91cef522016-05-05 16:45:40 -06005024 default:
5025 logger->missingFunctionality("invocation operation");
5026 return spv::NoResult;
5027 }
Rex Xu51596642016-09-21 18:56:12 +08005028
5029 assert(opCode != spv::OpNop);
5030 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005031}
5032
Rex Xu2bbbe062016-08-23 15:41:05 +08005033// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005034spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005035{
Rex Xub7072052016-09-26 15:53:40 +08005036#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005037 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5038 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005039 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005040 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005041 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5042 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5043 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005044#else
5045 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5046 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005047 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5048 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005049#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005050
5051 // Handle group invocation operations scalar by scalar.
5052 // The result type is the same type as the original type.
5053 // The algorithm is to:
5054 // - break the vector into scalars
5055 // - apply the operation to each scalar
5056 // - make a vector out the scalar results
5057
5058 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005059 int numComponents = builder.getNumComponents(operands[0]);
5060 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005061 std::vector<spv::Id> results;
5062
5063 // do each scalar op
5064 for (int comp = 0; comp < numComponents; ++comp) {
5065 std::vector<unsigned int> indexes;
5066 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005067 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005068 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005069 if (op == spv::OpSubgroupReadInvocationKHR) {
5070 spvGroupOperands.push_back(scalar);
5071 spvGroupOperands.push_back(operands[1]);
5072 } else if (op == spv::OpGroupBroadcast) {
5073 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005074 spvGroupOperands.push_back(scalar);
5075 spvGroupOperands.push_back(operands[1]);
5076 } else {
chaocf200da82016-12-20 12:44:35 -08005077 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005078 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005079 spvGroupOperands.push_back(scalar);
5080 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005081
Rex Xub7072052016-09-26 15:53:40 +08005082 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005083 }
5084
5085 // put the pieces together
5086 return builder.createCompositeConstruct(typeId, results);
5087}
Rex Xu2bbbe062016-08-23 15:41:05 +08005088
John Kessenich5e4b1242015-08-06 22:53:06 -06005089spv::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 -06005090{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005091#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005092 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005093 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5094#else
Rex Xucabbb782017-03-24 13:41:14 +08005095 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005096 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005097#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005098
John Kessenich140f3df2015-06-26 16:58:36 -06005099 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005100 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005101 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005102 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005103 spv::Id typeId0 = 0;
5104 if (consumedOperands > 0)
5105 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005106 spv::Id typeId1 = 0;
5107 if (consumedOperands > 1)
5108 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005109 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005110
5111 switch (op) {
5112 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005113 if (isFloat)
5114 libCall = spv::GLSLstd450FMin;
5115 else if (isUnsigned)
5116 libCall = spv::GLSLstd450UMin;
5117 else
5118 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005119 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005120 break;
5121 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005122 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005123 break;
5124 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005125 if (isFloat)
5126 libCall = spv::GLSLstd450FMax;
5127 else if (isUnsigned)
5128 libCall = spv::GLSLstd450UMax;
5129 else
5130 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005131 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005132 break;
5133 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005134 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005135 break;
5136 case glslang::EOpDot:
5137 opCode = spv::OpDot;
5138 break;
5139 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005140 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005141 break;
5142
5143 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005144 if (isFloat)
5145 libCall = spv::GLSLstd450FClamp;
5146 else if (isUnsigned)
5147 libCall = spv::GLSLstd450UClamp;
5148 else
5149 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005150 builder.promoteScalar(precision, operands.front(), operands[1]);
5151 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005152 break;
5153 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005154 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5155 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005156 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005157 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005158 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005159 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005160 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005161 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005162 break;
5163 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005164 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005165 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005166 break;
5167 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005168 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005169 builder.promoteScalar(precision, operands[0], operands[2]);
5170 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005171 break;
5172
5173 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005174 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005175 break;
5176 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005177 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005178 break;
5179 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005180 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005181 break;
5182 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005183 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005184 break;
5185 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005186 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005187 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005188 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005189 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005190 libCall = spv::GLSLstd450InterpolateAtSample;
5191 break;
5192 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005193 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005194 libCall = spv::GLSLstd450InterpolateAtOffset;
5195 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005196 case glslang::EOpAddCarry:
5197 opCode = spv::OpIAddCarry;
5198 typeId = builder.makeStructResultType(typeId0, typeId0);
5199 consumedOperands = 2;
5200 break;
5201 case glslang::EOpSubBorrow:
5202 opCode = spv::OpISubBorrow;
5203 typeId = builder.makeStructResultType(typeId0, typeId0);
5204 consumedOperands = 2;
5205 break;
5206 case glslang::EOpUMulExtended:
5207 opCode = spv::OpUMulExtended;
5208 typeId = builder.makeStructResultType(typeId0, typeId0);
5209 consumedOperands = 2;
5210 break;
5211 case glslang::EOpIMulExtended:
5212 opCode = spv::OpSMulExtended;
5213 typeId = builder.makeStructResultType(typeId0, typeId0);
5214 consumedOperands = 2;
5215 break;
5216 case glslang::EOpBitfieldExtract:
5217 if (isUnsigned)
5218 opCode = spv::OpBitFieldUExtract;
5219 else
5220 opCode = spv::OpBitFieldSExtract;
5221 break;
5222 case glslang::EOpBitfieldInsert:
5223 opCode = spv::OpBitFieldInsert;
5224 break;
5225
5226 case glslang::EOpFma:
5227 libCall = spv::GLSLstd450Fma;
5228 break;
5229 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005230 {
5231 libCall = spv::GLSLstd450FrexpStruct;
5232 assert(builder.isPointerType(typeId1));
5233 typeId1 = builder.getContainedTypeId(typeId1);
5234#ifdef AMD_EXTENSIONS
5235 int width = builder.getScalarTypeWidth(typeId1);
5236#else
5237 int width = 32;
5238#endif
5239 if (builder.getNumComponents(operands[0]) == 1)
5240 frexpIntType = builder.makeIntegerType(width, true);
5241 else
5242 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5243 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5244 consumedOperands = 1;
5245 }
John Kessenich55e7d112015-11-15 21:33:39 -07005246 break;
5247 case glslang::EOpLdexp:
5248 libCall = spv::GLSLstd450Ldexp;
5249 break;
5250
Rex Xu574ab042016-04-14 16:53:07 +08005251 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005252 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005253
Rex Xu9d93a232016-05-05 12:30:44 +08005254#ifdef AMD_EXTENSIONS
5255 case glslang::EOpSwizzleInvocations:
5256 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5257 libCall = spv::SwizzleInvocationsAMD;
5258 break;
5259 case glslang::EOpSwizzleInvocationsMasked:
5260 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5261 libCall = spv::SwizzleInvocationsMaskedAMD;
5262 break;
5263 case glslang::EOpWriteInvocation:
5264 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5265 libCall = spv::WriteInvocationAMD;
5266 break;
5267
5268 case glslang::EOpMin3:
5269 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5270 if (isFloat)
5271 libCall = spv::FMin3AMD;
5272 else {
5273 if (isUnsigned)
5274 libCall = spv::UMin3AMD;
5275 else
5276 libCall = spv::SMin3AMD;
5277 }
5278 break;
5279 case glslang::EOpMax3:
5280 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5281 if (isFloat)
5282 libCall = spv::FMax3AMD;
5283 else {
5284 if (isUnsigned)
5285 libCall = spv::UMax3AMD;
5286 else
5287 libCall = spv::SMax3AMD;
5288 }
5289 break;
5290 case glslang::EOpMid3:
5291 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5292 if (isFloat)
5293 libCall = spv::FMid3AMD;
5294 else {
5295 if (isUnsigned)
5296 libCall = spv::UMid3AMD;
5297 else
5298 libCall = spv::SMid3AMD;
5299 }
5300 break;
5301
5302 case glslang::EOpInterpolateAtVertex:
5303 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5304 libCall = spv::InterpolateAtVertexAMD;
5305 break;
5306#endif
5307
John Kessenich140f3df2015-06-26 16:58:36 -06005308 default:
5309 return 0;
5310 }
5311
5312 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005313 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005314 // Use an extended instruction from the standard library.
5315 // Construct the call arguments, without modifying the original operands vector.
5316 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5317 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005318 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005319 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005320 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005321 case 0:
5322 // should all be handled by visitAggregate and createNoArgOperation
5323 assert(0);
5324 return 0;
5325 case 1:
5326 // should all be handled by createUnaryOperation
5327 assert(0);
5328 return 0;
5329 case 2:
5330 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5331 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005332 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005333 // anything 3 or over doesn't have l-value operands, so all should be consumed
5334 assert(consumedOperands == operands.size());
5335 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005336 break;
5337 }
5338 }
5339
John Kessenich55e7d112015-11-15 21:33:39 -07005340 // Decode the return types that were structures
5341 switch (op) {
5342 case glslang::EOpAddCarry:
5343 case glslang::EOpSubBorrow:
5344 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5345 id = builder.createCompositeExtract(id, typeId0, 0);
5346 break;
5347 case glslang::EOpUMulExtended:
5348 case glslang::EOpIMulExtended:
5349 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5350 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5351 break;
5352 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005353 {
5354 assert(operands.size() == 2);
5355 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5356 // "exp" is floating-point type (from HLSL intrinsic)
5357 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5358 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5359 builder.createStore(member1, operands[1]);
5360 } else
5361 // "exp" is integer type (from GLSL built-in function)
5362 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5363 id = builder.createCompositeExtract(id, typeId0, 0);
5364 }
John Kessenich55e7d112015-11-15 21:33:39 -07005365 break;
5366 default:
5367 break;
5368 }
5369
John Kessenich32cfd492016-02-02 12:37:46 -07005370 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005371}
5372
Rex Xu9d93a232016-05-05 12:30:44 +08005373// Intrinsics with no arguments (or no return value, and no precision).
5374spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005375{
5376 // TODO: get the barrier operands correct
5377
5378 switch (op) {
5379 case glslang::EOpEmitVertex:
5380 builder.createNoResultOp(spv::OpEmitVertex);
5381 return 0;
5382 case glslang::EOpEndPrimitive:
5383 builder.createNoResultOp(spv::OpEndPrimitive);
5384 return 0;
5385 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005386 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005387 return 0;
5388 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005389 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005390 return 0;
5391 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005392 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005393 return 0;
5394 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005395 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005396 return 0;
5397 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005398 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005399 return 0;
5400 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005401 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005402 return 0;
5403 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005404 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005405 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005406 case glslang::EOpAllMemoryBarrierWithGroupSync:
5407 // Control barrier with non-"None" semantic is also a memory barrier.
5408 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5409 return 0;
5410 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5411 // Control barrier with non-"None" semantic is also a memory barrier.
5412 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5413 return 0;
5414 case glslang::EOpWorkgroupMemoryBarrier:
5415 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5416 return 0;
5417 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5418 // Control barrier with non-"None" semantic is also a memory barrier.
5419 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5420 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005421#ifdef AMD_EXTENSIONS
5422 case glslang::EOpTime:
5423 {
5424 std::vector<spv::Id> args; // Dummy arguments
5425 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5426 return builder.setPrecision(id, precision);
5427 }
5428#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005429 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005430 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005431 return 0;
5432 }
5433}
5434
5435spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5436{
John Kessenich2f273362015-07-18 22:34:27 -06005437 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005438 spv::Id id;
5439 if (symbolValues.end() != iter) {
5440 id = iter->second;
5441 return id;
5442 }
5443
5444 // it was not found, create it
5445 id = createSpvVariable(symbol);
5446 symbolValues[symbol->getId()] = id;
5447
Rex Xuc884b4a2016-06-29 15:03:44 +08005448 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005449 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005450 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005451 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005452 if (symbol->getType().getQualifier().hasSpecConstantId())
5453 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005454 if (symbol->getQualifier().hasIndex())
5455 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5456 if (symbol->getQualifier().hasComponent())
5457 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5458 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005459 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005460 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005461 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005462 if (symbol->getQualifier().hasXfbBuffer())
5463 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5464 if (symbol->getQualifier().hasXfbOffset())
5465 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5466 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005467 // atomic counters use this:
5468 if (symbol->getQualifier().hasOffset())
5469 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005470 }
5471
scygan2c864272016-05-18 18:09:17 +02005472 if (symbol->getQualifier().hasLocation())
5473 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005474 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005475 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005476 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005477 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005478 }
John Kessenich140f3df2015-06-26 16:58:36 -06005479 if (symbol->getQualifier().hasSet())
5480 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005481 else if (IsDescriptorResource(symbol->getType())) {
5482 // default to 0
5483 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5484 }
John Kessenich140f3df2015-06-26 16:58:36 -06005485 if (symbol->getQualifier().hasBinding())
5486 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005487 if (symbol->getQualifier().hasAttachment())
5488 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005489 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005490 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005491 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005492 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005493 if (symbol->getQualifier().hasXfbBuffer())
5494 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5495 }
5496
Rex Xu1da878f2016-02-21 20:59:01 +08005497 if (symbol->getType().isImage()) {
5498 std::vector<spv::Decoration> memory;
5499 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5500 for (unsigned int i = 0; i < memory.size(); ++i)
5501 addDecoration(id, memory[i]);
5502 }
5503
John Kessenich140f3df2015-06-26 16:58:36 -06005504 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005505 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005506 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005507 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005508
John Kessenichecba76f2017-01-06 00:34:48 -07005509#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005510 if (builtIn == spv::BuiltInSampleMask) {
5511 spv::Decoration decoration;
5512 // GL_NV_sample_mask_override_coverage extension
5513 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005514 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005515 else
5516 decoration = (spv::Decoration)spv::DecorationMax;
5517 addDecoration(id, decoration);
5518 if (decoration != spv::DecorationMax) {
5519 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5520 }
5521 }
chaoc771d89f2017-01-13 01:10:53 -08005522 else if (builtIn == spv::BuiltInLayer) {
5523 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005524 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005525 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5526 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5527 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5528 }
John Kessenichb41bff62017-08-11 13:07:17 -06005529 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005530 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5531 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5532 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5533 }
5534 }
5535
chaoc6e5acae2016-12-20 13:28:52 -08005536 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005537 addDecoration(id, spv::DecorationPassthroughNV);
5538 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005539 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5540 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005541#endif
5542
John Kessenich140f3df2015-06-26 16:58:36 -06005543 return id;
5544}
5545
John Kessenich55e7d112015-11-15 21:33:39 -07005546// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005547void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5548{
John Kessenich4016e382016-07-15 11:53:56 -06005549 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005550 builder.addDecoration(id, dec);
5551}
5552
John Kessenich55e7d112015-11-15 21:33:39 -07005553// If 'dec' is valid, add a one-operand decoration to an object
5554void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5555{
John Kessenich4016e382016-07-15 11:53:56 -06005556 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005557 builder.addDecoration(id, dec, value);
5558}
5559
5560// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005561void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5562{
John Kessenich4016e382016-07-15 11:53:56 -06005563 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005564 builder.addMemberDecoration(id, (unsigned)member, dec);
5565}
5566
John Kessenich92187592016-02-01 13:45:25 -07005567// If 'dec' is valid, add a one-operand decoration to a struct member
5568void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5569{
John Kessenich4016e382016-07-15 11:53:56 -06005570 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005571 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5572}
5573
John Kessenich55e7d112015-11-15 21:33:39 -07005574// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005575// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005576//
5577// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5578//
5579// Recursively walk the nodes. The nodes form a tree whose leaves are
5580// regular constants, which themselves are trees that createSpvConstant()
5581// recursively walks. So, this function walks the "top" of the tree:
5582// - emit specialization constant-building instructions for specConstant
5583// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005584spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005585{
John Kessenich7cc0e282016-03-20 00:46:02 -06005586 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005587
qining4f4bb812016-04-03 23:55:17 -04005588 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005589 if (! node.getQualifier().specConstant) {
5590 // hand off to the non-spec-constant path
5591 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5592 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005593 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005594 nextConst, false);
5595 }
5596
5597 // We now know we have a specialization constant to build
5598
John Kessenichd94c0032016-05-30 19:29:40 -06005599 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005600 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5601 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5602 std::vector<spv::Id> dimConstId;
5603 for (int dim = 0; dim < 3; ++dim) {
5604 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5605 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5606 if (specConst)
5607 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5608 }
5609 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5610 }
5611
5612 // An AST node labelled as specialization constant should be a symbol node.
5613 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5614 if (auto* sn = node.getAsSymbolNode()) {
5615 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005616 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5617 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5618 // will set the builder into spec constant op instruction generating mode.
5619 sub_tree->traverse(this);
5620 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005621 } else if (auto* const_union_array = &sn->getConstArray()){
5622 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005623 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5624 builder.addName(id, sn->getName().c_str());
5625 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005626 }
5627 }
qining4f4bb812016-04-03 23:55:17 -04005628
5629 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5630 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005631 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005632 exit(1);
5633 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005634}
5635
John Kessenich140f3df2015-06-26 16:58:36 -06005636// Use 'consts' as the flattened glslang source of scalar constants to recursively
5637// build the aggregate SPIR-V constant.
5638//
5639// If there are not enough elements present in 'consts', 0 will be substituted;
5640// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5641//
qining08408382016-03-21 09:51:37 -04005642spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005643{
5644 // vector of constants for SPIR-V
5645 std::vector<spv::Id> spvConsts;
5646
5647 // Type is used for struct and array constants
5648 spv::Id typeId = convertGlslangToSpvType(glslangType);
5649
5650 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005651 glslang::TType elementType(glslangType, 0);
5652 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005653 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005654 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005655 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005656 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005657 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005658 } else if (glslangType.getStruct()) {
5659 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5660 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005661 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005662 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005663 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5664 bool zero = nextConst >= consts.size();
5665 switch (glslangType.getBasicType()) {
5666 case glslang::EbtInt:
5667 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5668 break;
5669 case glslang::EbtUint:
5670 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5671 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005672 case glslang::EbtInt64:
5673 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5674 break;
5675 case glslang::EbtUint64:
5676 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5677 break;
Rex Xucabbb782017-03-24 13:41:14 +08005678#ifdef AMD_EXTENSIONS
5679 case glslang::EbtInt16:
5680 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5681 break;
5682 case glslang::EbtUint16:
5683 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5684 break;
5685#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005686 case glslang::EbtFloat:
5687 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5688 break;
5689 case glslang::EbtDouble:
5690 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5691 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005692#ifdef AMD_EXTENSIONS
5693 case glslang::EbtFloat16:
5694 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5695 break;
5696#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005697 case glslang::EbtBool:
5698 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5699 break;
5700 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005701 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005702 break;
5703 }
5704 ++nextConst;
5705 }
5706 } else {
5707 // we have a non-aggregate (scalar) constant
5708 bool zero = nextConst >= consts.size();
5709 spv::Id scalar = 0;
5710 switch (glslangType.getBasicType()) {
5711 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005712 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005713 break;
5714 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005715 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005716 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005717 case glslang::EbtInt64:
5718 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5719 break;
5720 case glslang::EbtUint64:
5721 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5722 break;
Rex Xucabbb782017-03-24 13:41:14 +08005723#ifdef AMD_EXTENSIONS
5724 case glslang::EbtInt16:
5725 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5726 break;
5727 case glslang::EbtUint16:
5728 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5729 break;
5730#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005731 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005732 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005733 break;
5734 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005735 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005736 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005737#ifdef AMD_EXTENSIONS
5738 case glslang::EbtFloat16:
5739 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5740 break;
5741#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005742 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005743 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005744 break;
5745 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005746 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005747 break;
5748 }
5749 ++nextConst;
5750 return scalar;
5751 }
5752
5753 return builder.makeCompositeConstant(typeId, spvConsts);
5754}
5755
John Kessenich7c1aa102015-10-15 13:29:11 -06005756// Return true if the node is a constant or symbol whose reading has no
5757// non-trivial observable cost or effect.
5758bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5759{
5760 // don't know what this is
5761 if (node == nullptr)
5762 return false;
5763
5764 // a constant is safe
5765 if (node->getAsConstantUnion() != nullptr)
5766 return true;
5767
5768 // not a symbol means non-trivial
5769 if (node->getAsSymbolNode() == nullptr)
5770 return false;
5771
5772 // a symbol, depends on what's being read
5773 switch (node->getType().getQualifier().storage) {
5774 case glslang::EvqTemporary:
5775 case glslang::EvqGlobal:
5776 case glslang::EvqIn:
5777 case glslang::EvqInOut:
5778 case glslang::EvqConst:
5779 case glslang::EvqConstReadOnly:
5780 case glslang::EvqUniform:
5781 return true;
5782 default:
5783 return false;
5784 }
qining25262b32016-05-06 17:25:16 -04005785}
John Kessenich7c1aa102015-10-15 13:29:11 -06005786
5787// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005788// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005789// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005790// Return true if trivial.
5791bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5792{
5793 if (node == nullptr)
5794 return false;
5795
John Kessenich84cc15f2017-05-24 16:44:47 -06005796 // count non scalars as trivial, as well as anything coming from HLSL
5797 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005798 return true;
5799
John Kessenich7c1aa102015-10-15 13:29:11 -06005800 // symbols and constants are trivial
5801 if (isTrivialLeaf(node))
5802 return true;
5803
5804 // otherwise, it needs to be a simple operation or one or two leaf nodes
5805
5806 // not a simple operation
5807 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5808 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5809 if (binaryNode == nullptr && unaryNode == nullptr)
5810 return false;
5811
5812 // not on leaf nodes
5813 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5814 return false;
5815
5816 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5817 return false;
5818 }
5819
5820 switch (node->getAsOperator()->getOp()) {
5821 case glslang::EOpLogicalNot:
5822 case glslang::EOpConvIntToBool:
5823 case glslang::EOpConvUintToBool:
5824 case glslang::EOpConvFloatToBool:
5825 case glslang::EOpConvDoubleToBool:
5826 case glslang::EOpEqual:
5827 case glslang::EOpNotEqual:
5828 case glslang::EOpLessThan:
5829 case glslang::EOpGreaterThan:
5830 case glslang::EOpLessThanEqual:
5831 case glslang::EOpGreaterThanEqual:
5832 case glslang::EOpIndexDirect:
5833 case glslang::EOpIndexDirectStruct:
5834 case glslang::EOpLogicalXor:
5835 case glslang::EOpAny:
5836 case glslang::EOpAll:
5837 return true;
5838 default:
5839 return false;
5840 }
5841}
5842
5843// Emit short-circuiting code, where 'right' is never evaluated unless
5844// the left side is true (for &&) or false (for ||).
5845spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5846{
5847 spv::Id boolTypeId = builder.makeBoolType();
5848
5849 // emit left operand
5850 builder.clearAccessChain();
5851 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005852 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005853
5854 // Operands to accumulate OpPhi operands
5855 std::vector<spv::Id> phiOperands;
5856 // accumulate left operand's phi information
5857 phiOperands.push_back(leftId);
5858 phiOperands.push_back(builder.getBuildPoint()->getId());
5859
5860 // Make the two kinds of operation symmetric with a "!"
5861 // || => emit "if (! left) result = right"
5862 // && => emit "if ( left) result = right"
5863 //
5864 // TODO: this runtime "not" for || could be avoided by adding functionality
5865 // to 'builder' to have an "else" without an "then"
5866 if (op == glslang::EOpLogicalOr)
5867 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5868
5869 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005870 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005871
5872 // emit right operand as the "then" part of the "if"
5873 builder.clearAccessChain();
5874 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005875 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005876
5877 // accumulate left operand's phi information
5878 phiOperands.push_back(rightId);
5879 phiOperands.push_back(builder.getBuildPoint()->getId());
5880
5881 // finish the "if"
5882 ifBuilder.makeEndIf();
5883
5884 // phi together the two results
5885 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5886}
5887
Rex Xu9d93a232016-05-05 12:30:44 +08005888// Return type Id of the imported set of extended instructions corresponds to the name.
5889// Import this set if it has not been imported yet.
5890spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5891{
5892 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5893 return extBuiltinMap[name];
5894 else {
Rex Xu51596642016-09-21 18:56:12 +08005895 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005896 spv::Id extBuiltins = builder.import(name);
5897 extBuiltinMap[name] = extBuiltins;
5898 return extBuiltins;
5899 }
5900}
5901
John Kessenich140f3df2015-06-26 16:58:36 -06005902}; // end anonymous namespace
5903
5904namespace glslang {
5905
John Kessenich68d78fd2015-07-12 19:28:10 -06005906void GetSpirvVersion(std::string& version)
5907{
John Kessenich9e55f632015-07-15 10:03:39 -06005908 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005909 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005910 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005911 version = buf;
5912}
5913
John Kessenich140f3df2015-06-26 16:58:36 -06005914// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005915void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005916{
5917 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005918 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005919 if (out.fail())
5920 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005921 for (int i = 0; i < (int)spirv.size(); ++i) {
5922 unsigned int word = spirv[i];
5923 out.write((const char*)&word, 4);
5924 }
5925 out.close();
5926}
5927
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005928// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005929void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005930{
5931 std::ofstream out;
5932 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005933 if (out.fail())
5934 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005935 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005936 if (varName != nullptr) {
5937 out << "\t #pragma once" << std::endl;
5938 out << "const uint32_t " << varName << "[] = {" << std::endl;
5939 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005940 const int WORDS_PER_LINE = 8;
5941 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5942 out << "\t";
5943 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5944 const unsigned int word = spirv[i + j];
5945 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5946 if (i + j + 1 < (int)spirv.size()) {
5947 out << ",";
5948 }
5949 }
5950 out << std::endl;
5951 }
Flavio15017db2017-02-15 14:29:33 -08005952 if (varName != nullptr) {
5953 out << "};";
5954 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005955 out.close();
5956}
5957
John Kessenich140f3df2015-06-26 16:58:36 -06005958//
5959// Set up the glslang traversal
5960//
John Kessenich121853f2017-05-31 17:11:16 -06005961void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005962{
Lei Zhang17535f72016-05-04 15:55:59 -04005963 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005964 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005965}
5966
John Kessenich121853f2017-05-31 17:11:16 -06005967void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5968 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005969{
John Kessenich140f3df2015-06-26 16:58:36 -06005970 TIntermNode* root = intermediate.getTreeRoot();
5971
5972 if (root == 0)
5973 return;
5974
John Kessenich121853f2017-05-31 17:11:16 -06005975 glslang::SpvOptions defaultOptions;
5976 if (options == nullptr)
5977 options = &defaultOptions;
5978
John Kessenich140f3df2015-06-26 16:58:36 -06005979 glslang::GetThreadPoolAllocator().push();
5980
John Kessenich121853f2017-05-31 17:11:16 -06005981 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005982 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005983 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005984 it.dumpSpv(spirv);
5985
5986 glslang::GetThreadPoolAllocator().pop();
5987}
5988
5989}; // end namespace glslang