blob: bda992262b9e35c2ef0ff7515a961ef56fd2f49e [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
John Kessenich121853f2017-05-31 17:11:16 -0600104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800125 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600126 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600127 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600128 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
129 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600130 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
131 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
132 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600133 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700134 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600135 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600136 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
137 glslang::TLayoutPacking, const glslang::TQualifier&);
138 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
139 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700140 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700141 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800142 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600143 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700144 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700145 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
147 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100148 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600149
John Kessenich6fccb3c2016-09-19 16:01:41 -0600150 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 void makeFunctions(const glslang::TIntermSequence&);
152 void makeGlobalInitializers(const glslang::TIntermSequence&);
153 void visitFunctions(const glslang::TIntermSequence&);
154 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800155 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600156 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
157 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600158 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
159
qining25262b32016-05-06 17:25:16 -0400160 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
161 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
162 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800163 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800164 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800166 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800167 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800168 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600169 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800170 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
172 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700173 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700175 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400176 spv::Id createSpvConstant(const glslang::TIntermTyped&);
177 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600178 bool isTrivialLeaf(const glslang::TIntermTyped* node);
179 bool isTrivial(const glslang::TIntermTyped* node);
180 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800181 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich121853f2017-05-31 17:11:16 -0600183 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600184 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600185 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700186 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600187 int sequenceDepth;
188
Lei Zhang17535f72016-05-04 15:55:59 -0400189 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400190
John Kessenich140f3df2015-06-26 16:58:36 -0600191 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
192 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700193 bool inEntryPoint;
194 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700195 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700196 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600197 const glslang::TIntermediate* glslangIntermediate;
198 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800199 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600200
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600202 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600203 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700204 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600205 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600206 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600207};
208
209//
210// Helper functions for translating glslang representations to SPIR-V enumerants.
211//
212
213// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700214spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600215{
John Kessenich66e2faf2016-03-12 18:34:36 -0700216 switch (source) {
217 case glslang::EShSourceGlsl:
218 switch (profile) {
219 case ENoProfile:
220 case ECoreProfile:
221 case ECompatibilityProfile:
222 return spv::SourceLanguageGLSL;
223 case EEsProfile:
224 return spv::SourceLanguageESSL;
225 default:
226 return spv::SourceLanguageUnknown;
227 }
228 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600229 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600230 default:
231 return spv::SourceLanguageUnknown;
232 }
233}
234
235// Translate glslang language (stage) to SPIR-V execution model.
236spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
237{
238 switch (stage) {
239 case EShLangVertex: return spv::ExecutionModelVertex;
240 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
241 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
242 case EShLangGeometry: return spv::ExecutionModelGeometry;
243 case EShLangFragment: return spv::ExecutionModelFragment;
244 case EShLangCompute: return spv::ExecutionModelGLCompute;
245 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600247 return spv::ExecutionModelFragment;
248 }
249}
250
John Kessenich140f3df2015-06-26 16:58:36 -0600251// Translate glslang sampler type to SPIR-V dimensionality.
252spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
253{
254 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700255 case glslang::Esd1D: return spv::Dim1D;
256 case glslang::Esd2D: return spv::Dim2D;
257 case glslang::Esd3D: return spv::Dim3D;
258 case glslang::EsdCube: return spv::DimCube;
259 case glslang::EsdRect: return spv::DimRect;
260 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700261 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::Dim2D;
265 }
266}
267
John Kessenichf6640762016-08-01 19:44:00 -0600268// Translate glslang precision to SPIR-V precision decorations.
269spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600270{
John Kessenichf6640762016-08-01 19:44:00 -0600271 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700272 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600273 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::NoPrecision;
276 }
277}
278
John Kessenichf6640762016-08-01 19:44:00 -0600279// Translate glslang type to SPIR-V precision decorations.
280spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
281{
282 return TranslatePrecisionDecoration(type.getQualifier().precision);
283}
284
John Kessenich140f3df2015-06-26 16:58:36 -0600285// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600286spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600287{
288 if (type.getBasicType() == glslang::EbtBlock) {
289 switch (type.getQualifier().storage) {
290 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600291 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 case glslang::EvqVaryingIn: return spv::DecorationBlock;
293 case glslang::EvqVaryingOut: return spv::DecorationBlock;
294 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700295 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600296 break;
297 }
298 }
299
John Kessenich4016e382016-07-15 11:53:56 -0600300 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600301}
302
Rex Xu1da878f2016-02-21 20:59:01 +0800303// Translate glslang type to SPIR-V memory decorations.
304void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
305{
306 if (qualifier.coherent)
307 memory.push_back(spv::DecorationCoherent);
308 if (qualifier.volatil)
309 memory.push_back(spv::DecorationVolatile);
310 if (qualifier.restrict)
311 memory.push_back(spv::DecorationRestrict);
312 if (qualifier.readonly)
313 memory.push_back(spv::DecorationNonWritable);
314 if (qualifier.writeonly)
315 memory.push_back(spv::DecorationNonReadable);
316}
317
John Kessenich140f3df2015-06-26 16:58:36 -0600318// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700319spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600320{
321 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700322 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600323 case glslang::ElmRowMajor:
324 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700327 default:
328 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600329 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600330 }
331 } else {
332 switch (type.getBasicType()) {
333 default:
John Kessenich4016e382016-07-15 11:53:56 -0600334 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 break;
336 case glslang::EbtBlock:
337 switch (type.getQualifier().storage) {
338 case glslang::EvqUniform:
339 case glslang::EvqBuffer:
340 switch (type.getQualifier().layoutPacking) {
341 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
343 default:
John Kessenich4016e382016-07-15 11:53:56 -0600344 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600345 }
346 case glslang::EvqVaryingIn:
347 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700348 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600349 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600350 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700351 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 }
355 }
356}
357
358// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600359// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700360// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800361spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600362{
Rex Xubbceed72016-05-21 09:40:44 +0800363 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700364 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600365 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800366 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700367 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700368 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600369 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800370#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800371 else if (qualifier.explicitInterp) {
372 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800373 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800374 }
Rex Xu9d93a232016-05-05 12:30:44 +0800375#endif
Rex Xubbceed72016-05-21 09:40:44 +0800376 else
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378}
379
380// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600381// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800382// should be applied.
383spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
384{
385 if (qualifier.patch)
386 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700387 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600388 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700389 else if (qualifier.sample) {
390 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700392 } else
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600394}
395
John Kessenich92187592016-02-01 13:45:25 -0700396// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600398{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationInvariant;
401 else
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600403}
404
qining9220dbb2016-05-04 17:34:38 -0400405// If glslang type is noContraction, return SPIR-V NoContraction decoration.
406spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
407{
408 if (qualifier.noContraction)
409 return spv::DecorationNoContraction;
410 else
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400412}
413
David Netoa901ffe2016-06-08 14:11:40 +0100414// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
415// associated capabilities when required. For some built-in variables, a capability
416// is generated only when using the variable in an executable instruction, but not when
417// just declaring a struct member variable with it. This is true for PointSize,
418// ClipDistance, and CullDistance.
419spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600420{
421 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700422 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600423 // Defer adding the capability until the built-in is actually used.
424 if (! memberDeclaration) {
425 switch (glslangIntermediate->getStage()) {
426 case EShLangGeometry:
427 builder.addCapability(spv::CapabilityGeometryPointSize);
428 break;
429 case EShLangTessControl:
430 case EShLangTessEvaluation:
431 builder.addCapability(spv::CapabilityTessellationPointSize);
432 break;
433 default:
434 break;
435 }
John Kessenich92187592016-02-01 13:45:25 -0700436 }
437 return spv::BuiltInPointSize;
438
John Kessenichebb50532016-05-16 19:22:05 -0600439 // These *Distance capabilities logically belong here, but if the member is declared and
440 // then never used, consumers of SPIR-V prefer the capability not be declared.
441 // They are now generated when used, rather than here when declared.
442 // Potentially, the specification should be more clear what the minimum
443 // use needed is to trigger the capability.
444 //
John Kessenich92187592016-02-01 13:45:25 -0700445 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100446 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800447 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700448 return spv::BuiltInClipDistance;
449
450 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100451 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800452 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700453 return spv::BuiltInCullDistance;
454
455 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800456 if (!memberDeclaration) {
457 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800458#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800459 if (glslangIntermediate->getStage() == EShLangVertex ||
460 glslangIntermediate->getStage() == EShLangTessControl ||
461 glslangIntermediate->getStage() == EShLangTessEvaluation) {
462
463 builder.addExtension(spv::E_SPV_NV_viewport_array2);
464 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
465 }
chaoc771d89f2017-01-13 01:10:53 -0800466#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800467 }
John Kessenich92187592016-02-01 13:45:25 -0700468 return spv::BuiltInViewportIndex;
469
John Kessenich5e801132016-02-15 11:09:46 -0700470 case glslang::EbvSampleId:
471 builder.addCapability(spv::CapabilitySampleRateShading);
472 return spv::BuiltInSampleId;
473
474 case glslang::EbvSamplePosition:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSamplePosition;
477
478 case glslang::EbvSampleMask:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSampleMask;
481
John Kessenich78a45572016-07-08 14:05:15 -0600482 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800483 if (!memberDeclaration) {
484 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
489
chaoc771d89f2017-01-13 01:10:53 -0800490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
chaoc771d89f2017-01-13 01:10:53 -0800493#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800494 }
495
John Kessenich78a45572016-07-08 14:05:15 -0600496 return spv::BuiltInLayer;
497
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvVertexId: return spv::BuiltInVertexId;
500 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700501 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
502 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800503
John Kessenichda581a22015-10-14 14:10:30 -0600504 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800505 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
506 builder.addCapability(spv::CapabilityDrawParameters);
507 return spv::BuiltInBaseVertex;
508
John Kessenichda581a22015-10-14 14:10:30 -0600509 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800510 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
511 builder.addCapability(spv::CapabilityDrawParameters);
512 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200513
John Kessenichda581a22015-10-14 14:10:30 -0600514 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800515 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
516 builder.addCapability(spv::CapabilityDrawParameters);
517 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200518
519 case glslang::EbvPrimitiveId:
520 if (glslangIntermediate->getStage() == EShLangFragment)
521 builder.addCapability(spv::CapabilityGeometry);
522 return spv::BuiltInPrimitiveId;
523
Rex Xu37cdcee2017-06-29 17:46:34 +0800524 case glslang::EbvFragStencilRef:
525 logger->missingFunctionality("shader stencil export");
526 return spv::BuiltInMax;
527
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
530 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
531 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
532 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
533 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
534 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
535 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600536 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
537 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
538 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
539 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
540 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
541 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
542 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
543 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800544
Rex Xu574ab042016-04-14 16:53:07 +0800545 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800546 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800547 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
548 return spv::BuiltInSubgroupSize;
549
Rex Xu574ab042016-04-14 16:53:07 +0800550 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800551 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800552 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
553 return spv::BuiltInSubgroupLocalInvocationId;
554
Rex Xu574ab042016-04-14 16:53:07 +0800555 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800556 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
557 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
558 return spv::BuiltInSubgroupEqMaskKHR;
559
Rex Xu574ab042016-04-14 16:53:07 +0800560 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800561 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
562 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
563 return spv::BuiltInSubgroupGeMaskKHR;
564
Rex Xu574ab042016-04-14 16:53:07 +0800565 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800566 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
567 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
568 return spv::BuiltInSubgroupGtMaskKHR;
569
Rex Xu574ab042016-04-14 16:53:07 +0800570 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
572 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
573 return spv::BuiltInSubgroupLeMaskKHR;
574
Rex Xu574ab042016-04-14 16:53:07 +0800575 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800576 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
577 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
578 return spv::BuiltInSubgroupLtMaskKHR;
579
Rex Xu9d93a232016-05-05 12:30:44 +0800580#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800581 case glslang::EbvBaryCoordNoPersp:
582 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
583 return spv::BuiltInBaryCoordNoPerspAMD;
584
585 case glslang::EbvBaryCoordNoPerspCentroid:
586 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
587 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
588
589 case glslang::EbvBaryCoordNoPerspSample:
590 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
591 return spv::BuiltInBaryCoordNoPerspSampleAMD;
592
593 case glslang::EbvBaryCoordSmooth:
594 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
595 return spv::BuiltInBaryCoordSmoothAMD;
596
597 case glslang::EbvBaryCoordSmoothCentroid:
598 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
599 return spv::BuiltInBaryCoordSmoothCentroidAMD;
600
601 case glslang::EbvBaryCoordSmoothSample:
602 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
603 return spv::BuiltInBaryCoordSmoothSampleAMD;
604
605 case glslang::EbvBaryCoordPullModel:
606 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
607 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800608#endif
chaoc771d89f2017-01-13 01:10:53 -0800609
John Kessenich6c8aaac2017-02-27 01:20:51 -0700610 case glslang::EbvDeviceIndex:
611 builder.addExtension(spv::E_SPV_KHR_device_group);
612 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700613 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700614
615 case glslang::EbvViewIndex:
616 builder.addExtension(spv::E_SPV_KHR_multiview);
617 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700618 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700619
chaoc771d89f2017-01-13 01:10:53 -0800620#ifdef NV_EXTENSIONS
621 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800622 if (!memberDeclaration) {
623 builder.addExtension(spv::E_SPV_NV_viewport_array2);
624 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
625 }
chaoc771d89f2017-01-13 01:10:53 -0800626 return spv::BuiltInViewportMaskNV;
627 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800628 if (!memberDeclaration) {
629 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
630 builder.addCapability(spv::CapabilityShaderStereoViewNV);
631 }
chaoc771d89f2017-01-13 01:10:53 -0800632 return spv::BuiltInSecondaryPositionNV;
633 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800634 if (!memberDeclaration) {
635 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
636 builder.addCapability(spv::CapabilityShaderStereoViewNV);
637 }
chaoc771d89f2017-01-13 01:10:53 -0800638 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800639 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800640 if (!memberDeclaration) {
641 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
642 builder.addCapability(spv::CapabilityPerViewAttributesNV);
643 }
chaocdf3956c2017-02-14 14:52:34 -0800644 return spv::BuiltInPositionPerViewNV;
645 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800646 if (!memberDeclaration) {
647 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
648 builder.addCapability(spv::CapabilityPerViewAttributesNV);
649 }
chaocdf3956c2017-02-14 14:52:34 -0800650 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800651#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800652 default:
653 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600654 }
655}
656
Rex Xufc618912015-09-09 16:42:49 +0800657// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700658spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800659{
660 assert(type.getBasicType() == glslang::EbtSampler);
661
John Kessenich5d0fa972016-02-15 11:57:00 -0700662 // Check for capabilities
663 switch (type.getQualifier().layoutFormat) {
664 case glslang::ElfRg32f:
665 case glslang::ElfRg16f:
666 case glslang::ElfR11fG11fB10f:
667 case glslang::ElfR16f:
668 case glslang::ElfRgba16:
669 case glslang::ElfRgb10A2:
670 case glslang::ElfRg16:
671 case glslang::ElfRg8:
672 case glslang::ElfR16:
673 case glslang::ElfR8:
674 case glslang::ElfRgba16Snorm:
675 case glslang::ElfRg16Snorm:
676 case glslang::ElfRg8Snorm:
677 case glslang::ElfR16Snorm:
678 case glslang::ElfR8Snorm:
679
680 case glslang::ElfRg32i:
681 case glslang::ElfRg16i:
682 case glslang::ElfRg8i:
683 case glslang::ElfR16i:
684 case glslang::ElfR8i:
685
686 case glslang::ElfRgb10a2ui:
687 case glslang::ElfRg32ui:
688 case glslang::ElfRg16ui:
689 case glslang::ElfRg8ui:
690 case glslang::ElfR16ui:
691 case glslang::ElfR8ui:
692 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
693 break;
694
695 default:
696 break;
697 }
698
699 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800700 switch (type.getQualifier().layoutFormat) {
701 case glslang::ElfNone: return spv::ImageFormatUnknown;
702 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
703 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
704 case glslang::ElfR32f: return spv::ImageFormatR32f;
705 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
706 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
707 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
708 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
709 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
710 case glslang::ElfR16f: return spv::ImageFormatR16f;
711 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
712 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
713 case glslang::ElfRg16: return spv::ImageFormatRg16;
714 case glslang::ElfRg8: return spv::ImageFormatRg8;
715 case glslang::ElfR16: return spv::ImageFormatR16;
716 case glslang::ElfR8: return spv::ImageFormatR8;
717 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
718 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
719 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
720 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
721 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
722 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
723 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
724 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
725 case glslang::ElfR32i: return spv::ImageFormatR32i;
726 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
727 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
728 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
729 case glslang::ElfR16i: return spv::ImageFormatR16i;
730 case glslang::ElfR8i: return spv::ImageFormatR8i;
731 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
732 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
733 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
734 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
735 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
736 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
737 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
738 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
739 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
740 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600741 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800742 }
743}
744
Rex Xu57e65922017-07-04 23:23:40 +0800745spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
746{
747 switch (selectionControl) {
748 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
749 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
750 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
751 default: return spv::SelectionControlMaskNone;
752 }
753}
754
steve-lunargf1709e72017-05-02 20:14:50 -0600755spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
756{
757 switch (loopControl) {
758 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
759 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
760 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
761 // TODO: DependencyInfinite
762 // TODO: DependencyLength
763 default: return spv::LoopControlMaskNone;
764 }
765}
766
John Kessenicha5c5fb62017-05-05 05:09:58 -0600767// Translate glslang type to SPIR-V storage class.
768spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
769{
770 if (type.getQualifier().isPipeInput())
771 return spv::StorageClassInput;
772 else if (type.getQualifier().isPipeOutput())
773 return spv::StorageClassOutput;
774 else if (type.getBasicType() == glslang::EbtAtomicUint)
775 return spv::StorageClassAtomicCounter;
776 else if (type.containsOpaque())
777 return spv::StorageClassUniformConstant;
778 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
779 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
780 return spv::StorageClassStorageBuffer;
781 } else if (type.getQualifier().isUniformOrBuffer()) {
782 if (type.getQualifier().layoutPushConstant)
783 return spv::StorageClassPushConstant;
784 if (type.getBasicType() == glslang::EbtBlock)
785 return spv::StorageClassUniform;
786 else
787 return spv::StorageClassUniformConstant;
788 } else {
789 switch (type.getQualifier().storage) {
790 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
791 case glslang::EvqGlobal: return spv::StorageClassPrivate;
792 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
793 case glslang::EvqTemporary: return spv::StorageClassFunction;
794 default:
795 assert(0);
796 return spv::StorageClassFunction;
797 }
798 }
799}
800
qining25262b32016-05-06 17:25:16 -0400801// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700802// descriptor set.
803bool IsDescriptorResource(const glslang::TType& type)
804{
John Kessenichf7497e22016-03-08 21:36:22 -0700805 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700806 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700807 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700808
809 // non block...
810 // basically samplerXXX/subpass/sampler/texture are all included
811 // if they are the global-scope-class, not the function parameter
812 // (or local, if they ever exist) class.
813 if (type.getBasicType() == glslang::EbtSampler)
814 return type.getQualifier().isUniformOrBuffer();
815
816 // None of the above.
817 return false;
818}
819
John Kesseniche0b6cad2015-12-24 10:30:13 -0700820void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
821{
822 if (child.layoutMatrix == glslang::ElmNone)
823 child.layoutMatrix = parent.layoutMatrix;
824
825 if (parent.invariant)
826 child.invariant = true;
827 if (parent.nopersp)
828 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800829#ifdef AMD_EXTENSIONS
830 if (parent.explicitInterp)
831 child.explicitInterp = true;
832#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700833 if (parent.flat)
834 child.flat = true;
835 if (parent.centroid)
836 child.centroid = true;
837 if (parent.patch)
838 child.patch = true;
839 if (parent.sample)
840 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800841 if (parent.coherent)
842 child.coherent = true;
843 if (parent.volatil)
844 child.volatil = true;
845 if (parent.restrict)
846 child.restrict = true;
847 if (parent.readonly)
848 child.readonly = true;
849 if (parent.writeonly)
850 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851}
852
John Kessenichf2b7f332016-09-01 17:05:23 -0600853bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700854{
John Kessenich7b9fa252016-01-21 18:56:57 -0700855 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600856 // - struct members might inherit from a struct declaration
857 // (note that non-block structs don't explicitly inherit,
858 // only implicitly, meaning no decoration involved)
859 // - affect decorations on the struct members
860 // (note smooth does not, and expecting something like volatile
861 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700862 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600863 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864}
865
John Kessenich140f3df2015-06-26 16:58:36 -0600866//
867// Implement the TGlslangToSpvTraverser class.
868//
869
John Kessenich121853f2017-05-31 17:11:16 -0600870TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
871 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
872 : TIntermTraverser(true, false, true),
873 options(options),
874 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600875 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400876 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700877 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600878 glslangIntermediate(glslangIntermediate)
879{
880 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
881
882 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600883 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
884 glslangIntermediate->getVersion());
885
John Kessenich121853f2017-05-31 17:11:16 -0600886 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600887 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600888 builder.setSourceFile(glslangIntermediate->getSourceFile());
889
890 // Set the source shader's text. If for SPV version 1.0, include
891 // a preamble in comments stating the OpModuleProcessed instructions.
892 // Otherwise, emit those as actual instructions.
893 std::string text;
894 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
895 for (int p = 0; p < (int)processes.size(); ++p) {
896 if (glslangIntermediate->getSpv().spv < 0x00010100) {
897 text.append("// OpModuleProcessed ");
898 text.append(processes[p]);
899 text.append("\n");
900 } else
901 builder.addModuleProcessed(processes[p]);
902 }
903 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
904 text.append("#line 1\n");
905 text.append(glslangIntermediate->getSourceText());
906 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600907 }
John Kessenich140f3df2015-06-26 16:58:36 -0600908 stdBuiltins = builder.import("GLSL.std.450");
909 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600910 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
911 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600912
913 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600914 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
915 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600916 builder.addSourceExtension(it->c_str());
917
918 // Add the top-level modes for this shader.
919
John Kessenich92187592016-02-01 13:45:25 -0700920 if (glslangIntermediate->getXfbMode()) {
921 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600922 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700923 }
John Kessenich140f3df2015-06-26 16:58:36 -0600924
925 unsigned int mode;
926 switch (glslangIntermediate->getStage()) {
927 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600928 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600929 break;
930
steve-lunarge7412492017-03-23 11:56:07 -0600931 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600932 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600933 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600934
steve-lunarge7412492017-03-23 11:56:07 -0600935 glslang::TLayoutGeometry primitive;
936
937 if (glslangIntermediate->getStage() == EShLangTessControl) {
938 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
939 primitive = glslangIntermediate->getOutputPrimitive();
940 } else {
941 primitive = glslangIntermediate->getInputPrimitive();
942 }
943
944 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700945 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
946 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
947 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600948 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600949 }
John Kessenich4016e382016-07-15 11:53:56 -0600950 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600951 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
952
John Kesseniche6903322015-10-13 16:29:02 -0600953 switch (glslangIntermediate->getVertexSpacing()) {
954 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
955 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
956 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; 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 switch (glslangIntermediate->getVertexOrder()) {
963 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
964 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600965 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600966 }
John Kessenich4016e382016-07-15 11:53:56 -0600967 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600968 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
969
970 if (glslangIntermediate->getPointMode())
971 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600972 break;
973
974 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600975 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600976 switch (glslangIntermediate->getInputPrimitive()) {
977 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
978 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
979 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700980 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600981 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600982 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600983 }
John Kessenich4016e382016-07-15 11:53:56 -0600984 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600985 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600986
John Kessenich140f3df2015-06-26 16:58:36 -0600987 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
988
989 switch (glslangIntermediate->getOutputPrimitive()) {
990 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
991 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
992 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600993 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600994 }
John Kessenich4016e382016-07-15 11:53:56 -0600995 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600996 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
997 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
998 break;
999
1000 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001001 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001002 if (glslangIntermediate->getPixelCenterInteger())
1003 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001004
John Kessenich140f3df2015-06-26 16:58:36 -06001005 if (glslangIntermediate->getOriginUpperLeft())
1006 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001007 else
1008 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001009
1010 if (glslangIntermediate->getEarlyFragmentTests())
1011 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1012
chaocc1204522017-06-30 17:14:30 -07001013 if (glslangIntermediate->getPostDepthCoverage()) {
1014 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1015 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1016 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1017 }
1018
John Kesseniche6903322015-10-13 16:29:02 -06001019 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001020 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1021 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001022 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001023 }
John Kessenich4016e382016-07-15 11:53:56 -06001024 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001025 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1026
1027 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1028 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001029 break;
1030
1031 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001032 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001033 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1034 glslangIntermediate->getLocalSize(1),
1035 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001036 break;
1037
1038 default:
1039 break;
1040 }
John Kessenich140f3df2015-06-26 16:58:36 -06001041}
1042
John Kessenichfca82622016-11-26 13:23:20 -07001043// Finish creating SPV, after the traversal is complete.
1044void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001045{
John Kessenich517fe7a2016-11-26 13:31:47 -07001046 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001047 builder.setBuildPoint(shaderEntry->getLastBlock());
1048 builder.leaveFunction();
1049 }
1050
John Kessenich7ba63412015-12-20 17:37:07 -07001051 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001052 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1053 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001054
qiningda397332016-03-09 19:54:03 -05001055 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001056}
1057
John Kessenichfca82622016-11-26 13:23:20 -07001058// Write the SPV into 'out'.
1059void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001060{
John Kessenichfca82622016-11-26 13:23:20 -07001061 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001062}
1063
1064//
1065// Implement the traversal functions.
1066//
1067// Return true from interior nodes to have the external traversal
1068// continue on to children. Return false if children were
1069// already processed.
1070//
1071
1072//
qining25262b32016-05-06 17:25:16 -04001073// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001074// - uniform/input reads
1075// - output writes
1076// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1077// - something simple that degenerates into the last bullet
1078//
1079void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1080{
qining75d1d802016-04-06 14:42:01 -04001081 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1082 if (symbol->getType().getQualifier().isSpecConstant())
1083 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1084
John Kessenich140f3df2015-06-26 16:58:36 -06001085 // getSymbolId() will set up all the IO decorations on the first call.
1086 // Formal function parameters were mapped during makeFunctions().
1087 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001088
1089 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1090 if (builder.isPointer(id)) {
1091 spv::StorageClass sc = builder.getStorageClass(id);
1092 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1093 iOSet.insert(id);
1094 }
1095
1096 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001097 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001098 // Prepare to generate code for the access
1099
1100 // L-value chains will be computed left to right. We're on the symbol now,
1101 // which is the left-most part of the access chain, so now is "clear" time,
1102 // followed by setting the base.
1103 builder.clearAccessChain();
1104
1105 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001106 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001107 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001108 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001109 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001110 // These are also pure R-values.
1111 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001112 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001113 builder.setAccessChainRValue(id);
1114 else
1115 builder.setAccessChainLValue(id);
1116 }
1117}
1118
1119bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1120{
John Kesseniche485c7a2017-05-31 18:50:53 -06001121 builder.setLine(node->getLoc().line);
1122
qining40887662016-04-03 22:20:42 -04001123 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1124 if (node->getType().getQualifier().isSpecConstant())
1125 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1126
John Kessenich140f3df2015-06-26 16:58:36 -06001127 // First, handle special cases
1128 switch (node->getOp()) {
1129 case glslang::EOpAssign:
1130 case glslang::EOpAddAssign:
1131 case glslang::EOpSubAssign:
1132 case glslang::EOpMulAssign:
1133 case glslang::EOpVectorTimesMatrixAssign:
1134 case glslang::EOpVectorTimesScalarAssign:
1135 case glslang::EOpMatrixTimesScalarAssign:
1136 case glslang::EOpMatrixTimesMatrixAssign:
1137 case glslang::EOpDivAssign:
1138 case glslang::EOpModAssign:
1139 case glslang::EOpAndAssign:
1140 case glslang::EOpInclusiveOrAssign:
1141 case glslang::EOpExclusiveOrAssign:
1142 case glslang::EOpLeftShiftAssign:
1143 case glslang::EOpRightShiftAssign:
1144 // A bin-op assign "a += b" means the same thing as "a = a + b"
1145 // where a is evaluated before b. For a simple assignment, GLSL
1146 // says to evaluate the left before the right. So, always, left
1147 // node then right node.
1148 {
1149 // get the left l-value, save it away
1150 builder.clearAccessChain();
1151 node->getLeft()->traverse(this);
1152 spv::Builder::AccessChain lValue = builder.getAccessChain();
1153
1154 // evaluate the right
1155 builder.clearAccessChain();
1156 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001157 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001158
1159 if (node->getOp() != glslang::EOpAssign) {
1160 // the left is also an r-value
1161 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001162 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001163
1164 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001165 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001166 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001167 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1168 node->getType().getBasicType());
1169
1170 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001171 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001172 }
1173
1174 // store the result
1175 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001176 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001177
1178 // assignments are expressions having an rValue after they are evaluated...
1179 builder.clearAccessChain();
1180 builder.setAccessChainRValue(rValue);
1181 }
1182 return false;
1183 case glslang::EOpIndexDirect:
1184 case glslang::EOpIndexDirectStruct:
1185 {
1186 // Get the left part of the access chain.
1187 node->getLeft()->traverse(this);
1188
1189 // Add the next element in the chain
1190
David Netoa901ffe2016-06-08 14:11:40 +01001191 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001192 if (! node->getLeft()->getType().isArray() &&
1193 node->getLeft()->getType().isVector() &&
1194 node->getOp() == glslang::EOpIndexDirect) {
1195 // This is essentially a hard-coded vector swizzle of size 1,
1196 // so short circuit the access-chain stuff with a swizzle.
1197 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001198 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001199 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001200 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001201 int spvIndex = glslangIndex;
1202 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1203 node->getOp() == glslang::EOpIndexDirectStruct)
1204 {
1205 // This may be, e.g., an anonymous block-member selection, which generally need
1206 // index remapping due to hidden members in anonymous blocks.
1207 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1208 assert(remapper.size() > 0);
1209 spvIndex = remapper[glslangIndex];
1210 }
John Kessenichebb50532016-05-16 19:22:05 -06001211
David Netoa901ffe2016-06-08 14:11:40 +01001212 // normal case for indexing array or structure or block
1213 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1214
1215 // Add capabilities here for accessing PointSize and clip/cull distance.
1216 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001217 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001218 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001219 }
1220 }
1221 return false;
1222 case glslang::EOpIndexIndirect:
1223 {
1224 // Structure or array or vector indirection.
1225 // Will use native SPIR-V access-chain for struct and array indirection;
1226 // matrices are arrays of vectors, so will also work for a matrix.
1227 // Will use the access chain's 'component' for variable index into a vector.
1228
1229 // This adapter is building access chains left to right.
1230 // Set up the access chain to the left.
1231 node->getLeft()->traverse(this);
1232
1233 // save it so that computing the right side doesn't trash it
1234 spv::Builder::AccessChain partial = builder.getAccessChain();
1235
1236 // compute the next index in the chain
1237 builder.clearAccessChain();
1238 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001239 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001240
1241 // restore the saved access chain
1242 builder.setAccessChain(partial);
1243
1244 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001245 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001246 else
John Kessenichfa668da2015-09-13 14:46:30 -06001247 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001248 }
1249 return false;
1250 case glslang::EOpVectorSwizzle:
1251 {
1252 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001253 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001254 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001255 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001256 }
1257 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001258 case glslang::EOpMatrixSwizzle:
1259 logger->missingFunctionality("matrix swizzle");
1260 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001261 case glslang::EOpLogicalOr:
1262 case glslang::EOpLogicalAnd:
1263 {
1264
1265 // These may require short circuiting, but can sometimes be done as straight
1266 // binary operations. The right operand must be short circuited if it has
1267 // side effects, and should probably be if it is complex.
1268 if (isTrivial(node->getRight()->getAsTyped()))
1269 break; // handle below as a normal binary operation
1270 // otherwise, we need to do dynamic short circuiting on the right operand
1271 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1272 builder.clearAccessChain();
1273 builder.setAccessChainRValue(result);
1274 }
1275 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001276 default:
1277 break;
1278 }
1279
1280 // Assume generic binary op...
1281
John Kessenich32cfd492016-02-02 12:37:46 -07001282 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001283 builder.clearAccessChain();
1284 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001285 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001286
John Kessenich32cfd492016-02-02 12:37:46 -07001287 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001288 builder.clearAccessChain();
1289 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001290 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001291
John Kessenich32cfd492016-02-02 12:37:46 -07001292 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001293 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001294 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001295 convertGlslangToSpvType(node->getType()), left, right,
1296 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001297
John Kessenich50e57562015-12-21 21:21:11 -07001298 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001299 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001300 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001301 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001302 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001303 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001304 return false;
1305 }
John Kessenich140f3df2015-06-26 16:58:36 -06001306}
1307
1308bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1309{
John Kesseniche485c7a2017-05-31 18:50:53 -06001310 builder.setLine(node->getLoc().line);
1311
qining40887662016-04-03 22:20:42 -04001312 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1313 if (node->getType().getQualifier().isSpecConstant())
1314 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1315
John Kessenichfc51d282015-08-19 13:34:18 -06001316 spv::Id result = spv::NoResult;
1317
1318 // try texturing first
1319 result = createImageTextureFunctionCall(node);
1320 if (result != spv::NoResult) {
1321 builder.clearAccessChain();
1322 builder.setAccessChainRValue(result);
1323
1324 return false; // done with this node
1325 }
1326
1327 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001328
1329 if (node->getOp() == glslang::EOpArrayLength) {
1330 // Quite special; won't want to evaluate the operand.
1331
1332 // Normal .length() would have been constant folded by the front-end.
1333 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001334 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001335 assert(node->getOperand()->getType().isRuntimeSizedArray());
1336 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1337 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001338 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1339 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001340
1341 builder.clearAccessChain();
1342 builder.setAccessChainRValue(length);
1343
1344 return false;
1345 }
1346
John Kessenichfc51d282015-08-19 13:34:18 -06001347 // Start by evaluating the operand
1348
John Kessenich8c8505c2016-07-26 12:50:38 -06001349 // Does it need a swizzle inversion? If so, evaluation is inverted;
1350 // operate first on the swizzle base, then apply the swizzle.
1351 spv::Id invertedType = spv::NoType;
1352 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1353 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1354 invertedType = getInvertedSwizzleType(*node->getOperand());
1355
John Kessenich140f3df2015-06-26 16:58:36 -06001356 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001357 if (invertedType != spv::NoType)
1358 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1359 else
1360 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001361
Rex Xufc618912015-09-09 16:42:49 +08001362 spv::Id operand = spv::NoResult;
1363
1364 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1365 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001366 node->getOp() == glslang::EOpAtomicCounter ||
1367 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001368 operand = builder.accessChainGetLValue(); // Special case l-value operands
1369 else
John Kessenich32cfd492016-02-02 12:37:46 -07001370 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001371
John Kessenichf6640762016-08-01 19:44:00 -06001372 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001373 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001374
1375 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001376 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001377 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001378
1379 // if not, then possibly an operation
1380 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001381 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001382
1383 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001384 if (invertedType)
1385 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1386
John Kessenich140f3df2015-06-26 16:58:36 -06001387 builder.clearAccessChain();
1388 builder.setAccessChainRValue(result);
1389
1390 return false; // done with this node
1391 }
1392
1393 // it must be a special case, check...
1394 switch (node->getOp()) {
1395 case glslang::EOpPostIncrement:
1396 case glslang::EOpPostDecrement:
1397 case glslang::EOpPreIncrement:
1398 case glslang::EOpPreDecrement:
1399 {
1400 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001401 spv::Id one = 0;
1402 if (node->getBasicType() == glslang::EbtFloat)
1403 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001404 else if (node->getBasicType() == glslang::EbtDouble)
1405 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001406#ifdef AMD_EXTENSIONS
1407 else if (node->getBasicType() == glslang::EbtFloat16)
1408 one = builder.makeFloat16Constant(1.0F);
1409#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001410 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1411 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001412#ifdef AMD_EXTENSIONS
1413 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1414 one = builder.makeInt16Constant(1);
1415#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001416 else
1417 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001418 glslang::TOperator op;
1419 if (node->getOp() == glslang::EOpPreIncrement ||
1420 node->getOp() == glslang::EOpPostIncrement)
1421 op = glslang::EOpAdd;
1422 else
1423 op = glslang::EOpSub;
1424
John Kessenichf6640762016-08-01 19:44:00 -06001425 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001426 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001427 convertGlslangToSpvType(node->getType()), operand, one,
1428 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001429 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001430
1431 // The result of operation is always stored, but conditionally the
1432 // consumed result. The consumed result is always an r-value.
1433 builder.accessChainStore(result);
1434 builder.clearAccessChain();
1435 if (node->getOp() == glslang::EOpPreIncrement ||
1436 node->getOp() == glslang::EOpPreDecrement)
1437 builder.setAccessChainRValue(result);
1438 else
1439 builder.setAccessChainRValue(operand);
1440 }
1441
1442 return false;
1443
1444 case glslang::EOpEmitStreamVertex:
1445 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1446 return false;
1447 case glslang::EOpEndStreamPrimitive:
1448 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1449 return false;
1450
1451 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001452 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001453 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001454 }
John Kessenich140f3df2015-06-26 16:58:36 -06001455}
1456
1457bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1458{
qining27e04a02016-04-14 16:40:20 -04001459 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1460 if (node->getType().getQualifier().isSpecConstant())
1461 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1462
John Kessenichfc51d282015-08-19 13:34:18 -06001463 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001464 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1465 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001466
1467 // try texturing
1468 result = createImageTextureFunctionCall(node);
1469 if (result != spv::NoResult) {
1470 builder.clearAccessChain();
1471 builder.setAccessChainRValue(result);
1472
1473 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001474 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001475 // "imageStore" is a special case, which has no result
1476 return false;
1477 }
John Kessenichfc51d282015-08-19 13:34:18 -06001478
John Kessenich140f3df2015-06-26 16:58:36 -06001479 glslang::TOperator binOp = glslang::EOpNull;
1480 bool reduceComparison = true;
1481 bool isMatrix = false;
1482 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001483 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001484
1485 assert(node->getOp());
1486
John Kessenichf6640762016-08-01 19:44:00 -06001487 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001488
1489 switch (node->getOp()) {
1490 case glslang::EOpSequence:
1491 {
1492 if (preVisit)
1493 ++sequenceDepth;
1494 else
1495 --sequenceDepth;
1496
1497 if (sequenceDepth == 1) {
1498 // If this is the parent node of all the functions, we want to see them
1499 // early, so all call points have actual SPIR-V functions to reference.
1500 // In all cases, still let the traverser visit the children for us.
1501 makeFunctions(node->getAsAggregate()->getSequence());
1502
John Kessenich6fccb3c2016-09-19 16:01:41 -06001503 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001504 // anything else gets there, so visit out of order, doing them all now.
1505 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1506
John Kessenich6a60c2f2016-12-08 21:01:59 -07001507 // 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 -06001508 // so do them manually.
1509 visitFunctions(node->getAsAggregate()->getSequence());
1510
1511 return false;
1512 }
1513
1514 return true;
1515 }
1516 case glslang::EOpLinkerObjects:
1517 {
1518 if (visit == glslang::EvPreVisit)
1519 linkageOnly = true;
1520 else
1521 linkageOnly = false;
1522
1523 return true;
1524 }
1525 case glslang::EOpComma:
1526 {
1527 // processing from left to right naturally leaves the right-most
1528 // lying around in the access chain
1529 glslang::TIntermSequence& glslangOperands = node->getSequence();
1530 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1531 glslangOperands[i]->traverse(this);
1532
1533 return false;
1534 }
1535 case glslang::EOpFunction:
1536 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001537 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001538 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001539 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001540 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001541 } else {
1542 handleFunctionEntry(node);
1543 }
1544 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001545 if (inEntryPoint)
1546 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001547 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001548 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001549 }
1550
1551 return true;
1552 case glslang::EOpParameters:
1553 // Parameters will have been consumed by EOpFunction processing, but not
1554 // the body, so we still visited the function node's children, making this
1555 // child redundant.
1556 return false;
1557 case glslang::EOpFunctionCall:
1558 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001559 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001560 if (node->isUserDefined())
1561 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001562 // 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 -07001563 if (result) {
1564 builder.clearAccessChain();
1565 builder.setAccessChainRValue(result);
1566 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001567 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001568
1569 return false;
1570 }
1571 case glslang::EOpConstructMat2x2:
1572 case glslang::EOpConstructMat2x3:
1573 case glslang::EOpConstructMat2x4:
1574 case glslang::EOpConstructMat3x2:
1575 case glslang::EOpConstructMat3x3:
1576 case glslang::EOpConstructMat3x4:
1577 case glslang::EOpConstructMat4x2:
1578 case glslang::EOpConstructMat4x3:
1579 case glslang::EOpConstructMat4x4:
1580 case glslang::EOpConstructDMat2x2:
1581 case glslang::EOpConstructDMat2x3:
1582 case glslang::EOpConstructDMat2x4:
1583 case glslang::EOpConstructDMat3x2:
1584 case glslang::EOpConstructDMat3x3:
1585 case glslang::EOpConstructDMat3x4:
1586 case glslang::EOpConstructDMat4x2:
1587 case glslang::EOpConstructDMat4x3:
1588 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001589 case glslang::EOpConstructIMat2x2:
1590 case glslang::EOpConstructIMat2x3:
1591 case glslang::EOpConstructIMat2x4:
1592 case glslang::EOpConstructIMat3x2:
1593 case glslang::EOpConstructIMat3x3:
1594 case glslang::EOpConstructIMat3x4:
1595 case glslang::EOpConstructIMat4x2:
1596 case glslang::EOpConstructIMat4x3:
1597 case glslang::EOpConstructIMat4x4:
1598 case glslang::EOpConstructUMat2x2:
1599 case glslang::EOpConstructUMat2x3:
1600 case glslang::EOpConstructUMat2x4:
1601 case glslang::EOpConstructUMat3x2:
1602 case glslang::EOpConstructUMat3x3:
1603 case glslang::EOpConstructUMat3x4:
1604 case glslang::EOpConstructUMat4x2:
1605 case glslang::EOpConstructUMat4x3:
1606 case glslang::EOpConstructUMat4x4:
1607 case glslang::EOpConstructBMat2x2:
1608 case glslang::EOpConstructBMat2x3:
1609 case glslang::EOpConstructBMat2x4:
1610 case glslang::EOpConstructBMat3x2:
1611 case glslang::EOpConstructBMat3x3:
1612 case glslang::EOpConstructBMat3x4:
1613 case glslang::EOpConstructBMat4x2:
1614 case glslang::EOpConstructBMat4x3:
1615 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001616#ifdef AMD_EXTENSIONS
1617 case glslang::EOpConstructF16Mat2x2:
1618 case glslang::EOpConstructF16Mat2x3:
1619 case glslang::EOpConstructF16Mat2x4:
1620 case glslang::EOpConstructF16Mat3x2:
1621 case glslang::EOpConstructF16Mat3x3:
1622 case glslang::EOpConstructF16Mat3x4:
1623 case glslang::EOpConstructF16Mat4x2:
1624 case glslang::EOpConstructF16Mat4x3:
1625 case glslang::EOpConstructF16Mat4x4:
1626#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001627 isMatrix = true;
1628 // fall through
1629 case glslang::EOpConstructFloat:
1630 case glslang::EOpConstructVec2:
1631 case glslang::EOpConstructVec3:
1632 case glslang::EOpConstructVec4:
1633 case glslang::EOpConstructDouble:
1634 case glslang::EOpConstructDVec2:
1635 case glslang::EOpConstructDVec3:
1636 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001637#ifdef AMD_EXTENSIONS
1638 case glslang::EOpConstructFloat16:
1639 case glslang::EOpConstructF16Vec2:
1640 case glslang::EOpConstructF16Vec3:
1641 case glslang::EOpConstructF16Vec4:
1642#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001643 case glslang::EOpConstructBool:
1644 case glslang::EOpConstructBVec2:
1645 case glslang::EOpConstructBVec3:
1646 case glslang::EOpConstructBVec4:
1647 case glslang::EOpConstructInt:
1648 case glslang::EOpConstructIVec2:
1649 case glslang::EOpConstructIVec3:
1650 case glslang::EOpConstructIVec4:
1651 case glslang::EOpConstructUint:
1652 case glslang::EOpConstructUVec2:
1653 case glslang::EOpConstructUVec3:
1654 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001655 case glslang::EOpConstructInt64:
1656 case glslang::EOpConstructI64Vec2:
1657 case glslang::EOpConstructI64Vec3:
1658 case glslang::EOpConstructI64Vec4:
1659 case glslang::EOpConstructUint64:
1660 case glslang::EOpConstructU64Vec2:
1661 case glslang::EOpConstructU64Vec3:
1662 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001663#ifdef AMD_EXTENSIONS
1664 case glslang::EOpConstructInt16:
1665 case glslang::EOpConstructI16Vec2:
1666 case glslang::EOpConstructI16Vec3:
1667 case glslang::EOpConstructI16Vec4:
1668 case glslang::EOpConstructUint16:
1669 case glslang::EOpConstructU16Vec2:
1670 case glslang::EOpConstructU16Vec3:
1671 case glslang::EOpConstructU16Vec4:
1672#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001673 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001674 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001675 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001676 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001677 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001678 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001679 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001680 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001681 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001682 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001683 std::vector<spv::Id> constituents;
1684 for (int c = 0; c < (int)arguments.size(); ++c)
1685 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001686 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001687 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001688 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001689 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001690 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001691
1692 builder.clearAccessChain();
1693 builder.setAccessChainRValue(constructed);
1694
1695 return false;
1696 }
1697
1698 // These six are component-wise compares with component-wise results.
1699 // Forward on to createBinaryOperation(), requesting a vector result.
1700 case glslang::EOpLessThan:
1701 case glslang::EOpGreaterThan:
1702 case glslang::EOpLessThanEqual:
1703 case glslang::EOpGreaterThanEqual:
1704 case glslang::EOpVectorEqual:
1705 case glslang::EOpVectorNotEqual:
1706 {
1707 // Map the operation to a binary
1708 binOp = node->getOp();
1709 reduceComparison = false;
1710 switch (node->getOp()) {
1711 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1712 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1713 default: binOp = node->getOp(); break;
1714 }
1715
1716 break;
1717 }
1718 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001719 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001720 binOp = glslang::EOpMul;
1721 break;
1722 case glslang::EOpOuterProduct:
1723 // two vectors multiplied to make a matrix
1724 binOp = glslang::EOpOuterProduct;
1725 break;
1726 case glslang::EOpDot:
1727 {
qining25262b32016-05-06 17:25:16 -04001728 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001729 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001730 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001731 binOp = glslang::EOpMul;
1732 break;
1733 }
1734 case glslang::EOpMod:
1735 // when an aggregate, this is the floating-point mod built-in function,
1736 // which can be emitted by the one in createBinaryOperation()
1737 binOp = glslang::EOpMod;
1738 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001739 case glslang::EOpEmitVertex:
1740 case glslang::EOpEndPrimitive:
1741 case glslang::EOpBarrier:
1742 case glslang::EOpMemoryBarrier:
1743 case glslang::EOpMemoryBarrierAtomicCounter:
1744 case glslang::EOpMemoryBarrierBuffer:
1745 case glslang::EOpMemoryBarrierImage:
1746 case glslang::EOpMemoryBarrierShared:
1747 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001748 case glslang::EOpAllMemoryBarrierWithGroupSync:
1749 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1750 case glslang::EOpWorkgroupMemoryBarrier:
1751 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001752 noReturnValue = true;
1753 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1754 break;
1755
John Kessenich426394d2015-07-23 10:22:48 -06001756 case glslang::EOpAtomicAdd:
1757 case glslang::EOpAtomicMin:
1758 case glslang::EOpAtomicMax:
1759 case glslang::EOpAtomicAnd:
1760 case glslang::EOpAtomicOr:
1761 case glslang::EOpAtomicXor:
1762 case glslang::EOpAtomicExchange:
1763 case glslang::EOpAtomicCompSwap:
1764 atomic = true;
1765 break;
1766
John Kessenich0d0c6d32017-07-23 16:08:26 -06001767 case glslang::EOpAtomicCounterAdd:
1768 case glslang::EOpAtomicCounterSubtract:
1769 case glslang::EOpAtomicCounterMin:
1770 case glslang::EOpAtomicCounterMax:
1771 case glslang::EOpAtomicCounterAnd:
1772 case glslang::EOpAtomicCounterOr:
1773 case glslang::EOpAtomicCounterXor:
1774 case glslang::EOpAtomicCounterExchange:
1775 case glslang::EOpAtomicCounterCompSwap:
1776 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1777 builder.addCapability(spv::CapabilityAtomicStorageOps);
1778 atomic = true;
1779 break;
1780
John Kessenich140f3df2015-06-26 16:58:36 -06001781 default:
1782 break;
1783 }
1784
1785 //
1786 // See if it maps to a regular operation.
1787 //
John Kessenich140f3df2015-06-26 16:58:36 -06001788 if (binOp != glslang::EOpNull) {
1789 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1790 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1791 assert(left && right);
1792
1793 builder.clearAccessChain();
1794 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001795 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001796
1797 builder.clearAccessChain();
1798 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001799 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001800
John Kesseniche485c7a2017-05-31 18:50:53 -06001801 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001802 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001803 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001804 left->getType().getBasicType(), reduceComparison);
1805
1806 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001807 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001808 builder.clearAccessChain();
1809 builder.setAccessChainRValue(result);
1810
1811 return false;
1812 }
1813
John Kessenich426394d2015-07-23 10:22:48 -06001814 //
1815 // Create the list of operands.
1816 //
John Kessenich140f3df2015-06-26 16:58:36 -06001817 glslang::TIntermSequence& glslangOperands = node->getSequence();
1818 std::vector<spv::Id> operands;
1819 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001820 // special case l-value operands; there are just a few
1821 bool lvalue = false;
1822 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001823 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001824 case glslang::EOpModf:
1825 if (arg == 1)
1826 lvalue = true;
1827 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001828 case glslang::EOpInterpolateAtSample:
1829 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001830#ifdef AMD_EXTENSIONS
1831 case glslang::EOpInterpolateAtVertex:
1832#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001833 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001834 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001835
1836 // Does it need a swizzle inversion? If so, evaluation is inverted;
1837 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001838 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001839 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1840 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1841 }
Rex Xu7a26c172015-12-08 17:12:09 +08001842 break;
Rex Xud4782c12015-09-06 16:30:11 +08001843 case glslang::EOpAtomicAdd:
1844 case glslang::EOpAtomicMin:
1845 case glslang::EOpAtomicMax:
1846 case glslang::EOpAtomicAnd:
1847 case glslang::EOpAtomicOr:
1848 case glslang::EOpAtomicXor:
1849 case glslang::EOpAtomicExchange:
1850 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001851 case glslang::EOpAtomicCounterAdd:
1852 case glslang::EOpAtomicCounterSubtract:
1853 case glslang::EOpAtomicCounterMin:
1854 case glslang::EOpAtomicCounterMax:
1855 case glslang::EOpAtomicCounterAnd:
1856 case glslang::EOpAtomicCounterOr:
1857 case glslang::EOpAtomicCounterXor:
1858 case glslang::EOpAtomicCounterExchange:
1859 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001860 if (arg == 0)
1861 lvalue = true;
1862 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001863 case glslang::EOpAddCarry:
1864 case glslang::EOpSubBorrow:
1865 if (arg == 2)
1866 lvalue = true;
1867 break;
1868 case glslang::EOpUMulExtended:
1869 case glslang::EOpIMulExtended:
1870 if (arg >= 2)
1871 lvalue = true;
1872 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001873 default:
1874 break;
1875 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001876 builder.clearAccessChain();
1877 if (invertedType != spv::NoType && arg == 0)
1878 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1879 else
1880 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001881 if (lvalue)
1882 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001883 else {
1884 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001885 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001886 }
John Kessenich140f3df2015-06-26 16:58:36 -06001887 }
John Kessenich426394d2015-07-23 10:22:48 -06001888
John Kesseniche485c7a2017-05-31 18:50:53 -06001889 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001890 if (atomic) {
1891 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001892 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001893 } else {
1894 // Pass through to generic operations.
1895 switch (glslangOperands.size()) {
1896 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001897 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001898 break;
1899 case 1:
qining25262b32016-05-06 17:25:16 -04001900 result = createUnaryOperation(
1901 node->getOp(), precision,
1902 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001903 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001904 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001905 break;
1906 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001907 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001908 break;
1909 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001910 if (invertedType)
1911 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001912 }
1913
1914 if (noReturnValue)
1915 return false;
1916
1917 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001918 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001919 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001920 } else {
1921 builder.clearAccessChain();
1922 builder.setAccessChainRValue(result);
1923 return false;
1924 }
1925}
1926
John Kessenich433e9ff2017-01-26 20:31:11 -07001927// This path handles both if-then-else and ?:
1928// The if-then-else has a node type of void, while
1929// ?: has either a void or a non-void node type
1930//
1931// Leaving the result, when not void:
1932// GLSL only has r-values as the result of a :?, but
1933// if we have an l-value, that can be more efficient if it will
1934// become the base of a complex r-value expression, because the
1935// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001936bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1937{
John Kessenich433e9ff2017-01-26 20:31:11 -07001938 // See if it simple and safe to generate OpSelect instead of using control flow.
1939 // Crucially, side effects must be avoided, and there are performance trade-offs.
1940 // Return true if good idea (and safe) for OpSelect, false otherwise.
1941 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001942 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1943 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001944 return false;
1945
1946 if (node->getTrueBlock() == nullptr ||
1947 node->getFalseBlock() == nullptr)
1948 return false;
1949
1950 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1951 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1952
1953 // return true if a single operand to ? : is okay for OpSelect
1954 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001955 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001956 };
1957
1958 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1959 operandOkay(node->getFalseBlock()->getAsTyped());
1960 };
1961
1962 // Emit OpSelect for this selection.
1963 const auto handleAsOpSelect = [&]() {
1964 node->getCondition()->traverse(this);
1965 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1966 node->getTrueBlock()->traverse(this);
1967 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1968 node->getFalseBlock()->traverse(this);
1969 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1970
John Kesseniche485c7a2017-05-31 18:50:53 -06001971 builder.setLine(node->getLoc().line);
1972
John Kesseniche434ad92017-03-30 10:09:28 -06001973 // smear condition to vector, if necessary (AST is always scalar)
1974 if (builder.isVector(trueValue))
1975 condition = builder.smearScalar(spv::NoPrecision, condition,
1976 builder.makeVectorType(builder.makeBoolType(),
1977 builder.getNumComponents(trueValue)));
1978
1979 spv::Id select = builder.createTriOp(spv::OpSelect,
1980 convertGlslangToSpvType(node->getType()), condition,
1981 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001982 builder.clearAccessChain();
1983 builder.setAccessChainRValue(select);
1984 };
1985
1986 // Try for OpSelect
1987
1988 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001989 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1990 if (node->getType().getQualifier().isSpecConstant())
1991 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1992
John Kessenich433e9ff2017-01-26 20:31:11 -07001993 handleAsOpSelect();
1994 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001995 }
1996
Rex Xu57e65922017-07-04 23:23:40 +08001997 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07001998 // Don't handle results as temporaries, because there will be two names
1999 // and better to leave SSA to later passes.
2000 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2001 ? spv::NoResult
2002 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2003
John Kessenich140f3df2015-06-26 16:58:36 -06002004 // emit the condition before doing anything with selection
2005 node->getCondition()->traverse(this);
2006
Rex Xu57e65922017-07-04 23:23:40 +08002007 // Selection control:
2008 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2009
John Kessenich140f3df2015-06-26 16:58:36 -06002010 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002011 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002012
John Kessenich433e9ff2017-01-26 20:31:11 -07002013 // emit the "then" statement
2014 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002015 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002016 if (result != spv::NoResult)
2017 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002018 }
2019
John Kessenich433e9ff2017-01-26 20:31:11 -07002020 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002021 ifBuilder.makeBeginElse();
2022 // emit the "else" statement
2023 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002024 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002025 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002026 }
2027
John Kessenich433e9ff2017-01-26 20:31:11 -07002028 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002029 ifBuilder.makeEndIf();
2030
John Kessenich433e9ff2017-01-26 20:31:11 -07002031 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002032 // GLSL only has r-values as the result of a :?, but
2033 // if we have an l-value, that can be more efficient if it will
2034 // become the base of a complex r-value expression, because the
2035 // next layer copies r-values into memory to use the access-chain mechanism
2036 builder.clearAccessChain();
2037 builder.setAccessChainLValue(result);
2038 }
2039
2040 return false;
2041}
2042
2043bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2044{
2045 // emit and get the condition before doing anything with switch
2046 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002047 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002048
Rex Xu57e65922017-07-04 23:23:40 +08002049 // Selection control:
2050 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2051
John Kessenich140f3df2015-06-26 16:58:36 -06002052 // browse the children to sort out code segments
2053 int defaultSegment = -1;
2054 std::vector<TIntermNode*> codeSegments;
2055 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2056 std::vector<int> caseValues;
2057 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2058 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2059 TIntermNode* child = *c;
2060 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002061 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002062 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002063 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002064 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2065 } else
2066 codeSegments.push_back(child);
2067 }
2068
qining25262b32016-05-06 17:25:16 -04002069 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002070 // statements between the last case and the end of the switch statement
2071 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2072 (int)codeSegments.size() == defaultSegment)
2073 codeSegments.push_back(nullptr);
2074
2075 // make the switch statement
2076 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002077 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002078
2079 // emit all the code in the segments
2080 breakForLoop.push(false);
2081 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2082 builder.nextSwitchSegment(segmentBlocks, s);
2083 if (codeSegments[s])
2084 codeSegments[s]->traverse(this);
2085 else
2086 builder.addSwitchBreak();
2087 }
2088 breakForLoop.pop();
2089
2090 builder.endSwitch(segmentBlocks);
2091
2092 return false;
2093}
2094
2095void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2096{
2097 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002098 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002099
2100 builder.clearAccessChain();
2101 builder.setAccessChainRValue(constant);
2102}
2103
2104bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2105{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002106 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002107 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002108
2109 // Loop control:
2110 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2111
2112 // TODO: dependency length
2113
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002114 // Spec requires back edges to target header blocks, and every header block
2115 // must dominate its merge block. Make a header block first to ensure these
2116 // conditions are met. By definition, it will contain OpLoopMerge, followed
2117 // by a block-ending branch. But we don't want to put any other body/test
2118 // instructions in it, since the body/test may have arbitrary instructions,
2119 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002120 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002121 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002122 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002123 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002124 spv::Block& test = builder.makeNewBlock();
2125 builder.createBranch(&test);
2126
2127 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002128 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002129 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002130 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2131
2132 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002133 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002134 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002135 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002136 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002137 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002138
2139 builder.setBuildPoint(&blocks.continue_target);
2140 if (node->getTerminal())
2141 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002142 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002143 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002144 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002145 builder.createBranch(&blocks.body);
2146
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002147 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002148 builder.setBuildPoint(&blocks.body);
2149 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002150 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002151 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002152 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002153
2154 builder.setBuildPoint(&blocks.continue_target);
2155 if (node->getTerminal())
2156 node->getTerminal()->traverse(this);
2157 if (node->getTest()) {
2158 node->getTest()->traverse(this);
2159 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002160 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002161 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002162 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002163 // TODO: unless there was a break/return/discard instruction
2164 // somewhere in the body, this is an infinite loop, so we should
2165 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002166 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002167 }
John Kessenich140f3df2015-06-26 16:58:36 -06002168 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002169 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002170 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002171 return false;
2172}
2173
2174bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2175{
2176 if (node->getExpression())
2177 node->getExpression()->traverse(this);
2178
John Kesseniche485c7a2017-05-31 18:50:53 -06002179 builder.setLine(node->getLoc().line);
2180
John Kessenich140f3df2015-06-26 16:58:36 -06002181 switch (node->getFlowOp()) {
2182 case glslang::EOpKill:
2183 builder.makeDiscard();
2184 break;
2185 case glslang::EOpBreak:
2186 if (breakForLoop.top())
2187 builder.createLoopExit();
2188 else
2189 builder.addSwitchBreak();
2190 break;
2191 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002192 builder.createLoopContinue();
2193 break;
2194 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002195 if (node->getExpression()) {
2196 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2197 spv::Id returnId = accessChainLoad(glslangReturnType);
2198 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2199 builder.clearAccessChain();
2200 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2201 builder.setAccessChainLValue(copyId);
2202 multiTypeStore(glslangReturnType, returnId);
2203 returnId = builder.createLoad(copyId);
2204 }
2205 builder.makeReturn(false, returnId);
2206 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002207 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002208
2209 builder.clearAccessChain();
2210 break;
2211
2212 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002213 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002214 break;
2215 }
2216
2217 return false;
2218}
2219
2220spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2221{
qining25262b32016-05-06 17:25:16 -04002222 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002223 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002224 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002225 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002226 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002227 }
2228
2229 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002230 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002231 spv::Id spvType = convertGlslangToSpvType(node->getType());
2232
Rex Xuf89ad982017-04-07 23:22:33 +08002233#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002234 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2235 node->getType().containsBasicType(glslang::EbtInt16) ||
2236 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002237 if (contains16BitType) {
2238 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2239 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2240 builder.addCapability(spv::CapabilityStorageInputOutput16);
2241 } else if (storageClass == spv::StorageClassPushConstant) {
2242 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2243 builder.addCapability(spv::CapabilityStoragePushConstant16);
2244 } else if (storageClass == spv::StorageClassUniform) {
2245 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2246 builder.addCapability(spv::CapabilityStorageUniform16);
2247 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2248 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2249 }
2250 }
2251#endif
2252
John Kessenich140f3df2015-06-26 16:58:36 -06002253 const char* name = node->getName().c_str();
2254 if (glslang::IsAnonymous(name))
2255 name = "";
2256
2257 return builder.createVariable(storageClass, spvType, name);
2258}
2259
2260// Return type Id of the sampled type.
2261spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2262{
2263 switch (sampler.type) {
2264 case glslang::EbtFloat: return builder.makeFloatType(32);
2265 case glslang::EbtInt: return builder.makeIntType(32);
2266 case glslang::EbtUint: return builder.makeUintType(32);
2267 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002268 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002269 return builder.makeFloatType(32);
2270 }
2271}
2272
John Kessenich8c8505c2016-07-26 12:50:38 -06002273// If node is a swizzle operation, return the type that should be used if
2274// the swizzle base is first consumed by another operation, before the swizzle
2275// is applied.
2276spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2277{
John Kessenichecba76f2017-01-06 00:34:48 -07002278 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002279 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2280 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2281 else
2282 return spv::NoType;
2283}
2284
2285// When inverting a swizzle with a parent op, this function
2286// will apply the swizzle operation to a completed parent operation.
2287spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2288{
2289 std::vector<unsigned> swizzle;
2290 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2291 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2292}
2293
John Kessenich8c8505c2016-07-26 12:50:38 -06002294// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2295void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2296{
2297 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2298 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2299 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2300}
2301
John Kessenich3ac051e2015-12-20 11:29:16 -07002302// Convert from a glslang type to an SPV type, by calling into a
2303// recursive version of this function. This establishes the inherited
2304// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002305spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2306{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002307 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002308}
2309
2310// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002311// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002312// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002313spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002314{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002315 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002316
2317 switch (type.getBasicType()) {
2318 case glslang::EbtVoid:
2319 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002320 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002321 break;
2322 case glslang::EbtFloat:
2323 spvType = builder.makeFloatType(32);
2324 break;
2325 case glslang::EbtDouble:
2326 spvType = builder.makeFloatType(64);
2327 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002328#ifdef AMD_EXTENSIONS
2329 case glslang::EbtFloat16:
2330 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002331 spvType = builder.makeFloatType(16);
2332 break;
2333#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002334 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002335 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2336 // a 32-bit int where non-0 means true.
2337 if (explicitLayout != glslang::ElpNone)
2338 spvType = builder.makeUintType(32);
2339 else
2340 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002341 break;
2342 case glslang::EbtInt:
2343 spvType = builder.makeIntType(32);
2344 break;
2345 case glslang::EbtUint:
2346 spvType = builder.makeUintType(32);
2347 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002348 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002349 spvType = builder.makeIntType(64);
2350 break;
2351 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002352 spvType = builder.makeUintType(64);
2353 break;
Rex Xucabbb782017-03-24 13:41:14 +08002354#ifdef AMD_EXTENSIONS
2355 case glslang::EbtInt16:
2356 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2357 spvType = builder.makeIntType(16);
2358 break;
2359 case glslang::EbtUint16:
2360 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2361 spvType = builder.makeUintType(16);
2362 break;
2363#endif
John Kessenich426394d2015-07-23 10:22:48 -06002364 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002365 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002366 spvType = builder.makeUintType(32);
2367 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002368 case glslang::EbtSampler:
2369 {
2370 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002371 if (sampler.sampler) {
2372 // pure sampler
2373 spvType = builder.makeSamplerType();
2374 } else {
2375 // an image is present, make its type
2376 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2377 sampler.image ? 2 : 1, TranslateImageFormat(type));
2378 if (sampler.combined) {
2379 // already has both image and sampler, make the combined type
2380 spvType = builder.makeSampledImageType(spvType);
2381 }
John Kessenich55e7d112015-11-15 21:33:39 -07002382 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002383 }
John Kessenich140f3df2015-06-26 16:58:36 -06002384 break;
2385 case glslang::EbtStruct:
2386 case glslang::EbtBlock:
2387 {
2388 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002389 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002390
2391 // Try to share structs for different layouts, but not yet for other
2392 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002393 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002394 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002395 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002396 break;
2397
2398 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002399 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002400 memberRemapper[glslangMembers].resize(glslangMembers->size());
2401 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002402 }
2403 break;
2404 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002405 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002406 break;
2407 }
2408
2409 if (type.isMatrix())
2410 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2411 else {
2412 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2413 if (type.getVectorSize() > 1)
2414 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2415 }
2416
2417 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002418 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2419
John Kessenichc9a80832015-09-12 12:17:44 -06002420 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002421 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002422 // We need to decorate array strides for types needing explicit layout, except blocks.
2423 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002424 // Use a dummy glslang type for querying internal strides of
2425 // arrays of arrays, but using just a one-dimensional array.
2426 glslang::TType simpleArrayType(type, 0); // deference type of the array
2427 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2428 simpleArrayType.getArraySizes().dereference();
2429
2430 // Will compute the higher-order strides here, rather than making a whole
2431 // pile of types and doing repetitive recursion on their contents.
2432 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2433 }
John Kessenichf8842e52016-01-04 19:22:56 -07002434
2435 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002436 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002437 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002438 if (stride > 0)
2439 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002440 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002441 }
2442 } else {
2443 // single-dimensional array, and don't yet have stride
2444
John Kessenichf8842e52016-01-04 19:22:56 -07002445 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002446 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2447 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002448 }
John Kessenich31ed4832015-09-09 17:51:38 -06002449
John Kessenichc9a80832015-09-12 12:17:44 -06002450 // Do the outer dimension, which might not be known for a runtime-sized array
2451 if (type.isRuntimeSizedArray()) {
2452 spvType = builder.makeRuntimeArray(spvType);
2453 } else {
2454 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002455 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002456 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002457 if (stride > 0)
2458 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002459 }
2460
2461 return spvType;
2462}
2463
John Kessenich0e737842017-03-24 18:38:16 -06002464// TODO: this functionality should exist at a higher level, in creating the AST
2465//
2466// Identify interface members that don't have their required extension turned on.
2467//
2468bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2469{
2470 auto& extensions = glslangIntermediate->getRequestedExtensions();
2471
Rex Xubcf291a2017-03-29 23:01:36 +08002472 if (member.getFieldName() == "gl_ViewportMask" &&
2473 extensions.find("GL_NV_viewport_array2") == extensions.end())
2474 return true;
2475 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2476 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2477 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002478 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2479 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2480 return true;
2481 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2482 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2483 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002484 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2485 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2486 return true;
John Kessenichd6be6da2017-08-17 23:49:39 -06002487 if ((member.getFieldName() == "gl_ViewportIndex" || member.getFieldName() == "gl_Layer") &&
2488 extensions.find(glslang::E_GL_ARB_shader_viewport_layer_array) == extensions.end() &&
John Kessenich786e8792017-08-19 15:54:49 -06002489 extensions.find("GL_NV_viewport_array2") == extensions.end())
John Kessenichd6be6da2017-08-17 23:49:39 -06002490 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002491
2492 return false;
2493};
2494
John Kessenich6090df02016-06-30 21:18:02 -06002495// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2496// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2497// Mutually recursive with convertGlslangToSpvType().
2498spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2499 const glslang::TTypeList* glslangMembers,
2500 glslang::TLayoutPacking explicitLayout,
2501 const glslang::TQualifier& qualifier)
2502{
2503 // Create a vector of struct types for SPIR-V to consume
2504 std::vector<spv::Id> spvMembers;
2505 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 -06002506 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2507 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2508 if (glslangMember.hiddenMember()) {
2509 ++memberDelta;
2510 if (type.getBasicType() == glslang::EbtBlock)
2511 memberRemapper[glslangMembers][i] = -1;
2512 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002513 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002514 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002515 if (filterMember(glslangMember))
2516 continue;
2517 }
John Kessenich6090df02016-06-30 21:18:02 -06002518 // modify just this child's view of the qualifier
2519 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2520 InheritQualifiers(memberQualifier, qualifier);
2521
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002522 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002523 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002524 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002525
2526 // recurse
2527 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2528 }
2529 }
2530
2531 // Make the SPIR-V type
2532 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002533 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002534 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2535
2536 // Decorate it
2537 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2538
2539 return spvType;
2540}
2541
2542void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2543 const glslang::TTypeList* glslangMembers,
2544 glslang::TLayoutPacking explicitLayout,
2545 const glslang::TQualifier& qualifier,
2546 spv::Id spvType)
2547{
2548 // Name and decorate the non-hidden members
2549 int offset = -1;
2550 int locationOffset = 0; // for use within the members of this struct
2551 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2552 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2553 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002554 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002555 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002556 if (filterMember(glslangMember))
2557 continue;
2558 }
John Kessenich6090df02016-06-30 21:18:02 -06002559
2560 // modify just this child's view of the qualifier
2561 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2562 InheritQualifiers(memberQualifier, qualifier);
2563
2564 // using -1 above to indicate a hidden member
2565 if (member >= 0) {
2566 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2567 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2568 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2569 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002570 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2571 type.getQualifier().storage == glslang::EvqVaryingOut) {
2572 if (type.getBasicType() == glslang::EbtBlock ||
2573 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002574 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2575 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2576 }
2577 }
2578 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2579
Rex Xu286ca432017-07-27 14:33:16 +08002580 if (type.getBasicType() == glslang::EbtBlock &&
2581 qualifier.storage == glslang::EvqBuffer) {
2582 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002583 std::vector<spv::Decoration> memory;
2584 TranslateMemoryDecoration(memberQualifier, memory);
2585 for (unsigned int i = 0; i < memory.size(); ++i)
2586 addMemberDecoration(spvType, member, memory[i]);
2587 }
2588
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002589 // Location assignment was already completed correctly by the front end,
2590 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002591 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002592 // ill-specified and decisions have been made to not allow this.
2593 if (! type.isArray() && memberQualifier.hasLocation())
2594 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002595
John Kessenich2f47bc92016-06-30 21:47:35 -06002596 if (qualifier.hasLocation()) // track for upcoming inheritance
2597 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2598
John Kessenich6090df02016-06-30 21:18:02 -06002599 // component, XFB, others
2600 if (glslangMember.getQualifier().hasComponent())
2601 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2602 if (glslangMember.getQualifier().hasXfbOffset())
2603 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2604 else if (explicitLayout != glslang::ElpNone) {
2605 // figure out what to do with offset, which is accumulating
2606 int nextOffset;
2607 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2608 if (offset >= 0)
2609 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2610 offset = nextOffset;
2611 }
2612
2613 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2614 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2615
2616 // built-in variable decorations
2617 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002618 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002619 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002620
2621#ifdef NV_EXTENSIONS
2622 if (builtIn == spv::BuiltInLayer) {
2623 // SPV_NV_viewport_array2 extension
2624 if (glslangMember.getQualifier().layoutViewportRelative){
2625 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2626 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2627 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2628 }
2629 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2630 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2631 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2632 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2633 }
2634 }
chaocdf3956c2017-02-14 14:52:34 -08002635 if (glslangMember.getQualifier().layoutPassthrough) {
2636 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2637 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2638 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2639 }
chaoc771d89f2017-01-13 01:10:53 -08002640#endif
John Kessenich6090df02016-06-30 21:18:02 -06002641 }
2642 }
2643
2644 // Decorate the structure
2645 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002646 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002647 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2648 builder.addCapability(spv::CapabilityGeometryStreams);
2649 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2650 }
2651 if (glslangIntermediate->getXfbMode()) {
2652 builder.addCapability(spv::CapabilityTransformFeedback);
2653 if (type.getQualifier().hasXfbStride())
2654 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2655 if (type.getQualifier().hasXfbBuffer())
2656 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2657 }
2658}
2659
John Kessenich6c292d32016-02-15 20:58:50 -07002660// Turn the expression forming the array size into an id.
2661// This is not quite trivial, because of specialization constants.
2662// Sometimes, a raw constant is turned into an Id, and sometimes
2663// a specialization constant expression is.
2664spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2665{
2666 // First, see if this is sized with a node, meaning a specialization constant:
2667 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2668 if (specNode != nullptr) {
2669 builder.clearAccessChain();
2670 specNode->traverse(this);
2671 return accessChainLoad(specNode->getAsTyped()->getType());
2672 }
qining25262b32016-05-06 17:25:16 -04002673
John Kessenich6c292d32016-02-15 20:58:50 -07002674 // Otherwise, need a compile-time (front end) size, get it:
2675 int size = arraySizes.getDimSize(dim);
2676 assert(size > 0);
2677 return builder.makeUintConstant(size);
2678}
2679
John Kessenich103bef92016-02-08 21:38:15 -07002680// Wrap the builder's accessChainLoad to:
2681// - localize handling of RelaxedPrecision
2682// - use the SPIR-V inferred type instead of another conversion of the glslang type
2683// (avoids unnecessary work and possible type punning for structures)
2684// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002685spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2686{
John Kessenich103bef92016-02-08 21:38:15 -07002687 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2688 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2689
2690 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002691 if (type.getBasicType() == glslang::EbtBool) {
2692 if (builder.isScalarType(nominalTypeId)) {
2693 // Conversion for bool
2694 spv::Id boolType = builder.makeBoolType();
2695 if (nominalTypeId != boolType)
2696 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2697 } else if (builder.isVectorType(nominalTypeId)) {
2698 // Conversion for bvec
2699 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2700 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2701 if (nominalTypeId != bvecType)
2702 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2703 }
2704 }
John Kessenich103bef92016-02-08 21:38:15 -07002705
2706 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002707}
2708
Rex Xu27253232016-02-23 17:51:09 +08002709// Wrap the builder's accessChainStore to:
2710// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002711//
2712// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002713void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2714{
2715 // Need to convert to abstract types when necessary
2716 if (type.getBasicType() == glslang::EbtBool) {
2717 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2718
2719 if (builder.isScalarType(nominalTypeId)) {
2720 // Conversion for bool
2721 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002722 if (nominalTypeId != boolType) {
2723 // keep these outside arguments, for determinant order-of-evaluation
2724 spv::Id one = builder.makeUintConstant(1);
2725 spv::Id zero = builder.makeUintConstant(0);
2726 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2727 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002728 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002729 } else if (builder.isVectorType(nominalTypeId)) {
2730 // Conversion for bvec
2731 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2732 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002733 if (nominalTypeId != bvecType) {
2734 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002735 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2736 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2737 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002738 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002739 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2740 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002741 }
2742 }
2743
2744 builder.accessChainStore(rvalue);
2745}
2746
John Kessenich4bf71552016-09-02 11:20:21 -06002747// For storing when types match at the glslang level, but not might match at the
2748// SPIR-V level.
2749//
2750// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002751// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002752// as in a member-decorated way.
2753//
2754// NOTE: This function can handle any store request; if it's not special it
2755// simplifies to a simple OpStore.
2756//
2757// Implicitly uses the existing builder.accessChain as the storage target.
2758void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2759{
John Kessenichb3e24e42016-09-11 12:33:43 -06002760 // we only do the complex path here if it's an aggregate
2761 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002762 accessChainStore(type, rValue);
2763 return;
2764 }
2765
John Kessenichb3e24e42016-09-11 12:33:43 -06002766 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002767 spv::Id rType = builder.getTypeId(rValue);
2768 spv::Id lValue = builder.accessChainGetLValue();
2769 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2770 if (lType == rType) {
2771 accessChainStore(type, rValue);
2772 return;
2773 }
2774
John Kessenichb3e24e42016-09-11 12:33:43 -06002775 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002776 // where the two types were the same type in GLSL. This requires member
2777 // by member copy, recursively.
2778
John Kessenichb3e24e42016-09-11 12:33:43 -06002779 // If an array, copy element by element.
2780 if (type.isArray()) {
2781 glslang::TType glslangElementType(type, 0);
2782 spv::Id elementRType = builder.getContainedTypeId(rType);
2783 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2784 // get the source member
2785 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002786
John Kessenichb3e24e42016-09-11 12:33:43 -06002787 // set up the target storage
2788 builder.clearAccessChain();
2789 builder.setAccessChainLValue(lValue);
2790 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002791
John Kessenichb3e24e42016-09-11 12:33:43 -06002792 // store the member
2793 multiTypeStore(glslangElementType, elementRValue);
2794 }
2795 } else {
2796 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002797
John Kessenichb3e24e42016-09-11 12:33:43 -06002798 // loop over structure members
2799 const glslang::TTypeList& members = *type.getStruct();
2800 for (int m = 0; m < (int)members.size(); ++m) {
2801 const glslang::TType& glslangMemberType = *members[m].type;
2802
2803 // get the source member
2804 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2805 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2806
2807 // set up the target storage
2808 builder.clearAccessChain();
2809 builder.setAccessChainLValue(lValue);
2810 builder.accessChainPush(builder.makeIntConstant(m));
2811
2812 // store the member
2813 multiTypeStore(glslangMemberType, memberRValue);
2814 }
John Kessenich4bf71552016-09-02 11:20:21 -06002815 }
2816}
2817
John Kessenichf85e8062015-12-19 13:57:10 -07002818// Decide whether or not this type should be
2819// decorated with offsets and strides, and if so
2820// whether std140 or std430 rules should be applied.
2821glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002822{
John Kessenichf85e8062015-12-19 13:57:10 -07002823 // has to be a block
2824 if (type.getBasicType() != glslang::EbtBlock)
2825 return glslang::ElpNone;
2826
2827 // has to be a uniform or buffer block
2828 if (type.getQualifier().storage != glslang::EvqUniform &&
2829 type.getQualifier().storage != glslang::EvqBuffer)
2830 return glslang::ElpNone;
2831
2832 // return the layout to use
2833 switch (type.getQualifier().layoutPacking) {
2834 case glslang::ElpStd140:
2835 case glslang::ElpStd430:
2836 return type.getQualifier().layoutPacking;
2837 default:
2838 return glslang::ElpNone;
2839 }
John Kessenich31ed4832015-09-09 17:51:38 -06002840}
2841
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002842// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002843int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002844{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002845 int size;
John Kessenich49987892015-12-29 17:11:44 -07002846 int stride;
2847 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002848
2849 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002850}
2851
John Kessenich49987892015-12-29 17:11:44 -07002852// 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 -07002853// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002854int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002855{
John Kessenich49987892015-12-29 17:11:44 -07002856 glslang::TType elementType;
2857 elementType.shallowCopy(matrixType);
2858 elementType.clearArraySizes();
2859
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002860 int size;
John Kessenich49987892015-12-29 17:11:44 -07002861 int stride;
2862 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2863
2864 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002865}
2866
John Kessenich5e4b1242015-08-06 22:53:06 -06002867// Given a member type of a struct, realign the current offset for it, and compute
2868// the next (not yet aligned) offset for the next member, which will get aligned
2869// on the next call.
2870// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2871// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2872// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002873void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002874 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002875{
2876 // this will get a positive value when deemed necessary
2877 nextOffset = -1;
2878
John Kessenich5e4b1242015-08-06 22:53:06 -06002879 // override anything in currentOffset with user-set offset
2880 if (memberType.getQualifier().hasOffset())
2881 currentOffset = memberType.getQualifier().layoutOffset;
2882
2883 // It could be that current linker usage in glslang updated all the layoutOffset,
2884 // in which case the following code does not matter. But, that's not quite right
2885 // once cross-compilation unit GLSL validation is done, as the original user
2886 // settings are needed in layoutOffset, and then the following will come into play.
2887
John Kessenichf85e8062015-12-19 13:57:10 -07002888 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002889 if (! memberType.getQualifier().hasOffset())
2890 currentOffset = -1;
2891
2892 return;
2893 }
2894
John Kessenichf85e8062015-12-19 13:57:10 -07002895 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002896 if (currentOffset < 0)
2897 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002898
John Kessenich5e4b1242015-08-06 22:53:06 -06002899 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2900 // but possibly not yet correctly aligned.
2901
2902 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002903 int dummyStride;
2904 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002905
2906 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002907 // TODO: make this consistent in early phases of code:
2908 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2909 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2910 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002911 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002912 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002913 int dummySize;
2914 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2915 if (componentAlignment <= 4)
2916 memberAlignment = componentAlignment;
2917 }
2918
2919 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002920 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002921
2922 // Bump up to vec4 if there is a bad straddle
2923 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2924 glslang::RoundToPow2(currentOffset, 16);
2925
John Kessenich5e4b1242015-08-06 22:53:06 -06002926 nextOffset = currentOffset + memberSize;
2927}
2928
David Netoa901ffe2016-06-08 14:11:40 +01002929void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002930{
David Netoa901ffe2016-06-08 14:11:40 +01002931 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2932 switch (glslangBuiltIn)
2933 {
2934 case glslang::EbvClipDistance:
2935 case glslang::EbvCullDistance:
2936 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002937#ifdef NV_EXTENSIONS
2938 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002939 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002940 case glslang::EbvViewportMaskNV:
2941 case glslang::EbvSecondaryPositionNV:
2942 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002943 case glslang::EbvPositionPerViewNV:
2944 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002945#endif
David Netoa901ffe2016-06-08 14:11:40 +01002946 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2947 // Alternately, we could just call this for any glslang built-in, since the
2948 // capability already guards against duplicates.
2949 TranslateBuiltInDecoration(glslangBuiltIn, false);
2950 break;
2951 default:
2952 // Capabilities were already generated when the struct was declared.
2953 break;
2954 }
John Kessenichebb50532016-05-16 19:22:05 -06002955}
2956
John Kessenich6fccb3c2016-09-19 16:01:41 -06002957bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002958{
John Kessenicheee9d532016-09-19 18:09:30 -06002959 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002960}
2961
2962// Make all the functions, skeletally, without actually visiting their bodies.
2963void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2964{
John Kessenichfad62972017-07-18 02:35:46 -06002965 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2966 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2967 if (paramPrecision != spv::NoPrecision)
2968 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002969 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002970 };
2971
John Kessenich140f3df2015-06-26 16:58:36 -06002972 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2973 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002974 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002975 continue;
2976
2977 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002978 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002979 //
qining25262b32016-05-06 17:25:16 -04002980 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002981 // function. What it is an address of varies:
2982 //
John Kessenich4bf71552016-09-02 11:20:21 -06002983 // - "in" parameters not marked as "const" can be written to without modifying the calling
2984 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002985 //
2986 // - "const in" parameters can just be the r-value, as no writes need occur.
2987 //
John Kessenich4bf71552016-09-02 11:20:21 -06002988 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2989 // 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 -06002990
2991 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002992 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002993 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2994
John Kessenichfad62972017-07-18 02:35:46 -06002995 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2996 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002997
John Kessenichfad62972017-07-18 02:35:46 -06002998 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06002999 for (int p = 0; p < (int)parameters.size(); ++p) {
3000 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3001 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06003002 // can we pass by reference?
3003 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06003004 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06003005 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06003006 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06003007 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07003008 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003009 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3010 else
John Kessenich4bf71552016-09-02 11:20:21 -06003011 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003012 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003013 paramTypes.push_back(typeId);
3014 }
3015
3016 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003017 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3018 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003019 glslFunction->getName().c_str(), paramTypes,
3020 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003021 if (implicitThis)
3022 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003023
3024 // Track function to emit/call later
3025 functionMap[glslFunction->getName().c_str()] = function;
3026
3027 // Set the parameter id's
3028 for (int p = 0; p < (int)parameters.size(); ++p) {
3029 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3030 // give a name too
3031 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3032 }
3033 }
3034}
3035
3036// Process all the initializers, while skipping the functions and link objects
3037void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3038{
3039 builder.setBuildPoint(shaderEntry->getLastBlock());
3040 for (int i = 0; i < (int)initializers.size(); ++i) {
3041 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3042 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3043
3044 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003045 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003046 initializer->traverse(this);
3047 }
3048 }
3049}
3050
3051// Process all the functions, while skipping initializers.
3052void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3053{
3054 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3055 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003056 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003057 node->traverse(this);
3058 }
3059}
3060
3061void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3062{
qining25262b32016-05-06 17:25:16 -04003063 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003064 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003065 currentFunction = functionMap[node->getName().c_str()];
3066 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003067 builder.setBuildPoint(functionBlock);
3068}
3069
Rex Xu04db3f52015-09-16 11:44:02 +08003070void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003071{
Rex Xufc618912015-09-09 16:42:49 +08003072 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003073
3074 glslang::TSampler sampler = {};
3075 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003076 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003077 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3078 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3079 }
3080
John Kessenich140f3df2015-06-26 16:58:36 -06003081 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3082 builder.clearAccessChain();
3083 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003084
3085 // Special case l-value operands
3086 bool lvalue = false;
3087 switch (node.getOp()) {
3088 case glslang::EOpImageAtomicAdd:
3089 case glslang::EOpImageAtomicMin:
3090 case glslang::EOpImageAtomicMax:
3091 case glslang::EOpImageAtomicAnd:
3092 case glslang::EOpImageAtomicOr:
3093 case glslang::EOpImageAtomicXor:
3094 case glslang::EOpImageAtomicExchange:
3095 case glslang::EOpImageAtomicCompSwap:
3096 if (i == 0)
3097 lvalue = true;
3098 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003099 case glslang::EOpSparseImageLoad:
3100 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3101 lvalue = true;
3102 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003103 case glslang::EOpSparseTexture:
3104 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3105 lvalue = true;
3106 break;
3107 case glslang::EOpSparseTextureClamp:
3108 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3109 lvalue = true;
3110 break;
3111 case glslang::EOpSparseTextureLod:
3112 case glslang::EOpSparseTextureOffset:
3113 if (i == 3)
3114 lvalue = true;
3115 break;
3116 case glslang::EOpSparseTextureFetch:
3117 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3118 lvalue = true;
3119 break;
3120 case glslang::EOpSparseTextureFetchOffset:
3121 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3122 lvalue = true;
3123 break;
3124 case glslang::EOpSparseTextureLodOffset:
3125 case glslang::EOpSparseTextureGrad:
3126 case glslang::EOpSparseTextureOffsetClamp:
3127 if (i == 4)
3128 lvalue = true;
3129 break;
3130 case glslang::EOpSparseTextureGradOffset:
3131 case glslang::EOpSparseTextureGradClamp:
3132 if (i == 5)
3133 lvalue = true;
3134 break;
3135 case glslang::EOpSparseTextureGradOffsetClamp:
3136 if (i == 6)
3137 lvalue = true;
3138 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003139 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003140 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3141 lvalue = true;
3142 break;
3143 case glslang::EOpSparseTextureGatherOffset:
3144 case glslang::EOpSparseTextureGatherOffsets:
3145 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3146 lvalue = true;
3147 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003148#ifdef AMD_EXTENSIONS
3149 case glslang::EOpSparseTextureGatherLod:
3150 if (i == 3)
3151 lvalue = true;
3152 break;
3153 case glslang::EOpSparseTextureGatherLodOffset:
3154 case glslang::EOpSparseTextureGatherLodOffsets:
3155 if (i == 4)
3156 lvalue = true;
3157 break;
3158#endif
Rex Xufc618912015-09-09 16:42:49 +08003159 default:
3160 break;
3161 }
3162
Rex Xu6b86d492015-09-16 17:48:22 +08003163 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003164 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003165 else
John Kessenich32cfd492016-02-02 12:37:46 -07003166 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003167 }
3168}
3169
John Kessenichfc51d282015-08-19 13:34:18 -06003170void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003171{
John Kessenichfc51d282015-08-19 13:34:18 -06003172 builder.clearAccessChain();
3173 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003174 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003175}
John Kessenich140f3df2015-06-26 16:58:36 -06003176
John Kessenichfc51d282015-08-19 13:34:18 -06003177spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3178{
John Kesseniche485c7a2017-05-31 18:50:53 -06003179 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003180 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003181
3182 builder.setLine(node->getLoc().line);
3183
John Kessenich8c8505c2016-07-26 12:50:38 -06003184 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003185
John Kessenichfc51d282015-08-19 13:34:18 -06003186 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003187 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3188 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3189 std::vector<spv::Id> arguments;
3190 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003191 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003192 else
3193 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003194 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003195
3196 spv::Builder::TextureParameters params = { };
3197 params.sampler = arguments[0];
3198
Rex Xu04db3f52015-09-16 11:44:02 +08003199 glslang::TCrackedTextureOp cracked;
3200 node->crackTexture(sampler, cracked);
3201
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003202 const bool isUnsignedResult =
3203 node->getType().getBasicType() == glslang::EbtUint64 ||
3204 node->getType().getBasicType() == glslang::EbtUint;
3205
John Kessenichfc51d282015-08-19 13:34:18 -06003206 // Check for queries
3207 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003208 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3209 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003210 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003211
John Kessenichfc51d282015-08-19 13:34:18 -06003212 switch (node->getOp()) {
3213 case glslang::EOpImageQuerySize:
3214 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003215 if (arguments.size() > 1) {
3216 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003217 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003218 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003219 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003220 case glslang::EOpImageQuerySamples:
3221 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003222 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003223 case glslang::EOpTextureQueryLod:
3224 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003225 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003226 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003227 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003228 case glslang::EOpSparseTexelsResident:
3229 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003230 default:
3231 assert(0);
3232 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003233 }
John Kessenich140f3df2015-06-26 16:58:36 -06003234 }
3235
Rex Xufc618912015-09-09 16:42:49 +08003236 // Check for image functions other than queries
3237 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003238 std::vector<spv::Id> operands;
3239 auto opIt = arguments.begin();
3240 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003241
3242 // Handle subpass operations
3243 // TODO: GLSL should change to have the "MS" only on the type rather than the
3244 // built-in function.
3245 if (cracked.subpass) {
3246 // add on the (0,0) coordinate
3247 spv::Id zero = builder.makeIntConstant(0);
3248 std::vector<spv::Id> comps;
3249 comps.push_back(zero);
3250 comps.push_back(zero);
3251 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3252 if (sampler.ms) {
3253 operands.push_back(spv::ImageOperandsSampleMask);
3254 operands.push_back(*(opIt++));
3255 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003256 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003257 }
3258
John Kessenich56bab042015-09-16 10:54:31 -06003259 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003260 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003261 if (sampler.ms) {
3262 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003263 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003264 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003265 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3266 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003267 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003268 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003269 if (sampler.ms) {
3270 operands.push_back(*(opIt + 1));
3271 operands.push_back(spv::ImageOperandsSampleMask);
3272 operands.push_back(*opIt);
3273 } else
3274 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003275 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003276 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3277 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003278 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003279 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3280 builder.addCapability(spv::CapabilitySparseResidency);
3281 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3282 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3283
3284 if (sampler.ms) {
3285 operands.push_back(spv::ImageOperandsSampleMask);
3286 operands.push_back(*opIt++);
3287 }
3288
3289 // Create the return type that was a special structure
3290 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003291 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003292 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3293 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3294
3295 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3296
3297 // Decode the return type
3298 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3299 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003300 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003301 // Process image atomic operations
3302
3303 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3304 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003305 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003306
John Kessenich8c8505c2016-07-26 12:50:38 -06003307 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003308 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003309
3310 std::vector<spv::Id> operands;
3311 operands.push_back(pointer);
3312 for (; opIt != arguments.end(); ++opIt)
3313 operands.push_back(*opIt);
3314
John Kessenich8c8505c2016-07-26 12:50:38 -06003315 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003316 }
3317 }
3318
3319 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003320 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003321 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3322
John Kessenichfc51d282015-08-19 13:34:18 -06003323 // check for bias argument
3324 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003325#ifdef AMD_EXTENSIONS
3326 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3327#else
Rex Xu71519fe2015-11-11 15:35:47 +08003328 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003329#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003330 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003331#ifdef AMD_EXTENSIONS
3332 if (cracked.gather)
3333 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3334#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003335 if (cracked.offset)
3336 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003337#ifdef AMD_EXTENSIONS
3338 else if (cracked.offsets)
3339 ++nonBiasArgCount;
3340#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003341 if (cracked.grad)
3342 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003343 if (cracked.lodClamp)
3344 ++nonBiasArgCount;
3345 if (sparse)
3346 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003347
3348 if ((int)arguments.size() > nonBiasArgCount)
3349 bias = true;
3350 }
3351
John Kessenicha5c33d62016-06-02 23:45:21 -06003352 // See if the sampler param should really be just the SPV image part
3353 if (cracked.fetch) {
3354 // a fetch needs to have the image extracted first
3355 if (builder.isSampledImage(params.sampler))
3356 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3357 }
3358
Rex Xu225e0fc2016-11-17 17:47:59 +08003359#ifdef AMD_EXTENSIONS
3360 if (cracked.gather) {
3361 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3362 if (bias || cracked.lod ||
3363 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3364 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003365 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003366 }
3367 }
3368#endif
3369
John Kessenichfc51d282015-08-19 13:34:18 -06003370 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003371
John Kessenichfc51d282015-08-19 13:34:18 -06003372 params.coords = arguments[1];
3373 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003374 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003375
3376 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003377 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003378 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003379 ++extraArgs;
3380 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003381 params.Dref = arguments[2];
3382 ++extraArgs;
3383 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003384 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003385 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003386 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003387 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003388 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003389 dRefComp = builder.getNumComponents(params.coords) - 1;
3390 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003391 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3392 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003393
3394 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003395 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003396 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003397 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003398 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3399 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3400 noImplicitLod = true;
3401 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003402
3403 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003404 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003405 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003406 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003407 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003408
3409 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003410 if (cracked.grad) {
3411 params.gradX = arguments[2 + extraArgs];
3412 params.gradY = arguments[3 + extraArgs];
3413 extraArgs += 2;
3414 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003415
3416 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003417 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003418 params.offset = arguments[2 + extraArgs];
3419 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003420 } else if (cracked.offsets) {
3421 params.offsets = arguments[2 + extraArgs];
3422 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003423 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003424
3425 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003426 if (cracked.lodClamp) {
3427 params.lodClamp = arguments[2 + extraArgs];
3428 ++extraArgs;
3429 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003430
3431 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003432 if (sparse) {
3433 params.texelOut = arguments[2 + extraArgs];
3434 ++extraArgs;
3435 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003436
John Kessenich76d4dfc2016-06-16 12:43:23 -06003437 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003438 if (cracked.gather && ! sampler.shadow) {
3439 // default component is 0, if missing, otherwise an argument
3440 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003441 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003442 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003443 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003444 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003445 }
3446
3447 // bias
3448 if (bias) {
3449 params.bias = arguments[2 + extraArgs];
3450 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003451 }
John Kessenichfc51d282015-08-19 13:34:18 -06003452
John Kessenich65336482016-06-16 14:06:26 -06003453 // projective component (might not to move)
3454 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3455 // are divided by the last component of P."
3456 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3457 // unused components will appear after all used components."
3458 if (cracked.proj) {
3459 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3460 int projTargetComp;
3461 switch (sampler.dim) {
3462 case glslang::Esd1D: projTargetComp = 1; break;
3463 case glslang::Esd2D: projTargetComp = 2; break;
3464 case glslang::EsdRect: projTargetComp = 2; break;
3465 default: projTargetComp = projSourceComp; break;
3466 }
3467 // copy the projective coordinate if we have to
3468 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003469 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003470 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3471 projSourceComp);
3472 params.coords = builder.createCompositeInsert(projComp, params.coords,
3473 builder.getTypeId(params.coords), projTargetComp);
3474 }
3475 }
3476
John Kessenich8c8505c2016-07-26 12:50:38 -06003477 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003478}
3479
3480spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3481{
3482 // Grab the function's pointer from the previously created function
3483 spv::Function* function = functionMap[node->getName().c_str()];
3484 if (! function)
3485 return 0;
3486
3487 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3488 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3489
3490 // See comments in makeFunctions() for details about the semantics for parameter passing.
3491 //
3492 // These imply we need a four step process:
3493 // 1. Evaluate the arguments
3494 // 2. Allocate and make copies of in, out, and inout arguments
3495 // 3. Make the call
3496 // 4. Copy back the results
3497
3498 // 1. Evaluate the arguments
3499 std::vector<spv::Builder::AccessChain> lValues;
3500 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003501 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003502 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003503 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003504 // build l-value
3505 builder.clearAccessChain();
3506 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003507 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003508 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003509 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003510 // save l-value
3511 lValues.push_back(builder.getAccessChain());
3512 } else {
3513 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003514 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003515 }
3516 }
3517
3518 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3519 // copy the original into that space.
3520 //
3521 // Also, build up the list of actual arguments to pass in for the call
3522 int lValueCount = 0;
3523 int rValueCount = 0;
3524 std::vector<spv::Id> spvArgs;
3525 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003526 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003527 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003528 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003529 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3530 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003531 builder.setAccessChain(lValues[lValueCount]);
3532 arg = builder.accessChainGetLValue();
3533 ++lValueCount;
3534 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003535 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003536 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3537 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3538 // need to copy the input into output space
3539 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003540 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003541 builder.clearAccessChain();
3542 builder.setAccessChainLValue(arg);
3543 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003544 }
3545 ++lValueCount;
3546 } else {
3547 arg = rValues[rValueCount];
3548 ++rValueCount;
3549 }
3550 spvArgs.push_back(arg);
3551 }
3552
3553 // 3. Make the call.
3554 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003555 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003556
3557 // 4. Copy back out an "out" arguments.
3558 lValueCount = 0;
3559 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003560 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003561 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3562 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3563 spv::Id copy = builder.createLoad(spvArgs[a]);
3564 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003565 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003566 }
3567 ++lValueCount;
3568 }
3569 }
3570
3571 return result;
3572}
3573
3574// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003575spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3576 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003577 spv::Id typeId, spv::Id left, spv::Id right,
3578 glslang::TBasicType typeProxy, bool reduceComparison)
3579{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003580#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003581 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003582 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3583#else
Rex Xucabbb782017-03-24 13:41:14 +08003584 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003585 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003586#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003587 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003588
3589 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003590 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003591 bool comparison = false;
3592
3593 switch (op) {
3594 case glslang::EOpAdd:
3595 case glslang::EOpAddAssign:
3596 if (isFloat)
3597 binOp = spv::OpFAdd;
3598 else
3599 binOp = spv::OpIAdd;
3600 break;
3601 case glslang::EOpSub:
3602 case glslang::EOpSubAssign:
3603 if (isFloat)
3604 binOp = spv::OpFSub;
3605 else
3606 binOp = spv::OpISub;
3607 break;
3608 case glslang::EOpMul:
3609 case glslang::EOpMulAssign:
3610 if (isFloat)
3611 binOp = spv::OpFMul;
3612 else
3613 binOp = spv::OpIMul;
3614 break;
3615 case glslang::EOpVectorTimesScalar:
3616 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003617 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003618 if (builder.isVector(right))
3619 std::swap(left, right);
3620 assert(builder.isScalar(right));
3621 needMatchingVectors = false;
3622 binOp = spv::OpVectorTimesScalar;
3623 } else
3624 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003625 break;
3626 case glslang::EOpVectorTimesMatrix:
3627 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003628 binOp = spv::OpVectorTimesMatrix;
3629 break;
3630 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003631 binOp = spv::OpMatrixTimesVector;
3632 break;
3633 case glslang::EOpMatrixTimesScalar:
3634 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003635 binOp = spv::OpMatrixTimesScalar;
3636 break;
3637 case glslang::EOpMatrixTimesMatrix:
3638 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003639 binOp = spv::OpMatrixTimesMatrix;
3640 break;
3641 case glslang::EOpOuterProduct:
3642 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003643 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003644 break;
3645
3646 case glslang::EOpDiv:
3647 case glslang::EOpDivAssign:
3648 if (isFloat)
3649 binOp = spv::OpFDiv;
3650 else if (isUnsigned)
3651 binOp = spv::OpUDiv;
3652 else
3653 binOp = spv::OpSDiv;
3654 break;
3655 case glslang::EOpMod:
3656 case glslang::EOpModAssign:
3657 if (isFloat)
3658 binOp = spv::OpFMod;
3659 else if (isUnsigned)
3660 binOp = spv::OpUMod;
3661 else
3662 binOp = spv::OpSMod;
3663 break;
3664 case glslang::EOpRightShift:
3665 case glslang::EOpRightShiftAssign:
3666 if (isUnsigned)
3667 binOp = spv::OpShiftRightLogical;
3668 else
3669 binOp = spv::OpShiftRightArithmetic;
3670 break;
3671 case glslang::EOpLeftShift:
3672 case glslang::EOpLeftShiftAssign:
3673 binOp = spv::OpShiftLeftLogical;
3674 break;
3675 case glslang::EOpAnd:
3676 case glslang::EOpAndAssign:
3677 binOp = spv::OpBitwiseAnd;
3678 break;
3679 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003680 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003681 binOp = spv::OpLogicalAnd;
3682 break;
3683 case glslang::EOpInclusiveOr:
3684 case glslang::EOpInclusiveOrAssign:
3685 binOp = spv::OpBitwiseOr;
3686 break;
3687 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003688 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003689 binOp = spv::OpLogicalOr;
3690 break;
3691 case glslang::EOpExclusiveOr:
3692 case glslang::EOpExclusiveOrAssign:
3693 binOp = spv::OpBitwiseXor;
3694 break;
3695 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003696 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003697 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003698 break;
3699
3700 case glslang::EOpLessThan:
3701 case glslang::EOpGreaterThan:
3702 case glslang::EOpLessThanEqual:
3703 case glslang::EOpGreaterThanEqual:
3704 case glslang::EOpEqual:
3705 case glslang::EOpNotEqual:
3706 case glslang::EOpVectorEqual:
3707 case glslang::EOpVectorNotEqual:
3708 comparison = true;
3709 break;
3710 default:
3711 break;
3712 }
3713
John Kessenich7c1aa102015-10-15 13:29:11 -06003714 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003715 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003716 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003717 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003718 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003719
3720 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003721 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003722 builder.promoteScalar(precision, left, right);
3723
qining25262b32016-05-06 17:25:16 -04003724 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3725 addDecoration(result, noContraction);
3726 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003727 }
3728
3729 if (! comparison)
3730 return 0;
3731
John Kessenich7c1aa102015-10-15 13:29:11 -06003732 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003733
John Kessenich4583b612016-08-07 19:14:22 -06003734 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3735 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003736 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003737
3738 switch (op) {
3739 case glslang::EOpLessThan:
3740 if (isFloat)
3741 binOp = spv::OpFOrdLessThan;
3742 else if (isUnsigned)
3743 binOp = spv::OpULessThan;
3744 else
3745 binOp = spv::OpSLessThan;
3746 break;
3747 case glslang::EOpGreaterThan:
3748 if (isFloat)
3749 binOp = spv::OpFOrdGreaterThan;
3750 else if (isUnsigned)
3751 binOp = spv::OpUGreaterThan;
3752 else
3753 binOp = spv::OpSGreaterThan;
3754 break;
3755 case glslang::EOpLessThanEqual:
3756 if (isFloat)
3757 binOp = spv::OpFOrdLessThanEqual;
3758 else if (isUnsigned)
3759 binOp = spv::OpULessThanEqual;
3760 else
3761 binOp = spv::OpSLessThanEqual;
3762 break;
3763 case glslang::EOpGreaterThanEqual:
3764 if (isFloat)
3765 binOp = spv::OpFOrdGreaterThanEqual;
3766 else if (isUnsigned)
3767 binOp = spv::OpUGreaterThanEqual;
3768 else
3769 binOp = spv::OpSGreaterThanEqual;
3770 break;
3771 case glslang::EOpEqual:
3772 case glslang::EOpVectorEqual:
3773 if (isFloat)
3774 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003775 else if (isBool)
3776 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003777 else
3778 binOp = spv::OpIEqual;
3779 break;
3780 case glslang::EOpNotEqual:
3781 case glslang::EOpVectorNotEqual:
3782 if (isFloat)
3783 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003784 else if (isBool)
3785 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003786 else
3787 binOp = spv::OpINotEqual;
3788 break;
3789 default:
3790 break;
3791 }
3792
qining25262b32016-05-06 17:25:16 -04003793 if (binOp != spv::OpNop) {
3794 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3795 addDecoration(result, noContraction);
3796 return builder.setPrecision(result, precision);
3797 }
John Kessenich140f3df2015-06-26 16:58:36 -06003798
3799 return 0;
3800}
3801
John Kessenich04bb8a02015-12-12 12:28:14 -07003802//
3803// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3804// These can be any of:
3805//
3806// matrix * scalar
3807// scalar * matrix
3808// matrix * matrix linear algebraic
3809// matrix * vector
3810// vector * matrix
3811// matrix * matrix componentwise
3812// matrix op matrix op in {+, -, /}
3813// matrix op scalar op in {+, -, /}
3814// scalar op matrix op in {+, -, /}
3815//
qining25262b32016-05-06 17:25:16 -04003816spv::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 -07003817{
3818 bool firstClass = true;
3819
3820 // First, handle first-class matrix operations (* and matrix/scalar)
3821 switch (op) {
3822 case spv::OpFDiv:
3823 if (builder.isMatrix(left) && builder.isScalar(right)) {
3824 // turn matrix / scalar into a multiply...
3825 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3826 op = spv::OpMatrixTimesScalar;
3827 } else
3828 firstClass = false;
3829 break;
3830 case spv::OpMatrixTimesScalar:
3831 if (builder.isMatrix(right))
3832 std::swap(left, right);
3833 assert(builder.isScalar(right));
3834 break;
3835 case spv::OpVectorTimesMatrix:
3836 assert(builder.isVector(left));
3837 assert(builder.isMatrix(right));
3838 break;
3839 case spv::OpMatrixTimesVector:
3840 assert(builder.isMatrix(left));
3841 assert(builder.isVector(right));
3842 break;
3843 case spv::OpMatrixTimesMatrix:
3844 assert(builder.isMatrix(left));
3845 assert(builder.isMatrix(right));
3846 break;
3847 default:
3848 firstClass = false;
3849 break;
3850 }
3851
qining25262b32016-05-06 17:25:16 -04003852 if (firstClass) {
3853 spv::Id result = builder.createBinOp(op, typeId, left, right);
3854 addDecoration(result, noContraction);
3855 return builder.setPrecision(result, precision);
3856 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003857
LoopDawg592860c2016-06-09 08:57:35 -06003858 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003859 // The result type of all of them is the same type as the (a) matrix operand.
3860 // The algorithm is to:
3861 // - break the matrix(es) into vectors
3862 // - smear any scalar to a vector
3863 // - do vector operations
3864 // - make a matrix out the vector results
3865 switch (op) {
3866 case spv::OpFAdd:
3867 case spv::OpFSub:
3868 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003869 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003870 case spv::OpFMul:
3871 {
3872 // one time set up...
3873 bool leftMat = builder.isMatrix(left);
3874 bool rightMat = builder.isMatrix(right);
3875 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3876 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3877 spv::Id scalarType = builder.getScalarTypeId(typeId);
3878 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3879 std::vector<spv::Id> results;
3880 spv::Id smearVec = spv::NoResult;
3881 if (builder.isScalar(left))
3882 smearVec = builder.smearScalar(precision, left, vecType);
3883 else if (builder.isScalar(right))
3884 smearVec = builder.smearScalar(precision, right, vecType);
3885
3886 // do each vector op
3887 for (unsigned int c = 0; c < numCols; ++c) {
3888 std::vector<unsigned int> indexes;
3889 indexes.push_back(c);
3890 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3891 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003892 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3893 addDecoration(result, noContraction);
3894 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003895 }
3896
3897 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003898 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003899 }
3900 default:
3901 assert(0);
3902 return spv::NoResult;
3903 }
3904}
3905
qining25262b32016-05-06 17:25:16 -04003906spv::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 -06003907{
3908 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003909 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003910 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003911#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003912 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003913 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3914#else
Rex Xucabbb782017-03-24 13:41:14 +08003915 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003916 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003917#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003918
3919 switch (op) {
3920 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003921 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003922 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003923 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003924 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003925 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003926 unaryOp = spv::OpSNegate;
3927 break;
3928
3929 case glslang::EOpLogicalNot:
3930 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003931 unaryOp = spv::OpLogicalNot;
3932 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003933 case glslang::EOpBitwiseNot:
3934 unaryOp = spv::OpNot;
3935 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003936
John Kessenich140f3df2015-06-26 16:58:36 -06003937 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003938 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003939 break;
3940 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003941 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003942 break;
3943 case glslang::EOpTranspose:
3944 unaryOp = spv::OpTranspose;
3945 break;
3946
3947 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003948 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003949 break;
3950 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003951 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003952 break;
3953 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003954 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003955 break;
3956 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003957 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003958 break;
3959 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003960 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003961 break;
3962 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003963 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003964 break;
3965 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003966 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003967 break;
3968 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003969 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003970 break;
3971
3972 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003973 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003974 break;
3975 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003976 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003977 break;
3978 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003979 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003980 break;
3981 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003982 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003983 break;
3984 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003985 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003986 break;
3987 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003988 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003989 break;
3990
3991 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003992 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003993 break;
3994 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003995 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003996 break;
3997
3998 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003999 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004000 break;
4001 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004002 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004003 break;
4004 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004005 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004006 break;
4007 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004008 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004009 break;
4010 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004011 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004012 break;
4013 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004015 break;
4016
4017 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004018 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004019 break;
4020 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004021 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004022 break;
4023 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004024 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004025 break;
4026 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004027 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004028 break;
4029 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004030 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004031 break;
4032 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004033 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004034 break;
4035
4036 case glslang::EOpIsNan:
4037 unaryOp = spv::OpIsNan;
4038 break;
4039 case glslang::EOpIsInf:
4040 unaryOp = spv::OpIsInf;
4041 break;
LoopDawg592860c2016-06-09 08:57:35 -06004042 case glslang::EOpIsFinite:
4043 unaryOp = spv::OpIsFinite;
4044 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004045
Rex Xucbc426e2015-12-15 16:03:10 +08004046 case glslang::EOpFloatBitsToInt:
4047 case glslang::EOpFloatBitsToUint:
4048 case glslang::EOpIntBitsToFloat:
4049 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004050 case glslang::EOpDoubleBitsToInt64:
4051 case glslang::EOpDoubleBitsToUint64:
4052 case glslang::EOpInt64BitsToDouble:
4053 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004054#ifdef AMD_EXTENSIONS
4055 case glslang::EOpFloat16BitsToInt16:
4056 case glslang::EOpFloat16BitsToUint16:
4057 case glslang::EOpInt16BitsToFloat16:
4058 case glslang::EOpUint16BitsToFloat16:
4059#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004060 unaryOp = spv::OpBitcast;
4061 break;
4062
John Kessenich140f3df2015-06-26 16:58:36 -06004063 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004064 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004065 break;
4066 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004067 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004068 break;
4069 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004070 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004071 break;
4072 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004073 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004074 break;
4075 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004076 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004077 break;
4078 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004079 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004080 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004081 case glslang::EOpPackSnorm4x8:
4082 libCall = spv::GLSLstd450PackSnorm4x8;
4083 break;
4084 case glslang::EOpUnpackSnorm4x8:
4085 libCall = spv::GLSLstd450UnpackSnorm4x8;
4086 break;
4087 case glslang::EOpPackUnorm4x8:
4088 libCall = spv::GLSLstd450PackUnorm4x8;
4089 break;
4090 case glslang::EOpUnpackUnorm4x8:
4091 libCall = spv::GLSLstd450UnpackUnorm4x8;
4092 break;
4093 case glslang::EOpPackDouble2x32:
4094 libCall = spv::GLSLstd450PackDouble2x32;
4095 break;
4096 case glslang::EOpUnpackDouble2x32:
4097 libCall = spv::GLSLstd450UnpackDouble2x32;
4098 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004099
Rex Xu8ff43de2016-04-22 16:51:45 +08004100 case glslang::EOpPackInt2x32:
4101 case glslang::EOpUnpackInt2x32:
4102 case glslang::EOpPackUint2x32:
4103 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004104 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004105 break;
4106
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004107#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004108 case glslang::EOpPackInt2x16:
4109 case glslang::EOpUnpackInt2x16:
4110 case glslang::EOpPackUint2x16:
4111 case glslang::EOpUnpackUint2x16:
4112 case glslang::EOpPackInt4x16:
4113 case glslang::EOpUnpackInt4x16:
4114 case glslang::EOpPackUint4x16:
4115 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004116 case glslang::EOpPackFloat2x16:
4117 case glslang::EOpUnpackFloat2x16:
4118 unaryOp = spv::OpBitcast;
4119 break;
4120#endif
4121
John Kessenich140f3df2015-06-26 16:58:36 -06004122 case glslang::EOpDPdx:
4123 unaryOp = spv::OpDPdx;
4124 break;
4125 case glslang::EOpDPdy:
4126 unaryOp = spv::OpDPdy;
4127 break;
4128 case glslang::EOpFwidth:
4129 unaryOp = spv::OpFwidth;
4130 break;
4131 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004132 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004133 unaryOp = spv::OpDPdxFine;
4134 break;
4135 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004136 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004137 unaryOp = spv::OpDPdyFine;
4138 break;
4139 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004140 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004141 unaryOp = spv::OpFwidthFine;
4142 break;
4143 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004144 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004145 unaryOp = spv::OpDPdxCoarse;
4146 break;
4147 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004148 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004149 unaryOp = spv::OpDPdyCoarse;
4150 break;
4151 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004152 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004153 unaryOp = spv::OpFwidthCoarse;
4154 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004155 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004156 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004157 libCall = spv::GLSLstd450InterpolateAtCentroid;
4158 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004159 case glslang::EOpAny:
4160 unaryOp = spv::OpAny;
4161 break;
4162 case glslang::EOpAll:
4163 unaryOp = spv::OpAll;
4164 break;
4165
4166 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004167 if (isFloat)
4168 libCall = spv::GLSLstd450FAbs;
4169 else
4170 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004171 break;
4172 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004173 if (isFloat)
4174 libCall = spv::GLSLstd450FSign;
4175 else
4176 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004177 break;
4178
John Kessenichfc51d282015-08-19 13:34:18 -06004179 case glslang::EOpAtomicCounterIncrement:
4180 case glslang::EOpAtomicCounterDecrement:
4181 case glslang::EOpAtomicCounter:
4182 {
4183 // Handle all of the atomics in one place, in createAtomicOperation()
4184 std::vector<spv::Id> operands;
4185 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004186 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004187 }
4188
John Kessenichfc51d282015-08-19 13:34:18 -06004189 case glslang::EOpBitFieldReverse:
4190 unaryOp = spv::OpBitReverse;
4191 break;
4192 case glslang::EOpBitCount:
4193 unaryOp = spv::OpBitCount;
4194 break;
4195 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004196 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004197 break;
4198 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004199 if (isUnsigned)
4200 libCall = spv::GLSLstd450FindUMsb;
4201 else
4202 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004203 break;
4204
Rex Xu574ab042016-04-14 16:53:07 +08004205 case glslang::EOpBallot:
4206 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004207 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004208 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004209 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004210#ifdef AMD_EXTENSIONS
4211 case glslang::EOpMinInvocations:
4212 case glslang::EOpMaxInvocations:
4213 case glslang::EOpAddInvocations:
4214 case glslang::EOpMinInvocationsNonUniform:
4215 case glslang::EOpMaxInvocationsNonUniform:
4216 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004217 case glslang::EOpMinInvocationsInclusiveScan:
4218 case glslang::EOpMaxInvocationsInclusiveScan:
4219 case glslang::EOpAddInvocationsInclusiveScan:
4220 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4221 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4222 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4223 case glslang::EOpMinInvocationsExclusiveScan:
4224 case glslang::EOpMaxInvocationsExclusiveScan:
4225 case glslang::EOpAddInvocationsExclusiveScan:
4226 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4227 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4228 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004229#endif
Rex Xu51596642016-09-21 18:56:12 +08004230 {
4231 std::vector<spv::Id> operands;
4232 operands.push_back(operand);
4233 return createInvocationsOperation(op, typeId, operands, typeProxy);
4234 }
Rex Xu9d93a232016-05-05 12:30:44 +08004235
4236#ifdef AMD_EXTENSIONS
4237 case glslang::EOpMbcnt:
4238 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4239 libCall = spv::MbcntAMD;
4240 break;
4241
4242 case glslang::EOpCubeFaceIndex:
4243 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4244 libCall = spv::CubeFaceIndexAMD;
4245 break;
4246
4247 case glslang::EOpCubeFaceCoord:
4248 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4249 libCall = spv::CubeFaceCoordAMD;
4250 break;
4251#endif
Rex Xu338b1852016-05-05 20:38:33 +08004252
John Kessenich140f3df2015-06-26 16:58:36 -06004253 default:
4254 return 0;
4255 }
4256
4257 spv::Id id;
4258 if (libCall >= 0) {
4259 std::vector<spv::Id> args;
4260 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004261 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004262 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004263 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004264 }
John Kessenich140f3df2015-06-26 16:58:36 -06004265
qining25262b32016-05-06 17:25:16 -04004266 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004267 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004268}
4269
John Kessenich7a53f762016-01-20 11:19:27 -07004270// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004271spv::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 -07004272{
4273 // Handle unary operations vector by vector.
4274 // The result type is the same type as the original type.
4275 // The algorithm is to:
4276 // - break the matrix into vectors
4277 // - apply the operation to each vector
4278 // - make a matrix out the vector results
4279
4280 // get the types sorted out
4281 int numCols = builder.getNumColumns(operand);
4282 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004283 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4284 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004285 std::vector<spv::Id> results;
4286
4287 // do each vector op
4288 for (int c = 0; c < numCols; ++c) {
4289 std::vector<unsigned int> indexes;
4290 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004291 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4292 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4293 addDecoration(destVec, noContraction);
4294 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004295 }
4296
4297 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004298 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004299}
4300
Rex Xu73e3ce72016-04-27 18:48:17 +08004301spv::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 -06004302{
4303 spv::Op convOp = spv::OpNop;
4304 spv::Id zero = 0;
4305 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004306 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004307
4308 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4309
4310 switch (op) {
4311 case glslang::EOpConvIntToBool:
4312 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004313 case glslang::EOpConvInt64ToBool:
4314 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004315#ifdef AMD_EXTENSIONS
4316 case glslang::EOpConvInt16ToBool:
4317 case glslang::EOpConvUint16ToBool:
4318#endif
4319 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4320 zero = builder.makeUint64Constant(0);
4321#ifdef AMD_EXTENSIONS
4322 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4323 zero = builder.makeUint16Constant(0);
4324#endif
4325 else
4326 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004327 zero = makeSmearedConstant(zero, vectorSize);
4328 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4329
4330 case glslang::EOpConvFloatToBool:
4331 zero = builder.makeFloatConstant(0.0F);
4332 zero = makeSmearedConstant(zero, vectorSize);
4333 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4334
4335 case glslang::EOpConvDoubleToBool:
4336 zero = builder.makeDoubleConstant(0.0);
4337 zero = makeSmearedConstant(zero, vectorSize);
4338 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4339
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004340#ifdef AMD_EXTENSIONS
4341 case glslang::EOpConvFloat16ToBool:
4342 zero = builder.makeFloat16Constant(0.0F);
4343 zero = makeSmearedConstant(zero, vectorSize);
4344 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4345#endif
4346
John Kessenich140f3df2015-06-26 16:58:36 -06004347 case glslang::EOpConvBoolToFloat:
4348 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004349 zero = builder.makeFloatConstant(0.0F);
4350 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004351 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004352
John Kessenich140f3df2015-06-26 16:58:36 -06004353 case glslang::EOpConvBoolToDouble:
4354 convOp = spv::OpSelect;
4355 zero = builder.makeDoubleConstant(0.0);
4356 one = builder.makeDoubleConstant(1.0);
4357 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004358
4359#ifdef AMD_EXTENSIONS
4360 case glslang::EOpConvBoolToFloat16:
4361 convOp = spv::OpSelect;
4362 zero = builder.makeFloat16Constant(0.0F);
4363 one = builder.makeFloat16Constant(1.0F);
4364 break;
4365#endif
4366
John Kessenich140f3df2015-06-26 16:58:36 -06004367 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004368 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004369#ifdef AMD_EXTENSIONS
4370 case glslang::EOpConvBoolToInt16:
4371#endif
4372 if (op == glslang::EOpConvBoolToInt64)
4373 zero = builder.makeInt64Constant(0);
4374#ifdef AMD_EXTENSIONS
4375 else if (op == glslang::EOpConvBoolToInt16)
4376 zero = builder.makeInt16Constant(0);
4377#endif
4378 else
4379 zero = builder.makeIntConstant(0);
4380
4381 if (op == glslang::EOpConvBoolToInt64)
4382 one = builder.makeInt64Constant(1);
4383#ifdef AMD_EXTENSIONS
4384 else if (op == glslang::EOpConvBoolToInt16)
4385 one = builder.makeInt16Constant(1);
4386#endif
4387 else
4388 one = builder.makeIntConstant(1);
4389
John Kessenich140f3df2015-06-26 16:58:36 -06004390 convOp = spv::OpSelect;
4391 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004392
John Kessenich140f3df2015-06-26 16:58:36 -06004393 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004394 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004395#ifdef AMD_EXTENSIONS
4396 case glslang::EOpConvBoolToUint16:
4397#endif
4398 if (op == glslang::EOpConvBoolToUint64)
4399 zero = builder.makeUint64Constant(0);
4400#ifdef AMD_EXTENSIONS
4401 else if (op == glslang::EOpConvBoolToUint16)
4402 zero = builder.makeUint16Constant(0);
4403#endif
4404 else
4405 zero = builder.makeUintConstant(0);
4406
4407 if (op == glslang::EOpConvBoolToUint64)
4408 one = builder.makeUint64Constant(1);
4409#ifdef AMD_EXTENSIONS
4410 else if (op == glslang::EOpConvBoolToUint16)
4411 one = builder.makeUint16Constant(1);
4412#endif
4413 else
4414 one = builder.makeUintConstant(1);
4415
John Kessenich140f3df2015-06-26 16:58:36 -06004416 convOp = spv::OpSelect;
4417 break;
4418
4419 case glslang::EOpConvIntToFloat:
4420 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004421 case glslang::EOpConvInt64ToFloat:
4422 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004423#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004424 case glslang::EOpConvInt16ToFloat:
4425 case glslang::EOpConvInt16ToDouble:
4426 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004427 case glslang::EOpConvIntToFloat16:
4428 case glslang::EOpConvInt64ToFloat16:
4429#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004430 convOp = spv::OpConvertSToF;
4431 break;
4432
4433 case glslang::EOpConvUintToFloat:
4434 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004435 case glslang::EOpConvUint64ToFloat:
4436 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004437#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004438 case glslang::EOpConvUint16ToFloat:
4439 case glslang::EOpConvUint16ToDouble:
4440 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004441 case glslang::EOpConvUintToFloat16:
4442 case glslang::EOpConvUint64ToFloat16:
4443#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004444 convOp = spv::OpConvertUToF;
4445 break;
4446
4447 case glslang::EOpConvDoubleToFloat:
4448 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004449#ifdef AMD_EXTENSIONS
4450 case glslang::EOpConvDoubleToFloat16:
4451 case glslang::EOpConvFloat16ToDouble:
4452 case glslang::EOpConvFloatToFloat16:
4453 case glslang::EOpConvFloat16ToFloat:
4454#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004455 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004456 if (builder.isMatrixType(destType))
4457 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004458 break;
4459
4460 case glslang::EOpConvFloatToInt:
4461 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004462 case glslang::EOpConvFloatToInt64:
4463 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004464#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004465 case glslang::EOpConvFloatToInt16:
4466 case glslang::EOpConvDoubleToInt16:
4467 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004468 case glslang::EOpConvFloat16ToInt:
4469 case glslang::EOpConvFloat16ToInt64:
4470#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004471 convOp = spv::OpConvertFToS;
4472 break;
4473
4474 case glslang::EOpConvUintToInt:
4475 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004476 case glslang::EOpConvUint64ToInt64:
4477 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004478#ifdef AMD_EXTENSIONS
4479 case glslang::EOpConvUint16ToInt16:
4480 case glslang::EOpConvInt16ToUint16:
4481#endif
qininge24aa5e2016-04-07 15:40:27 -04004482 if (builder.isInSpecConstCodeGenMode()) {
4483 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004484 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4485 zero = builder.makeUint64Constant(0);
4486#ifdef AMD_EXTENSIONS
4487 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4488 zero = builder.makeUint16Constant(0);
4489#endif
4490 else
4491 zero = builder.makeUintConstant(0);
4492
qining189b2032016-04-12 23:16:20 -04004493 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004494 // Use OpIAdd, instead of OpBitcast to do the conversion when
4495 // generating for OpSpecConstantOp instruction.
4496 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4497 }
4498 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004499 convOp = spv::OpBitcast;
4500 break;
4501
4502 case glslang::EOpConvFloatToUint:
4503 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004504 case glslang::EOpConvFloatToUint64:
4505 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004506#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004507 case glslang::EOpConvFloatToUint16:
4508 case glslang::EOpConvDoubleToUint16:
4509 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004510 case glslang::EOpConvFloat16ToUint:
4511 case glslang::EOpConvFloat16ToUint64:
4512#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004513 convOp = spv::OpConvertFToU;
4514 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004515
4516 case glslang::EOpConvIntToInt64:
4517 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004518#ifdef AMD_EXTENSIONS
4519 case glslang::EOpConvIntToInt16:
4520 case glslang::EOpConvInt16ToInt:
4521 case glslang::EOpConvInt64ToInt16:
4522 case glslang::EOpConvInt16ToInt64:
4523#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004524 convOp = spv::OpSConvert;
4525 break;
4526
4527 case glslang::EOpConvUintToUint64:
4528 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004529#ifdef AMD_EXTENSIONS
4530 case glslang::EOpConvUintToUint16:
4531 case glslang::EOpConvUint16ToUint:
4532 case glslang::EOpConvUint64ToUint16:
4533 case glslang::EOpConvUint16ToUint64:
4534#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004535 convOp = spv::OpUConvert;
4536 break;
4537
4538 case glslang::EOpConvIntToUint64:
4539 case glslang::EOpConvInt64ToUint:
4540 case glslang::EOpConvUint64ToInt:
4541 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004542#ifdef AMD_EXTENSIONS
4543 case glslang::EOpConvInt16ToUint:
4544 case glslang::EOpConvUintToInt16:
4545 case glslang::EOpConvInt16ToUint64:
4546 case glslang::EOpConvUint64ToInt16:
4547 case glslang::EOpConvUint16ToInt:
4548 case glslang::EOpConvIntToUint16:
4549 case glslang::EOpConvUint16ToInt64:
4550 case glslang::EOpConvInt64ToUint16:
4551#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004552 // OpSConvert/OpUConvert + OpBitCast
4553 switch (op) {
4554 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004555#ifdef AMD_EXTENSIONS
4556 case glslang::EOpConvInt16ToUint64:
4557#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004558 convOp = spv::OpSConvert;
4559 type = builder.makeIntType(64);
4560 break;
4561 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004562#ifdef AMD_EXTENSIONS
4563 case glslang::EOpConvInt16ToUint:
4564#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004565 convOp = spv::OpSConvert;
4566 type = builder.makeIntType(32);
4567 break;
4568 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004569#ifdef AMD_EXTENSIONS
4570 case glslang::EOpConvUint16ToInt:
4571#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004572 convOp = spv::OpUConvert;
4573 type = builder.makeUintType(32);
4574 break;
4575 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004576#ifdef AMD_EXTENSIONS
4577 case glslang::EOpConvUint16ToInt64:
4578#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004579 convOp = spv::OpUConvert;
4580 type = builder.makeUintType(64);
4581 break;
Rex Xucabbb782017-03-24 13:41:14 +08004582#ifdef AMD_EXTENSIONS
4583 case glslang::EOpConvUintToInt16:
4584 case glslang::EOpConvUint64ToInt16:
4585 convOp = spv::OpUConvert;
4586 type = builder.makeUintType(16);
4587 break;
4588 case glslang::EOpConvIntToUint16:
4589 case glslang::EOpConvInt64ToUint16:
4590 convOp = spv::OpSConvert;
4591 type = builder.makeIntType(16);
4592 break;
4593#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004594 default:
4595 assert(0);
4596 break;
4597 }
4598
4599 if (vectorSize > 0)
4600 type = builder.makeVectorType(type, vectorSize);
4601
4602 operand = builder.createUnaryOp(convOp, type, operand);
4603
4604 if (builder.isInSpecConstCodeGenMode()) {
4605 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004606#ifdef AMD_EXTENSIONS
4607 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4608 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4609 zero = builder.makeUint64Constant(0);
4610 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4611 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4612 zero = builder.makeUint16Constant(0);
4613 else
4614 zero = builder.makeUintConstant(0);
4615#else
4616 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4617 zero = builder.makeUint64Constant(0);
4618 else
4619 zero = builder.makeUintConstant(0);
4620#endif
4621
Rex Xu8ff43de2016-04-22 16:51:45 +08004622 zero = makeSmearedConstant(zero, vectorSize);
4623 // Use OpIAdd, instead of OpBitcast to do the conversion when
4624 // generating for OpSpecConstantOp instruction.
4625 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4626 }
4627 // For normal run-time conversion instruction, use OpBitcast.
4628 convOp = spv::OpBitcast;
4629 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004630 default:
4631 break;
4632 }
4633
4634 spv::Id result = 0;
4635 if (convOp == spv::OpNop)
4636 return result;
4637
4638 if (convOp == spv::OpSelect) {
4639 zero = makeSmearedConstant(zero, vectorSize);
4640 one = makeSmearedConstant(one, vectorSize);
4641 result = builder.createTriOp(convOp, destType, operand, one, zero);
4642 } else
4643 result = builder.createUnaryOp(convOp, destType, operand);
4644
John Kessenich32cfd492016-02-02 12:37:46 -07004645 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004646}
4647
4648spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4649{
4650 if (vectorSize == 0)
4651 return constant;
4652
4653 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4654 std::vector<spv::Id> components;
4655 for (int c = 0; c < vectorSize; ++c)
4656 components.push_back(constant);
4657 return builder.makeCompositeConstant(vectorTypeId, components);
4658}
4659
John Kessenich426394d2015-07-23 10:22:48 -06004660// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004661spv::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 -06004662{
4663 spv::Op opCode = spv::OpNop;
4664
4665 switch (op) {
4666 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004667 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004668 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004669 opCode = spv::OpAtomicIAdd;
4670 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004671 case glslang::EOpAtomicCounterSubtract:
4672 opCode = spv::OpAtomicISub;
4673 break;
John Kessenich426394d2015-07-23 10:22:48 -06004674 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004675 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004676 case glslang::EOpAtomicCounterMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004677 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004678 break;
4679 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004680 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004681 case glslang::EOpAtomicCounterMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004682 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004683 break;
4684 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004685 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004686 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004687 opCode = spv::OpAtomicAnd;
4688 break;
4689 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004690 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004691 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004692 opCode = spv::OpAtomicOr;
4693 break;
4694 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004695 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004696 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004697 opCode = spv::OpAtomicXor;
4698 break;
4699 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004700 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004701 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004702 opCode = spv::OpAtomicExchange;
4703 break;
4704 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004705 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004706 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004707 opCode = spv::OpAtomicCompareExchange;
4708 break;
4709 case glslang::EOpAtomicCounterIncrement:
4710 opCode = spv::OpAtomicIIncrement;
4711 break;
4712 case glslang::EOpAtomicCounterDecrement:
4713 opCode = spv::OpAtomicIDecrement;
4714 break;
4715 case glslang::EOpAtomicCounter:
4716 opCode = spv::OpAtomicLoad;
4717 break;
4718 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004719 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004720 break;
4721 }
4722
4723 // Sort out the operands
4724 // - mapping from glslang -> SPV
4725 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004726 // - compare-exchange swaps the value and comparator
4727 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004728 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4729 auto opIt = operands.begin(); // walk the glslang operands
4730 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004731 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4732 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4733 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004734 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4735 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004736 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004737 spvAtomicOperands.push_back(*(opIt + 1));
4738 spvAtomicOperands.push_back(*opIt);
4739 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004740 }
John Kessenich426394d2015-07-23 10:22:48 -06004741
John Kessenich3e60a6f2015-09-14 22:45:16 -06004742 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004743 for (; opIt != operands.end(); ++opIt)
4744 spvAtomicOperands.push_back(*opIt);
4745
4746 return builder.createOp(opCode, typeId, spvAtomicOperands);
4747}
4748
John Kessenich91cef522016-05-05 16:45:40 -06004749// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004750spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004751{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004752#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004753 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004754 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004755#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004756
Rex Xu51596642016-09-21 18:56:12 +08004757 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004758 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004759 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4760
chaocf200da82016-12-20 12:44:35 -08004761 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4762 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004763 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4764 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004765 } else if (op == glslang::EOpAnyInvocation ||
4766 op == glslang::EOpAllInvocations ||
4767 op == glslang::EOpAllInvocationsEqual) {
4768 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4769 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004770 } else {
4771 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004772#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004773 if (op == glslang::EOpMinInvocationsNonUniform ||
4774 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004775 op == glslang::EOpAddInvocationsNonUniform ||
4776 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4777 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4778 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4779 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4780 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4781 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004782 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004783#endif
Rex Xu51596642016-09-21 18:56:12 +08004784
4785 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004786#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004787 switch (op) {
4788 case glslang::EOpMinInvocations:
4789 case glslang::EOpMaxInvocations:
4790 case glslang::EOpAddInvocations:
4791 case glslang::EOpMinInvocationsNonUniform:
4792 case glslang::EOpMaxInvocationsNonUniform:
4793 case glslang::EOpAddInvocationsNonUniform:
4794 groupOperation = spv::GroupOperationReduce;
4795 spvGroupOperands.push_back(groupOperation);
4796 break;
4797 case glslang::EOpMinInvocationsInclusiveScan:
4798 case glslang::EOpMaxInvocationsInclusiveScan:
4799 case glslang::EOpAddInvocationsInclusiveScan:
4800 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4801 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4802 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4803 groupOperation = spv::GroupOperationInclusiveScan;
4804 spvGroupOperands.push_back(groupOperation);
4805 break;
4806 case glslang::EOpMinInvocationsExclusiveScan:
4807 case glslang::EOpMaxInvocationsExclusiveScan:
4808 case glslang::EOpAddInvocationsExclusiveScan:
4809 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4810 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4811 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4812 groupOperation = spv::GroupOperationExclusiveScan;
4813 spvGroupOperands.push_back(groupOperation);
4814 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004815 default:
4816 break;
Rex Xu430ef402016-10-14 17:22:23 +08004817 }
Rex Xu9d93a232016-05-05 12:30:44 +08004818#endif
Rex Xu51596642016-09-21 18:56:12 +08004819 }
4820
4821 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4822 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004823
4824 switch (op) {
4825 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004826 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004827 break;
John Kessenich91cef522016-05-05 16:45:40 -06004828 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004829 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004830 break;
John Kessenich91cef522016-05-05 16:45:40 -06004831 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004832 opCode = spv::OpSubgroupAllEqualKHR;
4833 break;
Rex Xu51596642016-09-21 18:56:12 +08004834 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004835 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004836 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004837 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004838 break;
4839 case glslang::EOpReadFirstInvocation:
4840 opCode = spv::OpSubgroupFirstInvocationKHR;
4841 break;
4842 case glslang::EOpBallot:
4843 {
4844 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4845 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4846 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4847 //
4848 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4849 //
4850 spv::Id uintType = builder.makeUintType(32);
4851 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4852 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4853
4854 std::vector<spv::Id> components;
4855 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4856 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4857
4858 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4859 return builder.createUnaryOp(spv::OpBitcast, typeId,
4860 builder.createCompositeConstruct(uvec2Type, components));
4861 }
4862
Rex Xu9d93a232016-05-05 12:30:44 +08004863#ifdef AMD_EXTENSIONS
4864 case glslang::EOpMinInvocations:
4865 case glslang::EOpMaxInvocations:
4866 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004867 case glslang::EOpMinInvocationsInclusiveScan:
4868 case glslang::EOpMaxInvocationsInclusiveScan:
4869 case glslang::EOpAddInvocationsInclusiveScan:
4870 case glslang::EOpMinInvocationsExclusiveScan:
4871 case glslang::EOpMaxInvocationsExclusiveScan:
4872 case glslang::EOpAddInvocationsExclusiveScan:
4873 if (op == glslang::EOpMinInvocations ||
4874 op == glslang::EOpMinInvocationsInclusiveScan ||
4875 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004876 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004877 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004878 else {
4879 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004880 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004881 else
Rex Xu51596642016-09-21 18:56:12 +08004882 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004883 }
Rex Xu430ef402016-10-14 17:22:23 +08004884 } else if (op == glslang::EOpMaxInvocations ||
4885 op == glslang::EOpMaxInvocationsInclusiveScan ||
4886 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004887 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004888 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004889 else {
4890 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004891 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004892 else
Rex Xu51596642016-09-21 18:56:12 +08004893 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004894 }
4895 } else {
4896 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004897 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004898 else
Rex Xu51596642016-09-21 18:56:12 +08004899 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004900 }
4901
Rex Xu2bbbe062016-08-23 15:41:05 +08004902 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004903 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004904
4905 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004906 case glslang::EOpMinInvocationsNonUniform:
4907 case glslang::EOpMaxInvocationsNonUniform:
4908 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004909 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4910 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4911 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4912 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4913 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4914 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4915 if (op == glslang::EOpMinInvocationsNonUniform ||
4916 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4917 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004918 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004919 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004920 else {
4921 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004922 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004923 else
Rex Xu51596642016-09-21 18:56:12 +08004924 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004925 }
4926 }
Rex Xu430ef402016-10-14 17:22:23 +08004927 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4928 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4929 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004930 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004931 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004932 else {
4933 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004934 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004935 else
Rex Xu51596642016-09-21 18:56:12 +08004936 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004937 }
4938 }
4939 else {
4940 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004941 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004942 else
Rex Xu51596642016-09-21 18:56:12 +08004943 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004944 }
4945
Rex Xu2bbbe062016-08-23 15:41:05 +08004946 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004947 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004948
4949 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004950#endif
John Kessenich91cef522016-05-05 16:45:40 -06004951 default:
4952 logger->missingFunctionality("invocation operation");
4953 return spv::NoResult;
4954 }
Rex Xu51596642016-09-21 18:56:12 +08004955
4956 assert(opCode != spv::OpNop);
4957 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004958}
4959
Rex Xu2bbbe062016-08-23 15:41:05 +08004960// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004961spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004962{
Rex Xub7072052016-09-26 15:53:40 +08004963#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004964 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4965 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004966 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004967 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004968 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4969 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4970 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004971#else
4972 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4973 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004974 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4975 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004976#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004977
4978 // Handle group invocation operations scalar by scalar.
4979 // The result type is the same type as the original type.
4980 // The algorithm is to:
4981 // - break the vector into scalars
4982 // - apply the operation to each scalar
4983 // - make a vector out the scalar results
4984
4985 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004986 int numComponents = builder.getNumComponents(operands[0]);
4987 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004988 std::vector<spv::Id> results;
4989
4990 // do each scalar op
4991 for (int comp = 0; comp < numComponents; ++comp) {
4992 std::vector<unsigned int> indexes;
4993 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004994 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004995 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004996 if (op == spv::OpSubgroupReadInvocationKHR) {
4997 spvGroupOperands.push_back(scalar);
4998 spvGroupOperands.push_back(operands[1]);
4999 } else if (op == spv::OpGroupBroadcast) {
5000 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005001 spvGroupOperands.push_back(scalar);
5002 spvGroupOperands.push_back(operands[1]);
5003 } else {
chaocf200da82016-12-20 12:44:35 -08005004 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005005 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005006 spvGroupOperands.push_back(scalar);
5007 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005008
Rex Xub7072052016-09-26 15:53:40 +08005009 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005010 }
5011
5012 // put the pieces together
5013 return builder.createCompositeConstruct(typeId, results);
5014}
Rex Xu2bbbe062016-08-23 15:41:05 +08005015
John Kessenich5e4b1242015-08-06 22:53:06 -06005016spv::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 -06005017{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005018#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005019 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005020 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5021#else
Rex Xucabbb782017-03-24 13:41:14 +08005022 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005023 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005024#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005025
John Kessenich140f3df2015-06-26 16:58:36 -06005026 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005027 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005028 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005029 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005030 spv::Id typeId0 = 0;
5031 if (consumedOperands > 0)
5032 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005033 spv::Id typeId1 = 0;
5034 if (consumedOperands > 1)
5035 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005036 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005037
5038 switch (op) {
5039 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005040 if (isFloat)
5041 libCall = spv::GLSLstd450FMin;
5042 else if (isUnsigned)
5043 libCall = spv::GLSLstd450UMin;
5044 else
5045 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005046 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005047 break;
5048 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005049 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005050 break;
5051 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005052 if (isFloat)
5053 libCall = spv::GLSLstd450FMax;
5054 else if (isUnsigned)
5055 libCall = spv::GLSLstd450UMax;
5056 else
5057 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005058 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005059 break;
5060 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005061 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005062 break;
5063 case glslang::EOpDot:
5064 opCode = spv::OpDot;
5065 break;
5066 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005067 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005068 break;
5069
5070 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005071 if (isFloat)
5072 libCall = spv::GLSLstd450FClamp;
5073 else if (isUnsigned)
5074 libCall = spv::GLSLstd450UClamp;
5075 else
5076 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005077 builder.promoteScalar(precision, operands.front(), operands[1]);
5078 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005079 break;
5080 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005081 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5082 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005083 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005084 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005085 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005086 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005087 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005088 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005089 break;
5090 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005091 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005092 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005093 break;
5094 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005095 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005096 builder.promoteScalar(precision, operands[0], operands[2]);
5097 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005098 break;
5099
5100 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005101 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005102 break;
5103 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005104 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005105 break;
5106 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005107 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005108 break;
5109 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005110 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005111 break;
5112 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005113 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005114 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005115 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005116 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005117 libCall = spv::GLSLstd450InterpolateAtSample;
5118 break;
5119 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005120 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005121 libCall = spv::GLSLstd450InterpolateAtOffset;
5122 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005123 case glslang::EOpAddCarry:
5124 opCode = spv::OpIAddCarry;
5125 typeId = builder.makeStructResultType(typeId0, typeId0);
5126 consumedOperands = 2;
5127 break;
5128 case glslang::EOpSubBorrow:
5129 opCode = spv::OpISubBorrow;
5130 typeId = builder.makeStructResultType(typeId0, typeId0);
5131 consumedOperands = 2;
5132 break;
5133 case glslang::EOpUMulExtended:
5134 opCode = spv::OpUMulExtended;
5135 typeId = builder.makeStructResultType(typeId0, typeId0);
5136 consumedOperands = 2;
5137 break;
5138 case glslang::EOpIMulExtended:
5139 opCode = spv::OpSMulExtended;
5140 typeId = builder.makeStructResultType(typeId0, typeId0);
5141 consumedOperands = 2;
5142 break;
5143 case glslang::EOpBitfieldExtract:
5144 if (isUnsigned)
5145 opCode = spv::OpBitFieldUExtract;
5146 else
5147 opCode = spv::OpBitFieldSExtract;
5148 break;
5149 case glslang::EOpBitfieldInsert:
5150 opCode = spv::OpBitFieldInsert;
5151 break;
5152
5153 case glslang::EOpFma:
5154 libCall = spv::GLSLstd450Fma;
5155 break;
5156 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005157 {
5158 libCall = spv::GLSLstd450FrexpStruct;
5159 assert(builder.isPointerType(typeId1));
5160 typeId1 = builder.getContainedTypeId(typeId1);
5161#ifdef AMD_EXTENSIONS
5162 int width = builder.getScalarTypeWidth(typeId1);
5163#else
5164 int width = 32;
5165#endif
5166 if (builder.getNumComponents(operands[0]) == 1)
5167 frexpIntType = builder.makeIntegerType(width, true);
5168 else
5169 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5170 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5171 consumedOperands = 1;
5172 }
John Kessenich55e7d112015-11-15 21:33:39 -07005173 break;
5174 case glslang::EOpLdexp:
5175 libCall = spv::GLSLstd450Ldexp;
5176 break;
5177
Rex Xu574ab042016-04-14 16:53:07 +08005178 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005179 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005180
Rex Xu9d93a232016-05-05 12:30:44 +08005181#ifdef AMD_EXTENSIONS
5182 case glslang::EOpSwizzleInvocations:
5183 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5184 libCall = spv::SwizzleInvocationsAMD;
5185 break;
5186 case glslang::EOpSwizzleInvocationsMasked:
5187 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5188 libCall = spv::SwizzleInvocationsMaskedAMD;
5189 break;
5190 case glslang::EOpWriteInvocation:
5191 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5192 libCall = spv::WriteInvocationAMD;
5193 break;
5194
5195 case glslang::EOpMin3:
5196 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5197 if (isFloat)
5198 libCall = spv::FMin3AMD;
5199 else {
5200 if (isUnsigned)
5201 libCall = spv::UMin3AMD;
5202 else
5203 libCall = spv::SMin3AMD;
5204 }
5205 break;
5206 case glslang::EOpMax3:
5207 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5208 if (isFloat)
5209 libCall = spv::FMax3AMD;
5210 else {
5211 if (isUnsigned)
5212 libCall = spv::UMax3AMD;
5213 else
5214 libCall = spv::SMax3AMD;
5215 }
5216 break;
5217 case glslang::EOpMid3:
5218 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5219 if (isFloat)
5220 libCall = spv::FMid3AMD;
5221 else {
5222 if (isUnsigned)
5223 libCall = spv::UMid3AMD;
5224 else
5225 libCall = spv::SMid3AMD;
5226 }
5227 break;
5228
5229 case glslang::EOpInterpolateAtVertex:
5230 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5231 libCall = spv::InterpolateAtVertexAMD;
5232 break;
5233#endif
5234
John Kessenich140f3df2015-06-26 16:58:36 -06005235 default:
5236 return 0;
5237 }
5238
5239 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005240 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005241 // Use an extended instruction from the standard library.
5242 // Construct the call arguments, without modifying the original operands vector.
5243 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5244 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005245 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005246 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005247 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005248 case 0:
5249 // should all be handled by visitAggregate and createNoArgOperation
5250 assert(0);
5251 return 0;
5252 case 1:
5253 // should all be handled by createUnaryOperation
5254 assert(0);
5255 return 0;
5256 case 2:
5257 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5258 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005259 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005260 // anything 3 or over doesn't have l-value operands, so all should be consumed
5261 assert(consumedOperands == operands.size());
5262 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005263 break;
5264 }
5265 }
5266
John Kessenich55e7d112015-11-15 21:33:39 -07005267 // Decode the return types that were structures
5268 switch (op) {
5269 case glslang::EOpAddCarry:
5270 case glslang::EOpSubBorrow:
5271 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5272 id = builder.createCompositeExtract(id, typeId0, 0);
5273 break;
5274 case glslang::EOpUMulExtended:
5275 case glslang::EOpIMulExtended:
5276 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5277 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5278 break;
5279 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005280 {
5281 assert(operands.size() == 2);
5282 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5283 // "exp" is floating-point type (from HLSL intrinsic)
5284 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5285 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5286 builder.createStore(member1, operands[1]);
5287 } else
5288 // "exp" is integer type (from GLSL built-in function)
5289 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5290 id = builder.createCompositeExtract(id, typeId0, 0);
5291 }
John Kessenich55e7d112015-11-15 21:33:39 -07005292 break;
5293 default:
5294 break;
5295 }
5296
John Kessenich32cfd492016-02-02 12:37:46 -07005297 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005298}
5299
Rex Xu9d93a232016-05-05 12:30:44 +08005300// Intrinsics with no arguments (or no return value, and no precision).
5301spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005302{
5303 // TODO: get the barrier operands correct
5304
5305 switch (op) {
5306 case glslang::EOpEmitVertex:
5307 builder.createNoResultOp(spv::OpEmitVertex);
5308 return 0;
5309 case glslang::EOpEndPrimitive:
5310 builder.createNoResultOp(spv::OpEndPrimitive);
5311 return 0;
5312 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005313 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005314 return 0;
5315 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005316 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005317 return 0;
5318 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005319 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005320 return 0;
5321 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005322 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005323 return 0;
5324 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005325 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005326 return 0;
5327 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005328 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005329 return 0;
5330 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005331 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005332 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005333 case glslang::EOpAllMemoryBarrierWithGroupSync:
5334 // Control barrier with non-"None" semantic is also a memory barrier.
5335 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5336 return 0;
5337 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5338 // Control barrier with non-"None" semantic is also a memory barrier.
5339 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5340 return 0;
5341 case glslang::EOpWorkgroupMemoryBarrier:
5342 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5343 return 0;
5344 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5345 // Control barrier with non-"None" semantic is also a memory barrier.
5346 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5347 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005348#ifdef AMD_EXTENSIONS
5349 case glslang::EOpTime:
5350 {
5351 std::vector<spv::Id> args; // Dummy arguments
5352 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5353 return builder.setPrecision(id, precision);
5354 }
5355#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005356 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005357 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005358 return 0;
5359 }
5360}
5361
5362spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5363{
John Kessenich2f273362015-07-18 22:34:27 -06005364 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005365 spv::Id id;
5366 if (symbolValues.end() != iter) {
5367 id = iter->second;
5368 return id;
5369 }
5370
5371 // it was not found, create it
5372 id = createSpvVariable(symbol);
5373 symbolValues[symbol->getId()] = id;
5374
Rex Xuc884b4a2016-06-29 15:03:44 +08005375 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005376 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005377 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005378 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005379 if (symbol->getType().getQualifier().hasSpecConstantId())
5380 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005381 if (symbol->getQualifier().hasIndex())
5382 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5383 if (symbol->getQualifier().hasComponent())
5384 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5385 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005386 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005387 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005388 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005389 if (symbol->getQualifier().hasXfbBuffer())
5390 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5391 if (symbol->getQualifier().hasXfbOffset())
5392 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5393 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005394 // atomic counters use this:
5395 if (symbol->getQualifier().hasOffset())
5396 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005397 }
5398
scygan2c864272016-05-18 18:09:17 +02005399 if (symbol->getQualifier().hasLocation())
5400 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005401 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005402 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005403 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005404 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005405 }
John Kessenich140f3df2015-06-26 16:58:36 -06005406 if (symbol->getQualifier().hasSet())
5407 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005408 else if (IsDescriptorResource(symbol->getType())) {
5409 // default to 0
5410 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5411 }
John Kessenich140f3df2015-06-26 16:58:36 -06005412 if (symbol->getQualifier().hasBinding())
5413 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005414 if (symbol->getQualifier().hasAttachment())
5415 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005416 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005417 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005418 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005419 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005420 if (symbol->getQualifier().hasXfbBuffer())
5421 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5422 }
5423
Rex Xu1da878f2016-02-21 20:59:01 +08005424 if (symbol->getType().isImage()) {
5425 std::vector<spv::Decoration> memory;
5426 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5427 for (unsigned int i = 0; i < memory.size(); ++i)
5428 addDecoration(id, memory[i]);
5429 }
5430
John Kessenich140f3df2015-06-26 16:58:36 -06005431 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005432 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005433 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005434 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005435
John Kessenichecba76f2017-01-06 00:34:48 -07005436#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005437 if (builtIn == spv::BuiltInSampleMask) {
5438 spv::Decoration decoration;
5439 // GL_NV_sample_mask_override_coverage extension
5440 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005441 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005442 else
5443 decoration = (spv::Decoration)spv::DecorationMax;
5444 addDecoration(id, decoration);
5445 if (decoration != spv::DecorationMax) {
5446 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5447 }
5448 }
chaoc771d89f2017-01-13 01:10:53 -08005449 else if (builtIn == spv::BuiltInLayer) {
5450 // SPV_NV_viewport_array2 extension
5451 if (symbol->getQualifier().layoutViewportRelative)
5452 {
5453 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5454 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5455 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5456 }
5457 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5458 {
5459 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5460 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5461 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5462 }
5463 }
5464
chaoc6e5acae2016-12-20 13:28:52 -08005465 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005466 addDecoration(id, spv::DecorationPassthroughNV);
5467 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005468 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5469 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005470#endif
5471
John Kessenich140f3df2015-06-26 16:58:36 -06005472 return id;
5473}
5474
John Kessenich55e7d112015-11-15 21:33:39 -07005475// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005476void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5477{
John Kessenich4016e382016-07-15 11:53:56 -06005478 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005479 builder.addDecoration(id, dec);
5480}
5481
John Kessenich55e7d112015-11-15 21:33:39 -07005482// If 'dec' is valid, add a one-operand decoration to an object
5483void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5484{
John Kessenich4016e382016-07-15 11:53:56 -06005485 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005486 builder.addDecoration(id, dec, value);
5487}
5488
5489// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005490void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5491{
John Kessenich4016e382016-07-15 11:53:56 -06005492 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005493 builder.addMemberDecoration(id, (unsigned)member, dec);
5494}
5495
John Kessenich92187592016-02-01 13:45:25 -07005496// If 'dec' is valid, add a one-operand decoration to a struct member
5497void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5498{
John Kessenich4016e382016-07-15 11:53:56 -06005499 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005500 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5501}
5502
John Kessenich55e7d112015-11-15 21:33:39 -07005503// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005504// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005505//
5506// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5507//
5508// Recursively walk the nodes. The nodes form a tree whose leaves are
5509// regular constants, which themselves are trees that createSpvConstant()
5510// recursively walks. So, this function walks the "top" of the tree:
5511// - emit specialization constant-building instructions for specConstant
5512// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005513spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005514{
John Kessenich7cc0e282016-03-20 00:46:02 -06005515 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005516
qining4f4bb812016-04-03 23:55:17 -04005517 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005518 if (! node.getQualifier().specConstant) {
5519 // hand off to the non-spec-constant path
5520 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5521 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005522 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005523 nextConst, false);
5524 }
5525
5526 // We now know we have a specialization constant to build
5527
John Kessenichd94c0032016-05-30 19:29:40 -06005528 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005529 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5530 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5531 std::vector<spv::Id> dimConstId;
5532 for (int dim = 0; dim < 3; ++dim) {
5533 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5534 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5535 if (specConst)
5536 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5537 }
5538 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5539 }
5540
5541 // An AST node labelled as specialization constant should be a symbol node.
5542 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5543 if (auto* sn = node.getAsSymbolNode()) {
5544 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005545 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5546 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5547 // will set the builder into spec constant op instruction generating mode.
5548 sub_tree->traverse(this);
5549 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005550 } else if (auto* const_union_array = &sn->getConstArray()){
5551 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005552 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5553 builder.addName(id, sn->getName().c_str());
5554 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005555 }
5556 }
qining4f4bb812016-04-03 23:55:17 -04005557
5558 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5559 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005560 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005561 exit(1);
5562 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005563}
5564
John Kessenich140f3df2015-06-26 16:58:36 -06005565// Use 'consts' as the flattened glslang source of scalar constants to recursively
5566// build the aggregate SPIR-V constant.
5567//
5568// If there are not enough elements present in 'consts', 0 will be substituted;
5569// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5570//
qining08408382016-03-21 09:51:37 -04005571spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005572{
5573 // vector of constants for SPIR-V
5574 std::vector<spv::Id> spvConsts;
5575
5576 // Type is used for struct and array constants
5577 spv::Id typeId = convertGlslangToSpvType(glslangType);
5578
5579 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005580 glslang::TType elementType(glslangType, 0);
5581 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005582 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005583 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005584 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005585 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005586 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005587 } else if (glslangType.getStruct()) {
5588 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5589 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005590 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005591 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005592 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5593 bool zero = nextConst >= consts.size();
5594 switch (glslangType.getBasicType()) {
5595 case glslang::EbtInt:
5596 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5597 break;
5598 case glslang::EbtUint:
5599 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5600 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005601 case glslang::EbtInt64:
5602 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5603 break;
5604 case glslang::EbtUint64:
5605 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5606 break;
Rex Xucabbb782017-03-24 13:41:14 +08005607#ifdef AMD_EXTENSIONS
5608 case glslang::EbtInt16:
5609 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5610 break;
5611 case glslang::EbtUint16:
5612 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5613 break;
5614#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005615 case glslang::EbtFloat:
5616 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5617 break;
5618 case glslang::EbtDouble:
5619 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5620 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005621#ifdef AMD_EXTENSIONS
5622 case glslang::EbtFloat16:
5623 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5624 break;
5625#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005626 case glslang::EbtBool:
5627 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5628 break;
5629 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005630 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005631 break;
5632 }
5633 ++nextConst;
5634 }
5635 } else {
5636 // we have a non-aggregate (scalar) constant
5637 bool zero = nextConst >= consts.size();
5638 spv::Id scalar = 0;
5639 switch (glslangType.getBasicType()) {
5640 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005641 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005642 break;
5643 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005644 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005645 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005646 case glslang::EbtInt64:
5647 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5648 break;
5649 case glslang::EbtUint64:
5650 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5651 break;
Rex Xucabbb782017-03-24 13:41:14 +08005652#ifdef AMD_EXTENSIONS
5653 case glslang::EbtInt16:
5654 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5655 break;
5656 case glslang::EbtUint16:
5657 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5658 break;
5659#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005660 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005661 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005662 break;
5663 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005664 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005665 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005666#ifdef AMD_EXTENSIONS
5667 case glslang::EbtFloat16:
5668 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5669 break;
5670#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005671 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005672 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005673 break;
5674 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005675 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005676 break;
5677 }
5678 ++nextConst;
5679 return scalar;
5680 }
5681
5682 return builder.makeCompositeConstant(typeId, spvConsts);
5683}
5684
John Kessenich7c1aa102015-10-15 13:29:11 -06005685// Return true if the node is a constant or symbol whose reading has no
5686// non-trivial observable cost or effect.
5687bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5688{
5689 // don't know what this is
5690 if (node == nullptr)
5691 return false;
5692
5693 // a constant is safe
5694 if (node->getAsConstantUnion() != nullptr)
5695 return true;
5696
5697 // not a symbol means non-trivial
5698 if (node->getAsSymbolNode() == nullptr)
5699 return false;
5700
5701 // a symbol, depends on what's being read
5702 switch (node->getType().getQualifier().storage) {
5703 case glslang::EvqTemporary:
5704 case glslang::EvqGlobal:
5705 case glslang::EvqIn:
5706 case glslang::EvqInOut:
5707 case glslang::EvqConst:
5708 case glslang::EvqConstReadOnly:
5709 case glslang::EvqUniform:
5710 return true;
5711 default:
5712 return false;
5713 }
qining25262b32016-05-06 17:25:16 -04005714}
John Kessenich7c1aa102015-10-15 13:29:11 -06005715
5716// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005717// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005718// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005719// Return true if trivial.
5720bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5721{
5722 if (node == nullptr)
5723 return false;
5724
John Kessenich84cc15f2017-05-24 16:44:47 -06005725 // count non scalars as trivial, as well as anything coming from HLSL
5726 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005727 return true;
5728
John Kessenich7c1aa102015-10-15 13:29:11 -06005729 // symbols and constants are trivial
5730 if (isTrivialLeaf(node))
5731 return true;
5732
5733 // otherwise, it needs to be a simple operation or one or two leaf nodes
5734
5735 // not a simple operation
5736 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5737 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5738 if (binaryNode == nullptr && unaryNode == nullptr)
5739 return false;
5740
5741 // not on leaf nodes
5742 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5743 return false;
5744
5745 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5746 return false;
5747 }
5748
5749 switch (node->getAsOperator()->getOp()) {
5750 case glslang::EOpLogicalNot:
5751 case glslang::EOpConvIntToBool:
5752 case glslang::EOpConvUintToBool:
5753 case glslang::EOpConvFloatToBool:
5754 case glslang::EOpConvDoubleToBool:
5755 case glslang::EOpEqual:
5756 case glslang::EOpNotEqual:
5757 case glslang::EOpLessThan:
5758 case glslang::EOpGreaterThan:
5759 case glslang::EOpLessThanEqual:
5760 case glslang::EOpGreaterThanEqual:
5761 case glslang::EOpIndexDirect:
5762 case glslang::EOpIndexDirectStruct:
5763 case glslang::EOpLogicalXor:
5764 case glslang::EOpAny:
5765 case glslang::EOpAll:
5766 return true;
5767 default:
5768 return false;
5769 }
5770}
5771
5772// Emit short-circuiting code, where 'right' is never evaluated unless
5773// the left side is true (for &&) or false (for ||).
5774spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5775{
5776 spv::Id boolTypeId = builder.makeBoolType();
5777
5778 // emit left operand
5779 builder.clearAccessChain();
5780 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005781 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005782
5783 // Operands to accumulate OpPhi operands
5784 std::vector<spv::Id> phiOperands;
5785 // accumulate left operand's phi information
5786 phiOperands.push_back(leftId);
5787 phiOperands.push_back(builder.getBuildPoint()->getId());
5788
5789 // Make the two kinds of operation symmetric with a "!"
5790 // || => emit "if (! left) result = right"
5791 // && => emit "if ( left) result = right"
5792 //
5793 // TODO: this runtime "not" for || could be avoided by adding functionality
5794 // to 'builder' to have an "else" without an "then"
5795 if (op == glslang::EOpLogicalOr)
5796 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5797
5798 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005799 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005800
5801 // emit right operand as the "then" part of the "if"
5802 builder.clearAccessChain();
5803 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005804 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005805
5806 // accumulate left operand's phi information
5807 phiOperands.push_back(rightId);
5808 phiOperands.push_back(builder.getBuildPoint()->getId());
5809
5810 // finish the "if"
5811 ifBuilder.makeEndIf();
5812
5813 // phi together the two results
5814 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5815}
5816
Rex Xu9d93a232016-05-05 12:30:44 +08005817// Return type Id of the imported set of extended instructions corresponds to the name.
5818// Import this set if it has not been imported yet.
5819spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5820{
5821 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5822 return extBuiltinMap[name];
5823 else {
Rex Xu51596642016-09-21 18:56:12 +08005824 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005825 spv::Id extBuiltins = builder.import(name);
5826 extBuiltinMap[name] = extBuiltins;
5827 return extBuiltins;
5828 }
5829}
5830
John Kessenich140f3df2015-06-26 16:58:36 -06005831}; // end anonymous namespace
5832
5833namespace glslang {
5834
John Kessenich68d78fd2015-07-12 19:28:10 -06005835void GetSpirvVersion(std::string& version)
5836{
John Kessenich9e55f632015-07-15 10:03:39 -06005837 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005838 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005839 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005840 version = buf;
5841}
5842
John Kessenich140f3df2015-06-26 16:58:36 -06005843// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005844void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005845{
5846 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005847 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005848 if (out.fail())
5849 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005850 for (int i = 0; i < (int)spirv.size(); ++i) {
5851 unsigned int word = spirv[i];
5852 out.write((const char*)&word, 4);
5853 }
5854 out.close();
5855}
5856
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005857// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005858void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005859{
5860 std::ofstream out;
5861 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005862 if (out.fail())
5863 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005864 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005865 if (varName != nullptr) {
5866 out << "\t #pragma once" << std::endl;
5867 out << "const uint32_t " << varName << "[] = {" << std::endl;
5868 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005869 const int WORDS_PER_LINE = 8;
5870 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5871 out << "\t";
5872 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5873 const unsigned int word = spirv[i + j];
5874 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5875 if (i + j + 1 < (int)spirv.size()) {
5876 out << ",";
5877 }
5878 }
5879 out << std::endl;
5880 }
Flavio15017db2017-02-15 14:29:33 -08005881 if (varName != nullptr) {
5882 out << "};";
5883 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005884 out.close();
5885}
5886
John Kessenich140f3df2015-06-26 16:58:36 -06005887//
5888// Set up the glslang traversal
5889//
John Kessenich121853f2017-05-31 17:11:16 -06005890void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005891{
Lei Zhang17535f72016-05-04 15:55:59 -04005892 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005893 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005894}
5895
John Kessenich121853f2017-05-31 17:11:16 -06005896void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5897 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005898{
John Kessenich140f3df2015-06-26 16:58:36 -06005899 TIntermNode* root = intermediate.getTreeRoot();
5900
5901 if (root == 0)
5902 return;
5903
John Kessenich121853f2017-05-31 17:11:16 -06005904 glslang::SpvOptions defaultOptions;
5905 if (options == nullptr)
5906 options = &defaultOptions;
5907
John Kessenich140f3df2015-06-26 16:58:36 -06005908 glslang::GetThreadPoolAllocator().push();
5909
John Kessenich121853f2017-05-31 17:11:16 -06005910 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005911 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005912 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005913 it.dumpSpv(spirv);
5914
5915 glslang::GetThreadPoolAllocator().pop();
5916}
5917
5918}; // end namespace glslang