blob: ddbfb8082cbdcbb36ea4c717e64fd87574fc1115 [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.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080050 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051}
John Kessenich140f3df2015-06-26 16:58:36 -060052
53// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020054#include "../glslang/MachineIndependent/localintermediate.h"
55#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060056#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050057#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060058
John Kessenich140f3df2015-06-26 16:58:36 -060059#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050060#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040061#include <list>
62#include <map>
63#include <stack>
64#include <string>
65#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060066
67namespace {
68
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
John Kessenichead86222018-03-28 18:01:20 -060088
89struct OpDecorations {
90 spv::Decoration precision;
91 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060092 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060093};
94
95} // namespace
qining4c912612016-04-01 10:35:16 -040096
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 Kessenich2b5ea9f2018-01-31 18:35:56 -0700104 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
105 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700106 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600107
108 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
109 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
110 void visitConstantUnion(glslang::TIntermConstantUnion*);
111 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
112 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
113 void visitSymbol(glslang::TIntermSymbol* symbol);
114 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
115 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
116 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
117
John Kessenichfca82622016-11-26 13:23:20 -0700118 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700119 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600120
121protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700122 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
123 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
124
Rex Xu17ff3432016-10-14 17:41:45 +0800125 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800126 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600127 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500128 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
129 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
130 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
131 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100132 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700133 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700134 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
135 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700136 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600137 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600138 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600139 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600140 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600141 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
142 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
143 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600144 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600145 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600147 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600148 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
149 glslang::TLayoutPacking, const glslang::TQualifier&);
150 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
151 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700152 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700153 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800154 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600155 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700156 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700157 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
158 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700159 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
160 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100161 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600162
John Kessenich6fccb3c2016-09-19 16:01:41 -0600163 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600164 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600165 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 void makeFunctions(const glslang::TIntermSequence&);
167 void makeGlobalInitializers(const glslang::TIntermSequence&);
168 void visitFunctions(const glslang::TIntermSequence&);
169 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500170 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600171 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
172 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
174
John Kessenichead86222018-03-28 18:01:20 -0600175 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
176 glslang::TBasicType typeProxy, bool reduceComparison = true);
177 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
178 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500179 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600180 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
181 glslang::TBasicType typeProxy);
182 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600184 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600185 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500186 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
Rex Xu51596642016-09-21 18:56:12 +0800187 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800188 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700189 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600190 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 +0800191 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600192 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700193 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400194 spv::Id createSpvConstant(const glslang::TIntermTyped&);
195 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600196 bool isTrivialLeaf(const glslang::TIntermTyped* node);
197 bool isTrivial(const glslang::TIntermTyped* node);
198 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800199 spv::Id getExtBuiltins(const char* name);
John Kessenich66011cb2018-03-06 16:12:04 -0700200 void addPre13Extension(const char* ext)
201 {
202 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
203 builder.addExtension(ext);
204 }
John Kessenich9c14f772019-06-17 08:38:35 -0600205 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
206 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500207 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600208
John Kessenich121853f2017-05-31 17:11:16 -0600209 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600210 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600211 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700212 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 int sequenceDepth;
214
Lei Zhang17535f72016-05-04 15:55:59 -0400215 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400216
John Kessenich140f3df2015-06-26 16:58:36 -0600217 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
218 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700219 bool inEntryPoint;
220 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700221 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 -0700222 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600223 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600224 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600225 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800226 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600227
John Kessenich2f273362015-07-18 22:34:27 -0600228 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600229 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700231 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700232 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
233 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700235 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600236 // Map pointee types for EbtReference to their forward pointers
237 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600238 // Type forcing, for when SPIR-V wants a different type than the AST,
239 // requiring local translation to and from SPIR-V type on every access.
240 // Maps <builtin-variable-id -> AST-required-type-id>
241 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600242};
243
244//
245// Helper functions for translating glslang representations to SPIR-V enumerants.
246//
247
248// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700249spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600250{
John Kessenich66e2faf2016-03-12 18:34:36 -0700251 switch (source) {
252 case glslang::EShSourceGlsl:
253 switch (profile) {
254 case ENoProfile:
255 case ECoreProfile:
256 case ECompatibilityProfile:
257 return spv::SourceLanguageGLSL;
258 case EEsProfile:
259 return spv::SourceLanguageESSL;
260 default:
261 return spv::SourceLanguageUnknown;
262 }
263 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600264 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 default:
266 return spv::SourceLanguageUnknown;
267 }
268}
269
270// Translate glslang language (stage) to SPIR-V execution model.
271spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
272{
273 switch (stage) {
274 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600275 case EShLangFragment: return spv::ExecutionModelFragment;
276#ifndef GLSLANG_WEB
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich140f3df2015-06-26 16:58:36 -0600278 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
279 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
280 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700281 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
282 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
283 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
284 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
285 case EShLangMissNV: return spv::ExecutionModelMissNV;
286 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700287 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
288 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
289#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::ExecutionModelFragment;
293 }
294}
295
John Kessenich140f3df2015-06-26 16:58:36 -0600296// Translate glslang sampler type to SPIR-V dimensionality.
297spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
298{
299 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700300 case glslang::Esd1D: return spv::Dim1D;
301 case glslang::Esd2D: return spv::Dim2D;
302 case glslang::Esd3D: return spv::Dim3D;
303 case glslang::EsdCube: return spv::DimCube;
304 case glslang::EsdRect: return spv::DimRect;
305 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700306 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600307 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700308 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600309 return spv::Dim2D;
310 }
311}
312
John Kessenichf6640762016-08-01 19:44:00 -0600313// Translate glslang precision to SPIR-V precision decorations.
314spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600315{
John Kessenichf6640762016-08-01 19:44:00 -0600316 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700317 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600318 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600319 default:
320 return spv::NoPrecision;
321 }
322}
323
John Kessenichf6640762016-08-01 19:44:00 -0600324// Translate glslang type to SPIR-V precision decorations.
325spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
326{
327 return TranslatePrecisionDecoration(type.getQualifier().precision);
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600331spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600332{
333 if (type.getBasicType() == glslang::EbtBlock) {
334 switch (type.getQualifier().storage) {
335 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600336 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600337 case glslang::EvqVaryingIn: return spv::DecorationBlock;
338 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600339#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700340 case glslang::EvqPayloadNV: return spv::DecorationBlock;
341 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
342 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700343 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
344 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700345#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 break;
349 }
350 }
351
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353}
354
Rex Xu1da878f2016-02-21 20:59:01 +0800355// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500356void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800357{
Jeff Bolz36831c92018-09-05 10:11:41 -0500358 if (!useVulkanMemoryModel) {
359 if (qualifier.coherent)
360 memory.push_back(spv::DecorationCoherent);
361 if (qualifier.volatil) {
362 memory.push_back(spv::DecorationVolatile);
363 memory.push_back(spv::DecorationCoherent);
364 }
John Kessenich14b85d32018-06-04 15:36:03 -0600365 }
Rex Xu1da878f2016-02-21 20:59:01 +0800366 if (qualifier.restrict)
367 memory.push_back(spv::DecorationRestrict);
368 if (qualifier.readonly)
369 memory.push_back(spv::DecorationNonWritable);
370 if (qualifier.writeonly)
371 memory.push_back(spv::DecorationNonReadable);
372}
373
John Kessenich140f3df2015-06-26 16:58:36 -0600374// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700375spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600376{
377 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700378 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600379 case glslang::ElmRowMajor:
380 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600382 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700383 default:
384 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600385 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600386 }
387 } else {
388 switch (type.getBasicType()) {
389 default:
John Kessenich4016e382016-07-15 11:53:56 -0600390 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600391 break;
392 case glslang::EbtBlock:
393 switch (type.getQualifier().storage) {
394 case glslang::EvqUniform:
395 case glslang::EvqBuffer:
396 switch (type.getQualifier().layoutPacking) {
397 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600398 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
399 default:
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600401 }
402 case glslang::EvqVaryingIn:
403 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700404 if (type.getQualifier().isTaskMemory()) {
405 switch (type.getQualifier().layoutPacking) {
406 case glslang::ElpShared: return spv::DecorationGLSLShared;
407 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
408 default: break;
409 }
410 } else {
411 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
412 }
John Kessenich4016e382016-07-15 11:53:56 -0600413 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600414#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700415 case glslang::EvqPayloadNV:
416 case glslang::EvqPayloadInNV:
417 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700418 case glslang::EvqCallableDataNV:
419 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700420 return spv::DecorationMax;
421#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600422 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700423 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600424 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600425 }
426 }
427 }
428}
429
430// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600431// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700432// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800433spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600434{
Rex Xubbceed72016-05-21 09:40:44 +0800435 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700436 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600437 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600438 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700439 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700440 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600441 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600442 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800443 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800444 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800445 }
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
John Kessenicha28f7a72019-08-06 07:00:58 -0600478 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenicha28f7a72019-08-06 07:00:58 -0600620 case glslang::EbvPosition: return spv::BuiltInPosition;
621 case glslang::EbvVertexId: return spv::BuiltInVertexId;
622 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
623 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
624 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
625
626 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
627 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
628 case glslang::EbvFace: return spv::BuiltInFrontFacing;
629 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
630
631#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600632 // These *Distance capabilities logically belong here, but if the member is declared and
633 // then never used, consumers of SPIR-V prefer the capability not be declared.
634 // They are now generated when used, rather than here when declared.
635 // Potentially, the specification should be more clear what the minimum
636 // use needed is to trigger the capability.
637 //
John Kessenich92187592016-02-01 13:45:25 -0700638 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100639 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800640 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700641 return spv::BuiltInClipDistance;
642
643 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100644 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800645 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700646 return spv::BuiltInCullDistance;
647
648 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600649 builder.addCapability(spv::CapabilityMultiViewport);
650 if (glslangIntermediate->getStage() == EShLangVertex ||
651 glslangIntermediate->getStage() == EShLangTessControl ||
652 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800653
John Kessenichba6a3c22017-09-13 13:22:50 -0600654 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
655 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800656 }
John Kessenich92187592016-02-01 13:45:25 -0700657 return spv::BuiltInViewportIndex;
658
John Kessenich5e801132016-02-15 11:09:46 -0700659 case glslang::EbvSampleId:
660 builder.addCapability(spv::CapabilitySampleRateShading);
661 return spv::BuiltInSampleId;
662
663 case glslang::EbvSamplePosition:
664 builder.addCapability(spv::CapabilitySampleRateShading);
665 return spv::BuiltInSamplePosition;
666
667 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700668 return spv::BuiltInSampleMask;
669
John Kessenich78a45572016-07-08 14:05:15 -0600670 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700671 if (glslangIntermediate->getStage() == EShLangMeshNV) {
672 return spv::BuiltInLayer;
673 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600674 builder.addCapability(spv::CapabilityGeometry);
675 if (glslangIntermediate->getStage() == EShLangVertex ||
676 glslangIntermediate->getStage() == EShLangTessControl ||
677 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800678
John Kessenichba6a3c22017-09-13 13:22:50 -0600679 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
680 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800681 }
John Kessenich78a45572016-07-08 14:05:15 -0600682 return spv::BuiltInLayer;
683
John Kessenichda581a22015-10-14 14:10:30 -0600684 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700685 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800686 builder.addCapability(spv::CapabilityDrawParameters);
687 return spv::BuiltInBaseVertex;
688
John Kessenichda581a22015-10-14 14:10:30 -0600689 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700690 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800691 builder.addCapability(spv::CapabilityDrawParameters);
692 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200693
John Kessenichda581a22015-10-14 14:10:30 -0600694 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700695 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800696 builder.addCapability(spv::CapabilityDrawParameters);
697 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200698
699 case glslang::EbvPrimitiveId:
700 if (glslangIntermediate->getStage() == EShLangFragment)
701 builder.addCapability(spv::CapabilityGeometry);
702 return spv::BuiltInPrimitiveId;
703
Rex Xu37cdcee2017-06-29 17:46:34 +0800704 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800705 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
706 builder.addCapability(spv::CapabilityStencilExportEXT);
707 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800708
John Kessenich140f3df2015-06-26 16:58:36 -0600709 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600710 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
711 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
712 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
713 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600735 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600740 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600745 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600750 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600755 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600797
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800825
John Kessenich6c8aaac2017-02-27 01:20:51 -0700826 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700827 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700828 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700829 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700830
831 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700832 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700833 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700834 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700835
Daniel Koch5154db52018-11-26 10:01:58 -0500836 case glslang::EbvFragSizeEXT:
837 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
838 builder.addCapability(spv::CapabilityFragmentDensityEXT);
839 return spv::BuiltInFragSizeEXT;
840
841 case glslang::EbvFragInvocationCountEXT:
842 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
843 builder.addCapability(spv::CapabilityFragmentDensityEXT);
844 return spv::BuiltInFragInvocationCountEXT;
845
chaoc771d89f2017-01-13 01:10:53 -0800846 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800847 if (!memberDeclaration) {
848 builder.addExtension(spv::E_SPV_NV_viewport_array2);
849 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
850 }
chaoc771d89f2017-01-13 01:10:53 -0800851 return spv::BuiltInViewportMaskNV;
852 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800853 if (!memberDeclaration) {
854 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
855 builder.addCapability(spv::CapabilityShaderStereoViewNV);
856 }
chaoc771d89f2017-01-13 01:10:53 -0800857 return spv::BuiltInSecondaryPositionNV;
858 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800859 if (!memberDeclaration) {
860 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
861 builder.addCapability(spv::CapabilityShaderStereoViewNV);
862 }
chaoc771d89f2017-01-13 01:10:53 -0800863 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800864 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800865 if (!memberDeclaration) {
866 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
867 builder.addCapability(spv::CapabilityPerViewAttributesNV);
868 }
chaocdf3956c2017-02-14 14:52:34 -0800869 return spv::BuiltInPositionPerViewNV;
870 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800871 if (!memberDeclaration) {
872 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
873 builder.addCapability(spv::CapabilityPerViewAttributesNV);
874 }
chaocdf3956c2017-02-14 14:52:34 -0800875 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700876 case glslang::EbvFragFullyCoveredNV:
877 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
878 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
879 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700880 case glslang::EbvFragmentSizeNV:
881 builder.addExtension(spv::E_SPV_NV_shading_rate);
882 builder.addCapability(spv::CapabilityShadingRateNV);
883 return spv::BuiltInFragmentSizeNV;
884 case glslang::EbvInvocationsPerPixelNV:
885 builder.addExtension(spv::E_SPV_NV_shading_rate);
886 builder.addCapability(spv::CapabilityShadingRateNV);
887 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700888
Daniel Koch593a4e02019-05-27 16:46:31 -0400889 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700890 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700891 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700892 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInWorldToObjectNV;
916 case glslang::EbvIncomingRayFlagsNV:
917 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400918
919 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700920 case glslang::EbvBaryCoordNV:
921 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
922 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
923 return spv::BuiltInBaryCoordNV;
924 case glslang::EbvBaryCoordNoPerspNV:
925 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
926 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
927 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400928
929 // mesh shaders
930 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700931 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400932 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700933 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400934 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700935 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400936 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700937 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400938 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700939 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400940 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700941 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700943 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700945 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -0400946
947 // sm builtins
948 case glslang::EbvWarpsPerSM:
949 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
950 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
951 return spv::BuiltInWarpsPerSMNV;
952 case glslang::EbvSMCount:
953 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
954 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
955 return spv::BuiltInSMCountNV;
956 case glslang::EbvWarpID:
957 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
958 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
959 return spv::BuiltInWarpIDNV;
960 case glslang::EbvSMID:
961 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
962 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
963 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -0600964#endif
965
Rex Xu3e783f92017-02-22 16:44:48 +0800966 default:
967 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600968 }
969}
970
Rex Xufc618912015-09-09 16:42:49 +0800971// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700972spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800973{
974 assert(type.getBasicType() == glslang::EbtSampler);
975
John Kessenich5d0fa972016-02-15 11:57:00 -0700976 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -0600977 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -0700978 case glslang::ElfRg32f:
979 case glslang::ElfRg16f:
980 case glslang::ElfR11fG11fB10f:
981 case glslang::ElfR16f:
982 case glslang::ElfRgba16:
983 case glslang::ElfRgb10A2:
984 case glslang::ElfRg16:
985 case glslang::ElfRg8:
986 case glslang::ElfR16:
987 case glslang::ElfR8:
988 case glslang::ElfRgba16Snorm:
989 case glslang::ElfRg16Snorm:
990 case glslang::ElfRg8Snorm:
991 case glslang::ElfR16Snorm:
992 case glslang::ElfR8Snorm:
993
994 case glslang::ElfRg32i:
995 case glslang::ElfRg16i:
996 case glslang::ElfRg8i:
997 case glslang::ElfR16i:
998 case glslang::ElfR8i:
999
1000 case glslang::ElfRgb10a2ui:
1001 case glslang::ElfRg32ui:
1002 case glslang::ElfRg16ui:
1003 case glslang::ElfRg8ui:
1004 case glslang::ElfR16ui:
1005 case glslang::ElfR8ui:
1006 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1007 break;
1008
1009 default:
1010 break;
1011 }
1012
1013 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001014 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001015 case glslang::ElfNone: return spv::ImageFormatUnknown;
1016 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1017 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1018 case glslang::ElfR32f: return spv::ImageFormatR32f;
1019 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1020 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1021 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1022 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1023 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1024 case glslang::ElfR16f: return spv::ImageFormatR16f;
1025 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1026 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1027 case glslang::ElfRg16: return spv::ImageFormatRg16;
1028 case glslang::ElfRg8: return spv::ImageFormatRg8;
1029 case glslang::ElfR16: return spv::ImageFormatR16;
1030 case glslang::ElfR8: return spv::ImageFormatR8;
1031 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1032 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1033 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1034 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1035 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1036 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1037 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1038 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1039 case glslang::ElfR32i: return spv::ImageFormatR32i;
1040 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1041 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1042 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1043 case glslang::ElfR16i: return spv::ImageFormatR16i;
1044 case glslang::ElfR8i: return spv::ImageFormatR8i;
1045 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1046 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1047 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1048 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1049 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1050 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1051 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1052 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1053 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1054 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001055 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001056 }
1057}
1058
John Kesseniche18fd202018-01-30 11:01:39 -07001059spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001060{
John Kesseniche18fd202018-01-30 11:01:39 -07001061 if (selectionNode.getFlatten())
1062 return spv::SelectionControlFlattenMask;
1063 if (selectionNode.getDontFlatten())
1064 return spv::SelectionControlDontFlattenMask;
1065 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001066}
1067
John Kesseniche18fd202018-01-30 11:01:39 -07001068spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001069{
John Kesseniche18fd202018-01-30 11:01:39 -07001070 if (switchNode.getFlatten())
1071 return spv::SelectionControlFlattenMask;
1072 if (switchNode.getDontFlatten())
1073 return spv::SelectionControlDontFlattenMask;
1074 return spv::SelectionControlMaskNone;
1075}
1076
John Kessenicha2858d92018-01-31 08:11:18 -07001077// return a non-0 dependency if the dependency argument must be set
1078spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001079 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001080{
1081 spv::LoopControlMask control = spv::LoopControlMaskNone;
1082
1083 if (loopNode.getDontUnroll())
1084 control = control | spv::LoopControlDontUnrollMask;
1085 if (loopNode.getUnroll())
1086 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001087 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001088 control = control | spv::LoopControlDependencyInfiniteMask;
1089 else if (loopNode.getLoopDependency() > 0) {
1090 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001091 operands.push_back((unsigned int)loopNode.getLoopDependency());
1092 }
1093 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1094 if (loopNode.getMinIterations() > 0) {
1095 control = control | spv::LoopControlMinIterationsMask;
1096 operands.push_back(loopNode.getMinIterations());
1097 }
1098 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1099 control = control | spv::LoopControlMaxIterationsMask;
1100 operands.push_back(loopNode.getMaxIterations());
1101 }
1102 if (loopNode.getIterationMultiple() > 1) {
1103 control = control | spv::LoopControlIterationMultipleMask;
1104 operands.push_back(loopNode.getIterationMultiple());
1105 }
1106 if (loopNode.getPeelCount() > 0) {
1107 control = control | spv::LoopControlPeelCountMask;
1108 operands.push_back(loopNode.getPeelCount());
1109 }
1110 if (loopNode.getPartialCount() > 0) {
1111 control = control | spv::LoopControlPartialCountMask;
1112 operands.push_back(loopNode.getPartialCount());
1113 }
John Kessenicha2858d92018-01-31 08:11:18 -07001114 }
John Kesseniche18fd202018-01-30 11:01:39 -07001115
1116 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001117}
1118
John Kessenicha5c5fb62017-05-05 05:09:58 -06001119// Translate glslang type to SPIR-V storage class.
1120spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1121{
1122 if (type.getQualifier().isPipeInput())
1123 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001124 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001125 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001126
1127 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001128 type.getQualifier().storage == glslang::EvqUniform) {
1129#ifndef GLSLANG_WEB
John Kessenichbed4e4f2017-09-08 02:38:07 -06001130 if (type.getBasicType() == glslang::EbtAtomicUint)
1131 return spv::StorageClassAtomicCounter;
John Kessenicha28f7a72019-08-06 07:00:58 -06001132#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001133 if (type.containsOpaque())
1134 return spv::StorageClassUniformConstant;
1135 }
1136
John Kessenicha28f7a72019-08-06 07:00:58 -06001137#ifndef GLSLANG_WEB
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001138 if (type.getQualifier().isUniformOrBuffer() &&
1139 type.getQualifier().layoutShaderRecordNV) {
1140 return spv::StorageClassShaderRecordBufferNV;
1141 }
1142#endif
1143
John Kessenichbed4e4f2017-09-08 02:38:07 -06001144 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001145 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001146 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001147 }
1148
1149 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha28f7a72019-08-06 07:00:58 -06001150#ifndef GLSLANG_WEB
John Kessenich7015bd62019-08-01 03:28:08 -06001151 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001152 return spv::StorageClassPushConstant;
John Kessenicha28f7a72019-08-06 07:00:58 -06001153#endif
John Kessenicha5c5fb62017-05-05 05:09:58 -06001154 if (type.getBasicType() == glslang::EbtBlock)
1155 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001156 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001157 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001158
1159 switch (type.getQualifier().storage) {
John Kessenichbed4e4f2017-09-08 02:38:07 -06001160 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1161 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1162 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenicha28f7a72019-08-06 07:00:58 -06001163#ifndef GLSLANG_WEB
1164 case glslang::EvqShared: return spv::StorageClassWorkgroup;
Ashwin Leleff1783d2018-10-22 16:41:44 -07001165 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1166 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1167 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1168 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1169 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001170#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001171 default:
1172 assert(0);
1173 break;
1174 }
1175
1176 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001177}
1178
John Kessenich5611c6d2018-04-05 11:25:02 -06001179// Add capabilities pertaining to how an array is indexed.
1180void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1181 const glslang::TType& indexType)
1182{
1183 if (indexType.getQualifier().isNonUniform()) {
1184 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001185 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001186 if (baseType.getBasicType() == glslang::EbtSampler) {
1187 if (baseType.getQualifier().hasAttachment())
1188 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1189 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1190 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1191 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1192 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1193 else if (baseType.isImage())
1194 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1195 else if (baseType.isTexture())
1196 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1197 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1198 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1199 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1200 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1201 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1202 }
1203 } else {
1204 // assume a dynamically uniform index
1205 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001206 if (baseType.getQualifier().hasAttachment()) {
1207 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001208 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001209 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1210 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001211 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001212 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1213 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001214 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001215 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001216 }
1217 }
1218}
1219
qining25262b32016-05-06 17:25:16 -04001220// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001221// descriptor set.
1222bool IsDescriptorResource(const glslang::TType& type)
1223{
John Kessenichf7497e22016-03-08 21:36:22 -07001224 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001225 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001226 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001227 ! type.getQualifier().isShaderRecordNV() &&
1228 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001229
1230 // non block...
1231 // basically samplerXXX/subpass/sampler/texture are all included
1232 // if they are the global-scope-class, not the function parameter
1233 // (or local, if they ever exist) class.
1234 if (type.getBasicType() == glslang::EbtSampler)
1235 return type.getQualifier().isUniformOrBuffer();
1236
1237 // None of the above.
1238 return false;
1239}
1240
John Kesseniche0b6cad2015-12-24 10:30:13 -07001241void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1242{
1243 if (child.layoutMatrix == glslang::ElmNone)
1244 child.layoutMatrix = parent.layoutMatrix;
1245
1246 if (parent.invariant)
1247 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001248 if (parent.flat)
1249 child.flat = true;
1250 if (parent.centroid)
1251 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001252#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001253 if (parent.nopersp)
1254 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001255 if (parent.explicitInterp)
1256 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001257 if (parent.perPrimitiveNV)
1258 child.perPrimitiveNV = true;
1259 if (parent.perViewNV)
1260 child.perViewNV = true;
1261 if (parent.perTaskNV)
1262 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001263 if (parent.patch)
1264 child.patch = true;
1265 if (parent.sample)
1266 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001267 if (parent.coherent)
1268 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001269 if (parent.devicecoherent)
1270 child.devicecoherent = true;
1271 if (parent.queuefamilycoherent)
1272 child.queuefamilycoherent = true;
1273 if (parent.workgroupcoherent)
1274 child.workgroupcoherent = true;
1275 if (parent.subgroupcoherent)
1276 child.subgroupcoherent = true;
1277 if (parent.nonprivate)
1278 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001279 if (parent.volatil)
1280 child.volatil = true;
1281 if (parent.restrict)
1282 child.restrict = true;
1283 if (parent.readonly)
1284 child.readonly = true;
1285 if (parent.writeonly)
1286 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001287#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001288}
1289
John Kessenichf2b7f332016-09-01 17:05:23 -06001290bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001291{
John Kessenich7b9fa252016-01-21 18:56:57 -07001292 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001293 // - struct members might inherit from a struct declaration
1294 // (note that non-block structs don't explicitly inherit,
1295 // only implicitly, meaning no decoration involved)
1296 // - affect decorations on the struct members
1297 // (note smooth does not, and expecting something like volatile
1298 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001299 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001300 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001301}
1302
John Kessenich140f3df2015-06-26 16:58:36 -06001303//
1304// Implement the TGlslangToSpvTraverser class.
1305//
1306
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001307TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001308 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1309 : TIntermTraverser(true, false, true),
1310 options(options),
1311 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001312 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001313 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001314 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001315 glslangIntermediate(glslangIntermediate),
1316 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001317{
1318 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1319
1320 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001321 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1322 glslangIntermediate->getVersion());
1323
John Kessenich121853f2017-05-31 17:11:16 -06001324 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001325 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001326 builder.setSourceFile(glslangIntermediate->getSourceFile());
1327
1328 // Set the source shader's text. If for SPV version 1.0, include
1329 // a preamble in comments stating the OpModuleProcessed instructions.
1330 // Otherwise, emit those as actual instructions.
1331 std::string text;
1332 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1333 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001334 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001335 text.append("// OpModuleProcessed ");
1336 text.append(processes[p]);
1337 text.append("\n");
1338 } else
1339 builder.addModuleProcessed(processes[p]);
1340 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001341 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001342 text.append("#line 1\n");
1343 text.append(glslangIntermediate->getSourceText());
1344 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001345 // Pass name and text for all included files
1346 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1347 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1348 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001349 }
John Kessenich140f3df2015-06-26 16:58:36 -06001350 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001351
1352 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1353 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1354
1355 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1356 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1357 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1358 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1359 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001360 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001361 memoryModel = spv::MemoryModelVulkanKHR;
1362 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001363 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001364 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001365 builder.setMemoryModel(addressingModel, memoryModel);
1366
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001367 if (glslangIntermediate->usingVariablePointers()) {
1368 builder.addCapability(spv::CapabilityVariablePointers);
1369 }
1370
John Kessenicheee9d532016-09-19 18:09:30 -06001371 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1372 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001373
1374 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001375 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1376 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001377 builder.addSourceExtension(it->c_str());
1378
1379 // Add the top-level modes for this shader.
1380
John Kessenich92187592016-02-01 13:45:25 -07001381 if (glslangIntermediate->getXfbMode()) {
1382 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001383 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001384 }
John Kessenich140f3df2015-06-26 16:58:36 -06001385
1386 unsigned int mode;
1387 switch (glslangIntermediate->getStage()) {
1388 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001389 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001390 break;
1391
John Kessenicha28f7a72019-08-06 07:00:58 -06001392 case EShLangFragment:
1393 builder.addCapability(spv::CapabilityShader);
1394 if (glslangIntermediate->getPixelCenterInteger())
1395 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1396
1397 if (glslangIntermediate->getOriginUpperLeft())
1398 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1399 else
1400 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1401
1402 if (glslangIntermediate->getEarlyFragmentTests())
1403 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1404
1405 if (glslangIntermediate->getPostDepthCoverage()) {
1406 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1407 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1408 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1409 }
1410
1411 switch(glslangIntermediate->getDepth()) {
1412 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1413 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1414 default: mode = spv::ExecutionModeMax; break;
1415 }
1416 if (mode != spv::ExecutionModeMax)
1417 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1418
1419 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1420 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1421
1422 switch (glslangIntermediate->getInterlockOrdering()) {
1423 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1424 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1425 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1426 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1427 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1428 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1429 default: mode = spv::ExecutionModeMax; break;
1430 }
1431 if (mode != spv::ExecutionModeMax) {
1432 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1433 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1434 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1435 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1436 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1437 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1438 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1439 } else {
1440 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1441 }
1442 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1443 }
1444
1445 break;
1446
1447#ifndef GLSLANG_WEB
1448 case EShLangCompute:
1449 builder.addCapability(spv::CapabilityShader);
1450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1451 glslangIntermediate->getLocalSize(1),
1452 glslangIntermediate->getLocalSize(2));
1453 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1454 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1455 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1456 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1457 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1458 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1459 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1460 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1461 }
1462 break;
steve-lunarge7412492017-03-23 11:56:07 -06001463 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001464 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001465 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001466
steve-lunarge7412492017-03-23 11:56:07 -06001467 glslang::TLayoutGeometry primitive;
1468
1469 if (glslangIntermediate->getStage() == EShLangTessControl) {
1470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1471 primitive = glslangIntermediate->getOutputPrimitive();
1472 } else {
1473 primitive = glslangIntermediate->getInputPrimitive();
1474 }
1475
1476 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001477 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1478 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1479 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001480 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001481 }
John Kessenich4016e382016-07-15 11:53:56 -06001482 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001483 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1484
John Kesseniche6903322015-10-13 16:29:02 -06001485 switch (glslangIntermediate->getVertexSpacing()) {
1486 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1487 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1488 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001489 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001490 }
John Kessenich4016e382016-07-15 11:53:56 -06001491 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001492 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1493
1494 switch (glslangIntermediate->getVertexOrder()) {
1495 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1496 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001497 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001498 }
John Kessenich4016e382016-07-15 11:53:56 -06001499 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001500 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1501
1502 if (glslangIntermediate->getPointMode())
1503 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001504 break;
1505
1506 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001507 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001508 switch (glslangIntermediate->getInputPrimitive()) {
1509 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1510 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1511 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001512 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001513 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001514 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001515 }
John Kessenich4016e382016-07-15 11:53:56 -06001516 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001517 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001518
John Kessenich140f3df2015-06-26 16:58:36 -06001519 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1520
1521 switch (glslangIntermediate->getOutputPrimitive()) {
1522 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1523 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1524 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001525 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001526 }
John Kessenich4016e382016-07-15 11:53:56 -06001527 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001528 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1529 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1530 break;
1531
Chao Chenb50c02e2018-09-19 11:42:24 -07001532 case EShLangRayGenNV:
1533 case EShLangIntersectNV:
1534 case EShLangAnyHitNV:
1535 case EShLangClosestHitNV:
1536 case EShLangMissNV:
1537 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001538 builder.addCapability(spv::CapabilityRayTracingNV);
1539 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001540 break;
Chao Chen3c366992018-09-19 11:41:59 -07001541 case EShLangTaskNV:
1542 case EShLangMeshNV:
1543 builder.addCapability(spv::CapabilityMeshShadingNV);
1544 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1545 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1546 glslangIntermediate->getLocalSize(1),
1547 glslangIntermediate->getLocalSize(2));
1548 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1549 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1550 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1551
1552 switch (glslangIntermediate->getOutputPrimitive()) {
1553 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1554 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1555 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1556 default: mode = spv::ExecutionModeMax; break;
1557 }
1558 if (mode != spv::ExecutionModeMax)
1559 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1560 }
1561 break;
1562#endif
1563
John Kessenich140f3df2015-06-26 16:58:36 -06001564 default:
1565 break;
1566 }
John Kessenich140f3df2015-06-26 16:58:36 -06001567}
1568
John Kessenichfca82622016-11-26 13:23:20 -07001569// Finish creating SPV, after the traversal is complete.
1570void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001571{
John Kessenichf04c51b2018-08-03 15:56:12 -06001572 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001573 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001574 builder.setBuildPoint(shaderEntry->getLastBlock());
1575 builder.leaveFunction();
1576 }
1577
John Kessenich7ba63412015-12-20 17:37:07 -07001578 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001579 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1580 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001581
John Kessenich23d27752019-07-28 02:12:10 -06001582#ifndef GLSLANG_WEB
John Kessenichf04c51b2018-08-03 15:56:12 -06001583 // Add capabilities, extensions, remove unneeded decorations, etc.,
1584 // based on the resulting SPIR-V.
1585 builder.postProcess();
John Kessenich23d27752019-07-28 02:12:10 -06001586#endif
John Kessenich7ba63412015-12-20 17:37:07 -07001587}
1588
John Kessenichfca82622016-11-26 13:23:20 -07001589// Write the SPV into 'out'.
1590void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001591{
John Kessenichfca82622016-11-26 13:23:20 -07001592 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001593}
1594
1595//
1596// Implement the traversal functions.
1597//
1598// Return true from interior nodes to have the external traversal
1599// continue on to children. Return false if children were
1600// already processed.
1601//
1602
1603//
qining25262b32016-05-06 17:25:16 -04001604// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001605// - uniform/input reads
1606// - output writes
1607// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1608// - something simple that degenerates into the last bullet
1609//
1610void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1611{
qining75d1d802016-04-06 14:42:01 -04001612 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1613 if (symbol->getType().getQualifier().isSpecConstant())
1614 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1615
John Kessenich140f3df2015-06-26 16:58:36 -06001616 // getSymbolId() will set up all the IO decorations on the first call.
1617 // Formal function parameters were mapped during makeFunctions().
1618 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001619
John Kessenich7ba63412015-12-20 17:37:07 -07001620 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001621 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001622 // Consider adding to the OpEntryPoint interface list.
1623 // Only looking at structures if they have at least one member.
1624 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1625 spv::StorageClass sc = builder.getStorageClass(id);
1626 // Before SPIR-V 1.4, we only want to include Input and Output.
1627 // Starting with SPIR-V 1.4, we want all globals.
1628 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1629 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001630 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001631 }
John Kessenich5f77d862017-09-19 11:09:59 -06001632 }
John Kessenich9c14f772019-06-17 08:38:35 -06001633
1634 // If the SPIR-V type is required to be different than the AST type,
1635 // translate now from the SPIR-V type to the AST type, for the consuming
1636 // operation.
1637 // Note this turns it from an l-value to an r-value.
1638 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1639 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1640 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001641 }
1642
1643 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001644 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001645 // Prepare to generate code for the access
1646
1647 // L-value chains will be computed left to right. We're on the symbol now,
1648 // which is the left-most part of the access chain, so now is "clear" time,
1649 // followed by setting the base.
1650 builder.clearAccessChain();
1651
1652 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001653 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001654 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001655 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001656 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001657 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001658 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001659 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001660 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1661 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001662 builder.setAccessChainRValue(id);
1663 else
1664 builder.setAccessChainLValue(id);
1665 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001666
1667 // Process linkage-only nodes for any special additional interface work.
1668 if (linkageOnly) {
1669 if (glslangIntermediate->getHlslFunctionality1()) {
1670 // Map implicit counter buffers to their originating buffers, which should have been
1671 // seen by now, given earlier pruning of unused counters, and preservation of order
1672 // of declaration.
1673 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1674 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1675 // Save possible originating buffers for counter buffers, keyed by
1676 // making the potential counter-buffer name.
1677 std::string keyName = symbol->getName().c_str();
1678 keyName = glslangIntermediate->addCounterBufferName(keyName);
1679 counterOriginator[keyName] = symbol;
1680 } else {
1681 // Handle a counter buffer, by finding the saved originating buffer.
1682 std::string keyName = symbol->getName().c_str();
1683 auto it = counterOriginator.find(keyName);
1684 if (it != counterOriginator.end()) {
1685 id = getSymbolId(it->second);
1686 if (id != spv::NoResult) {
1687 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001688 if (counterId != spv::NoResult) {
1689 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001690 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001691 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001692 }
1693 }
1694 }
1695 }
1696 }
1697 }
John Kessenich140f3df2015-06-26 16:58:36 -06001698}
1699
1700bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1701{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001702 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001703
qining40887662016-04-03 22:20:42 -04001704 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1705 if (node->getType().getQualifier().isSpecConstant())
1706 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1707
John Kessenich140f3df2015-06-26 16:58:36 -06001708 // First, handle special cases
1709 switch (node->getOp()) {
1710 case glslang::EOpAssign:
1711 case glslang::EOpAddAssign:
1712 case glslang::EOpSubAssign:
1713 case glslang::EOpMulAssign:
1714 case glslang::EOpVectorTimesMatrixAssign:
1715 case glslang::EOpVectorTimesScalarAssign:
1716 case glslang::EOpMatrixTimesScalarAssign:
1717 case glslang::EOpMatrixTimesMatrixAssign:
1718 case glslang::EOpDivAssign:
1719 case glslang::EOpModAssign:
1720 case glslang::EOpAndAssign:
1721 case glslang::EOpInclusiveOrAssign:
1722 case glslang::EOpExclusiveOrAssign:
1723 case glslang::EOpLeftShiftAssign:
1724 case glslang::EOpRightShiftAssign:
1725 // A bin-op assign "a += b" means the same thing as "a = a + b"
1726 // where a is evaluated before b. For a simple assignment, GLSL
1727 // says to evaluate the left before the right. So, always, left
1728 // node then right node.
1729 {
1730 // get the left l-value, save it away
1731 builder.clearAccessChain();
1732 node->getLeft()->traverse(this);
1733 spv::Builder::AccessChain lValue = builder.getAccessChain();
1734
1735 // evaluate the right
1736 builder.clearAccessChain();
1737 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001738 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001739
1740 if (node->getOp() != glslang::EOpAssign) {
1741 // the left is also an r-value
1742 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001743 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001744
1745 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001746 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001747 TranslateNoContractionDecoration(node->getType().getQualifier()),
1748 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001749 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001750 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1751 node->getType().getBasicType());
1752
1753 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001754 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001755 }
1756
1757 // store the result
1758 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001759 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001760
1761 // assignments are expressions having an rValue after they are evaluated...
1762 builder.clearAccessChain();
1763 builder.setAccessChainRValue(rValue);
1764 }
1765 return false;
1766 case glslang::EOpIndexDirect:
1767 case glslang::EOpIndexDirectStruct:
1768 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001769 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001770 // Get the left part of the access chain.
1771 node->getLeft()->traverse(this);
1772
1773 // Add the next element in the chain
1774
David Netoa901ffe2016-06-08 14:11:40 +01001775 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001776 if (! node->getLeft()->getType().isArray() &&
1777 node->getLeft()->getType().isVector() &&
1778 node->getOp() == glslang::EOpIndexDirect) {
1779 // This is essentially a hard-coded vector swizzle of size 1,
1780 // so short circuit the access-chain stuff with a swizzle.
1781 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001782 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001783 int dummySize;
1784 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1785 TranslateCoherent(node->getLeft()->getType()),
1786 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001787 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001788
1789 // Load through a block reference is performed with a dot operator that
1790 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1791 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001792 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001793 !node->getLeft()->getType().isArray() &&
1794 node->getOp() == glslang::EOpIndexDirectStruct)
1795 {
1796 spv::Id left = accessChainLoad(node->getLeft()->getType());
1797 builder.clearAccessChain();
1798 builder.setAccessChainLValue(left);
1799 }
1800
David Netoa901ffe2016-06-08 14:11:40 +01001801 int spvIndex = glslangIndex;
1802 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1803 node->getOp() == glslang::EOpIndexDirectStruct)
1804 {
1805 // This may be, e.g., an anonymous block-member selection, which generally need
1806 // index remapping due to hidden members in anonymous blocks.
1807 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1808 assert(remapper.size() > 0);
1809 spvIndex = remapper[glslangIndex];
1810 }
John Kessenichebb50532016-05-16 19:22:05 -06001811
David Netoa901ffe2016-06-08 14:11:40 +01001812 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001813 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001814
1815 // Add capabilities here for accessing PointSize and clip/cull distance.
1816 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001817 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001818 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001819 }
1820 }
1821 return false;
1822 case glslang::EOpIndexIndirect:
1823 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001824 // Array, matrix, or vector indirection with variable index.
1825 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001826 // matrices are arrays of vectors, so will also work for a matrix.
1827 // Will use the access chain's 'component' for variable index into a vector.
1828
1829 // This adapter is building access chains left to right.
1830 // Set up the access chain to the left.
1831 node->getLeft()->traverse(this);
1832
1833 // save it so that computing the right side doesn't trash it
1834 spv::Builder::AccessChain partial = builder.getAccessChain();
1835
1836 // compute the next index in the chain
1837 builder.clearAccessChain();
1838 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001839 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001840
John Kessenich5611c6d2018-04-05 11:25:02 -06001841 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1842
John Kessenich140f3df2015-06-26 16:58:36 -06001843 // restore the saved access chain
1844 builder.setAccessChain(partial);
1845
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001846 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1847 int dummySize;
1848 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1849 TranslateCoherent(node->getLeft()->getType()),
1850 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1851 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001852 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001853 }
1854 return false;
1855 case glslang::EOpVectorSwizzle:
1856 {
1857 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001858 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001859 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001860 int dummySize;
1861 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1862 TranslateCoherent(node->getLeft()->getType()),
1863 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001864 }
1865 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001866 case glslang::EOpMatrixSwizzle:
1867 logger->missingFunctionality("matrix swizzle");
1868 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001869 case glslang::EOpLogicalOr:
1870 case glslang::EOpLogicalAnd:
1871 {
1872
1873 // These may require short circuiting, but can sometimes be done as straight
1874 // binary operations. The right operand must be short circuited if it has
1875 // side effects, and should probably be if it is complex.
1876 if (isTrivial(node->getRight()->getAsTyped()))
1877 break; // handle below as a normal binary operation
1878 // otherwise, we need to do dynamic short circuiting on the right operand
1879 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1880 builder.clearAccessChain();
1881 builder.setAccessChainRValue(result);
1882 }
1883 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001884 default:
1885 break;
1886 }
1887
1888 // Assume generic binary op...
1889
John Kessenich32cfd492016-02-02 12:37:46 -07001890 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001891 builder.clearAccessChain();
1892 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001893 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001894
John Kessenich32cfd492016-02-02 12:37:46 -07001895 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001896 builder.clearAccessChain();
1897 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001898 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001899
John Kessenich32cfd492016-02-02 12:37:46 -07001900 // get result
John Kessenichead86222018-03-28 18:01:20 -06001901 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001902 TranslateNoContractionDecoration(node->getType().getQualifier()),
1903 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001904 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001905 convertGlslangToSpvType(node->getType()), left, right,
1906 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001907
John Kessenich50e57562015-12-21 21:21:11 -07001908 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001909 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001910 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001911 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001912 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001913 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001914 return false;
1915 }
John Kessenich140f3df2015-06-26 16:58:36 -06001916}
1917
John Kessenich9c14f772019-06-17 08:38:35 -06001918// Figure out what, if any, type changes are needed when accessing a specific built-in.
1919// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1920// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1921std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1922 const glslang::TType& glslangType)
1923{
1924 switch(builtIn)
1925 {
1926 case spv::BuiltInSubgroupEqMask:
1927 case spv::BuiltInSubgroupGeMask:
1928 case spv::BuiltInSubgroupGtMask:
1929 case spv::BuiltInSubgroupLeMask:
1930 case spv::BuiltInSubgroupLtMask: {
1931 // these require changing a 64-bit scaler -> a vector of 32-bit components
1932 if (glslangType.isVector())
1933 break;
1934 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1935 builder.makeUintType(64));
1936 return ret;
1937 }
1938 default:
1939 break;
1940 }
1941
1942 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1943 return ret;
1944}
1945
1946// For an object previously identified (see getForcedType() and forceType)
1947// as needing type translations, do the translation needed for a load, turning
1948// an L-value into in R-value.
1949spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
1950{
1951 const auto forceIt = forceType.find(object);
1952 if (forceIt == forceType.end())
1953 return object;
1954
1955 spv::Id desiredTypeId = forceIt->second;
1956 spv::Id objectTypeId = builder.getTypeId(object);
1957 assert(builder.isPointerType(objectTypeId));
1958 objectTypeId = builder.getContainedTypeId(objectTypeId);
1959 if (builder.isVectorType(objectTypeId) &&
1960 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
1961 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
1962 // handle 32-bit v.xy* -> 64-bit
1963 builder.clearAccessChain();
1964 builder.setAccessChainLValue(object);
1965 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
1966 std::vector<spv::Id> components;
1967 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
1968 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
1969
1970 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
1971 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
1972 builder.createCompositeConstruct(vecType, components));
1973 } else {
1974 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
1975 }
1976 } else {
1977 logger->missingFunctionality("forcing non 32-bit vector type");
1978 }
1979
1980 return object;
1981}
1982
John Kessenich140f3df2015-06-26 16:58:36 -06001983bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1984{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001985 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001986
qining40887662016-04-03 22:20:42 -04001987 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1988 if (node->getType().getQualifier().isSpecConstant())
1989 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1990
John Kessenichfc51d282015-08-19 13:34:18 -06001991 spv::Id result = spv::NoResult;
1992
1993 // try texturing first
1994 result = createImageTextureFunctionCall(node);
1995 if (result != spv::NoResult) {
1996 builder.clearAccessChain();
1997 builder.setAccessChainRValue(result);
1998
1999 return false; // done with this node
2000 }
2001
2002 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002003
2004 if (node->getOp() == glslang::EOpArrayLength) {
2005 // Quite special; won't want to evaluate the operand.
2006
John Kessenich5611c6d2018-04-05 11:25:02 -06002007 // Currently, the front-end does not allow .length() on an array until it is sized,
2008 // except for the last block membeor of an SSBO.
2009 // TODO: If this changes, link-time sized arrays might show up here, and need their
2010 // size extracted.
2011
John Kessenichc9a80832015-09-12 12:17:44 -06002012 // Normal .length() would have been constant folded by the front-end.
2013 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002014 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002015
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002016 spv::Id length;
2017 if (node->getOperand()->getType().isCoopMat()) {
2018 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2019
2020 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2021 assert(builder.isCooperativeMatrixType(typeId));
2022
2023 length = builder.createCooperativeMatrixLength(typeId);
2024 } else {
2025 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2026 block->traverse(this);
2027 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2028 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2029 }
John Kessenichc9a80832015-09-12 12:17:44 -06002030
John Kessenich8c869672018-11-28 07:01:37 -07002031 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2032 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2033 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002034 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2035 if (builder.isInSpecConstCodeGenMode()) {
2036 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2037 } else {
2038 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2039 }
2040 }
John Kessenich8c869672018-11-28 07:01:37 -07002041
John Kessenichc9a80832015-09-12 12:17:44 -06002042 builder.clearAccessChain();
2043 builder.setAccessChainRValue(length);
2044
2045 return false;
2046 }
2047
John Kessenichfc51d282015-08-19 13:34:18 -06002048 // Start by evaluating the operand
2049
John Kessenich8c8505c2016-07-26 12:50:38 -06002050 // Does it need a swizzle inversion? If so, evaluation is inverted;
2051 // operate first on the swizzle base, then apply the swizzle.
2052 spv::Id invertedType = spv::NoType;
2053 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2054 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2055 invertedType = getInvertedSwizzleType(*node->getOperand());
2056
John Kessenich140f3df2015-06-26 16:58:36 -06002057 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002058 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002059 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002060 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002061 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002062 operandNode = node->getOperand();
2063
2064 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002065
Rex Xufc618912015-09-09 16:42:49 +08002066 spv::Id operand = spv::NoResult;
2067
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002068 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2069
Rex Xufc618912015-09-09 16:42:49 +08002070 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2071 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002072 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002073 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002074 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002075 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2076 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2077 } else
John Kessenich32cfd492016-02-02 12:37:46 -07002078 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002079
John Kessenichead86222018-03-28 18:01:20 -06002080 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002081 TranslateNoContractionDecoration(node->getType().getQualifier()),
2082 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002083
2084 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002085 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002086 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002087
2088 // if not, then possibly an operation
2089 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002090 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002091
2092 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002093 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002094 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002095 builder.addDecoration(result, decorations.nonUniform);
2096 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002097
John Kessenich140f3df2015-06-26 16:58:36 -06002098 builder.clearAccessChain();
2099 builder.setAccessChainRValue(result);
2100
2101 return false; // done with this node
2102 }
2103
2104 // it must be a special case, check...
2105 switch (node->getOp()) {
2106 case glslang::EOpPostIncrement:
2107 case glslang::EOpPostDecrement:
2108 case glslang::EOpPreIncrement:
2109 case glslang::EOpPreDecrement:
2110 {
2111 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002112 spv::Id one = 0;
2113 if (node->getBasicType() == glslang::EbtFloat)
2114 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08002115 else if (node->getBasicType() == glslang::EbtDouble)
2116 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002117 else if (node->getBasicType() == glslang::EbtFloat16)
2118 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002119 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2120 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002121 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2122 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002123 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2124 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002125 else
2126 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002127 glslang::TOperator op;
2128 if (node->getOp() == glslang::EOpPreIncrement ||
2129 node->getOp() == glslang::EOpPostIncrement)
2130 op = glslang::EOpAdd;
2131 else
2132 op = glslang::EOpSub;
2133
John Kessenichead86222018-03-28 18:01:20 -06002134 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002135 convertGlslangToSpvType(node->getType()), operand, one,
2136 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002137 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002138
2139 // The result of operation is always stored, but conditionally the
2140 // consumed result. The consumed result is always an r-value.
2141 builder.accessChainStore(result);
2142 builder.clearAccessChain();
2143 if (node->getOp() == glslang::EOpPreIncrement ||
2144 node->getOp() == glslang::EOpPreDecrement)
2145 builder.setAccessChainRValue(result);
2146 else
2147 builder.setAccessChainRValue(operand);
2148 }
2149
2150 return false;
2151
2152 case glslang::EOpEmitStreamVertex:
2153 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2154 return false;
2155 case glslang::EOpEndStreamPrimitive:
2156 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2157 return false;
2158
2159 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002160 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002161 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002162 }
John Kessenich140f3df2015-06-26 16:58:36 -06002163}
2164
Jeff Bolz53134492019-06-25 13:31:10 -05002165// Construct a composite object, recursively copying members if their types don't match
2166spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2167{
2168 for (int c = 0; c < (int)constituents.size(); ++c) {
2169 spv::Id& constituent = constituents[c];
2170 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2171 spv::Id rType = builder.getTypeId(constituent);
2172 if (lType != rType) {
2173 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2174 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2175 } else if (builder.isStructType(rType)) {
2176 std::vector<spv::Id> rTypeConstituents;
2177 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2178 for (int i = 0; i < numrTypeConstituents; ++i) {
2179 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2180 }
2181 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2182 } else {
2183 assert(builder.isArrayType(rType));
2184 std::vector<spv::Id> rTypeConstituents;
2185 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2186
2187 spv::Id elementRType = builder.getContainedTypeId(rType);
2188 for (int i = 0; i < numrTypeConstituents; ++i) {
2189 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2190 }
2191 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2192 }
2193 }
2194 }
2195 return builder.createCompositeConstruct(resultTypeId, constituents);
2196}
2197
John Kessenich140f3df2015-06-26 16:58:36 -06002198bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2199{
qining27e04a02016-04-14 16:40:20 -04002200 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2201 if (node->getType().getQualifier().isSpecConstant())
2202 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2203
John Kessenichfc51d282015-08-19 13:34:18 -06002204 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002205 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2206 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002207
2208 // try texturing
2209 result = createImageTextureFunctionCall(node);
2210 if (result != spv::NoResult) {
2211 builder.clearAccessChain();
2212 builder.setAccessChainRValue(result);
2213
2214 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002215 }
2216#ifndef GLSLANG_WEB
2217 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002218 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002219 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002220 // "imageStore" is a special case, which has no result
2221 return false;
2222 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002223#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002224
John Kessenich140f3df2015-06-26 16:58:36 -06002225 glslang::TOperator binOp = glslang::EOpNull;
2226 bool reduceComparison = true;
2227 bool isMatrix = false;
2228 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002229 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002230
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002231 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2232
John Kessenich140f3df2015-06-26 16:58:36 -06002233 assert(node->getOp());
2234
John Kessenichf6640762016-08-01 19:44:00 -06002235 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002236
2237 switch (node->getOp()) {
2238 case glslang::EOpSequence:
2239 {
2240 if (preVisit)
2241 ++sequenceDepth;
2242 else
2243 --sequenceDepth;
2244
2245 if (sequenceDepth == 1) {
2246 // If this is the parent node of all the functions, we want to see them
2247 // early, so all call points have actual SPIR-V functions to reference.
2248 // In all cases, still let the traverser visit the children for us.
2249 makeFunctions(node->getAsAggregate()->getSequence());
2250
John Kessenich6fccb3c2016-09-19 16:01:41 -06002251 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002252 // anything else gets there, so visit out of order, doing them all now.
2253 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2254
John Kessenich6a60c2f2016-12-08 21:01:59 -07002255 // 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 -06002256 // so do them manually.
2257 visitFunctions(node->getAsAggregate()->getSequence());
2258
2259 return false;
2260 }
2261
2262 return true;
2263 }
2264 case glslang::EOpLinkerObjects:
2265 {
2266 if (visit == glslang::EvPreVisit)
2267 linkageOnly = true;
2268 else
2269 linkageOnly = false;
2270
2271 return true;
2272 }
2273 case glslang::EOpComma:
2274 {
2275 // processing from left to right naturally leaves the right-most
2276 // lying around in the access chain
2277 glslang::TIntermSequence& glslangOperands = node->getSequence();
2278 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2279 glslangOperands[i]->traverse(this);
2280
2281 return false;
2282 }
2283 case glslang::EOpFunction:
2284 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002285 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002286 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002287 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002288 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002289 } else {
2290 handleFunctionEntry(node);
2291 }
2292 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002293 if (inEntryPoint)
2294 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002295 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002296 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002297 }
2298
2299 return true;
2300 case glslang::EOpParameters:
2301 // Parameters will have been consumed by EOpFunction processing, but not
2302 // the body, so we still visited the function node's children, making this
2303 // child redundant.
2304 return false;
2305 case glslang::EOpFunctionCall:
2306 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002307 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002308 if (node->isUserDefined())
2309 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002310 // 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 -07002311 if (result) {
2312 builder.clearAccessChain();
2313 builder.setAccessChainRValue(result);
2314 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002315 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002316
2317 return false;
2318 }
2319 case glslang::EOpConstructMat2x2:
2320 case glslang::EOpConstructMat2x3:
2321 case glslang::EOpConstructMat2x4:
2322 case glslang::EOpConstructMat3x2:
2323 case glslang::EOpConstructMat3x3:
2324 case glslang::EOpConstructMat3x4:
2325 case glslang::EOpConstructMat4x2:
2326 case glslang::EOpConstructMat4x3:
2327 case glslang::EOpConstructMat4x4:
2328 case glslang::EOpConstructDMat2x2:
2329 case glslang::EOpConstructDMat2x3:
2330 case glslang::EOpConstructDMat2x4:
2331 case glslang::EOpConstructDMat3x2:
2332 case glslang::EOpConstructDMat3x3:
2333 case glslang::EOpConstructDMat3x4:
2334 case glslang::EOpConstructDMat4x2:
2335 case glslang::EOpConstructDMat4x3:
2336 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002337 case glslang::EOpConstructIMat2x2:
2338 case glslang::EOpConstructIMat2x3:
2339 case glslang::EOpConstructIMat2x4:
2340 case glslang::EOpConstructIMat3x2:
2341 case glslang::EOpConstructIMat3x3:
2342 case glslang::EOpConstructIMat3x4:
2343 case glslang::EOpConstructIMat4x2:
2344 case glslang::EOpConstructIMat4x3:
2345 case glslang::EOpConstructIMat4x4:
2346 case glslang::EOpConstructUMat2x2:
2347 case glslang::EOpConstructUMat2x3:
2348 case glslang::EOpConstructUMat2x4:
2349 case glslang::EOpConstructUMat3x2:
2350 case glslang::EOpConstructUMat3x3:
2351 case glslang::EOpConstructUMat3x4:
2352 case glslang::EOpConstructUMat4x2:
2353 case glslang::EOpConstructUMat4x3:
2354 case glslang::EOpConstructUMat4x4:
2355 case glslang::EOpConstructBMat2x2:
2356 case glslang::EOpConstructBMat2x3:
2357 case glslang::EOpConstructBMat2x4:
2358 case glslang::EOpConstructBMat3x2:
2359 case glslang::EOpConstructBMat3x3:
2360 case glslang::EOpConstructBMat3x4:
2361 case glslang::EOpConstructBMat4x2:
2362 case glslang::EOpConstructBMat4x3:
2363 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002364 case glslang::EOpConstructF16Mat2x2:
2365 case glslang::EOpConstructF16Mat2x3:
2366 case glslang::EOpConstructF16Mat2x4:
2367 case glslang::EOpConstructF16Mat3x2:
2368 case glslang::EOpConstructF16Mat3x3:
2369 case glslang::EOpConstructF16Mat3x4:
2370 case glslang::EOpConstructF16Mat4x2:
2371 case glslang::EOpConstructF16Mat4x3:
2372 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002373 isMatrix = true;
2374 // fall through
2375 case glslang::EOpConstructFloat:
2376 case glslang::EOpConstructVec2:
2377 case glslang::EOpConstructVec3:
2378 case glslang::EOpConstructVec4:
2379 case glslang::EOpConstructDouble:
2380 case glslang::EOpConstructDVec2:
2381 case glslang::EOpConstructDVec3:
2382 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002383 case glslang::EOpConstructFloat16:
2384 case glslang::EOpConstructF16Vec2:
2385 case glslang::EOpConstructF16Vec3:
2386 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002387 case glslang::EOpConstructBool:
2388 case glslang::EOpConstructBVec2:
2389 case glslang::EOpConstructBVec3:
2390 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002391 case glslang::EOpConstructInt8:
2392 case glslang::EOpConstructI8Vec2:
2393 case glslang::EOpConstructI8Vec3:
2394 case glslang::EOpConstructI8Vec4:
2395 case glslang::EOpConstructUint8:
2396 case glslang::EOpConstructU8Vec2:
2397 case glslang::EOpConstructU8Vec3:
2398 case glslang::EOpConstructU8Vec4:
2399 case glslang::EOpConstructInt16:
2400 case glslang::EOpConstructI16Vec2:
2401 case glslang::EOpConstructI16Vec3:
2402 case glslang::EOpConstructI16Vec4:
2403 case glslang::EOpConstructUint16:
2404 case glslang::EOpConstructU16Vec2:
2405 case glslang::EOpConstructU16Vec3:
2406 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002407 case glslang::EOpConstructInt:
2408 case glslang::EOpConstructIVec2:
2409 case glslang::EOpConstructIVec3:
2410 case glslang::EOpConstructIVec4:
2411 case glslang::EOpConstructUint:
2412 case glslang::EOpConstructUVec2:
2413 case glslang::EOpConstructUVec3:
2414 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002415 case glslang::EOpConstructInt64:
2416 case glslang::EOpConstructI64Vec2:
2417 case glslang::EOpConstructI64Vec3:
2418 case glslang::EOpConstructI64Vec4:
2419 case glslang::EOpConstructUint64:
2420 case glslang::EOpConstructU64Vec2:
2421 case glslang::EOpConstructU64Vec3:
2422 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002423 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002424 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002425 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002426 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002427 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002428 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002429 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002430 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002431 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002432 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002433 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002434 else if (node->getOp() == glslang::EOpConstructStruct ||
2435 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2436 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002437 std::vector<spv::Id> constituents;
2438 for (int c = 0; c < (int)arguments.size(); ++c)
2439 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002440 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002441 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002442 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002443 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002444 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002445
2446 builder.clearAccessChain();
2447 builder.setAccessChainRValue(constructed);
2448
2449 return false;
2450 }
2451
2452 // These six are component-wise compares with component-wise results.
2453 // Forward on to createBinaryOperation(), requesting a vector result.
2454 case glslang::EOpLessThan:
2455 case glslang::EOpGreaterThan:
2456 case glslang::EOpLessThanEqual:
2457 case glslang::EOpGreaterThanEqual:
2458 case glslang::EOpVectorEqual:
2459 case glslang::EOpVectorNotEqual:
2460 {
2461 // Map the operation to a binary
2462 binOp = node->getOp();
2463 reduceComparison = false;
2464 switch (node->getOp()) {
2465 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2466 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2467 default: binOp = node->getOp(); break;
2468 }
2469
2470 break;
2471 }
2472 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002473 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002474 binOp = glslang::EOpMul;
2475 break;
2476 case glslang::EOpOuterProduct:
2477 // two vectors multiplied to make a matrix
2478 binOp = glslang::EOpOuterProduct;
2479 break;
2480 case glslang::EOpDot:
2481 {
qining25262b32016-05-06 17:25:16 -04002482 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002483 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002484 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002485 binOp = glslang::EOpMul;
2486 break;
2487 }
2488 case glslang::EOpMod:
2489 // when an aggregate, this is the floating-point mod built-in function,
2490 // which can be emitted by the one in createBinaryOperation()
2491 binOp = glslang::EOpMod;
2492 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002493
2494#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002495 case glslang::EOpEmitVertex:
2496 case glslang::EOpEndPrimitive:
2497 case glslang::EOpBarrier:
2498 case glslang::EOpMemoryBarrier:
2499 case glslang::EOpMemoryBarrierAtomicCounter:
2500 case glslang::EOpMemoryBarrierBuffer:
2501 case glslang::EOpMemoryBarrierImage:
2502 case glslang::EOpMemoryBarrierShared:
2503 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002504 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002505 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002506 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002507 case glslang::EOpWorkgroupMemoryBarrier:
2508 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002509 case glslang::EOpSubgroupBarrier:
2510 case glslang::EOpSubgroupMemoryBarrier:
2511 case glslang::EOpSubgroupMemoryBarrierBuffer:
2512 case glslang::EOpSubgroupMemoryBarrierImage:
2513 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002514 noReturnValue = true;
2515 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2516 break;
2517
Jeff Bolz36831c92018-09-05 10:11:41 -05002518 case glslang::EOpAtomicStore:
2519 noReturnValue = true;
2520 // fallthrough
2521 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002522 case glslang::EOpAtomicAdd:
2523 case glslang::EOpAtomicMin:
2524 case glslang::EOpAtomicMax:
2525 case glslang::EOpAtomicAnd:
2526 case glslang::EOpAtomicOr:
2527 case glslang::EOpAtomicXor:
2528 case glslang::EOpAtomicExchange:
2529 case glslang::EOpAtomicCompSwap:
2530 atomic = true;
2531 break;
2532
John Kessenich0d0c6d32017-07-23 16:08:26 -06002533 case glslang::EOpAtomicCounterAdd:
2534 case glslang::EOpAtomicCounterSubtract:
2535 case glslang::EOpAtomicCounterMin:
2536 case glslang::EOpAtomicCounterMax:
2537 case glslang::EOpAtomicCounterAnd:
2538 case glslang::EOpAtomicCounterOr:
2539 case glslang::EOpAtomicCounterXor:
2540 case glslang::EOpAtomicCounterExchange:
2541 case glslang::EOpAtomicCounterCompSwap:
2542 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2543 builder.addCapability(spv::CapabilityAtomicStorageOps);
2544 atomic = true;
2545 break;
2546
Chao Chenb50c02e2018-09-19 11:42:24 -07002547 case glslang::EOpIgnoreIntersectionNV:
2548 case glslang::EOpTerminateRayNV:
2549 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002550 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002551 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2552 noReturnValue = true;
2553 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002554 case glslang::EOpCooperativeMatrixLoad:
2555 case glslang::EOpCooperativeMatrixStore:
2556 noReturnValue = true;
2557 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002558 case glslang::EOpBeginInvocationInterlock:
2559 case glslang::EOpEndInvocationInterlock:
2560 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2561 noReturnValue = true;
2562 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002563#endif
Chao Chen3c366992018-09-19 11:41:59 -07002564
John Kessenich140f3df2015-06-26 16:58:36 -06002565 default:
2566 break;
2567 }
2568
2569 //
2570 // See if it maps to a regular operation.
2571 //
John Kessenich140f3df2015-06-26 16:58:36 -06002572 if (binOp != glslang::EOpNull) {
2573 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2574 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2575 assert(left && right);
2576
2577 builder.clearAccessChain();
2578 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002579 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002580
2581 builder.clearAccessChain();
2582 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002583 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002584
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002585 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002586 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002587 TranslateNoContractionDecoration(node->getType().getQualifier()),
2588 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002589 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002590 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002591 left->getType().getBasicType(), reduceComparison);
2592
2593 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002594 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002595 builder.clearAccessChain();
2596 builder.setAccessChainRValue(result);
2597
2598 return false;
2599 }
2600
John Kessenich426394d2015-07-23 10:22:48 -06002601 //
2602 // Create the list of operands.
2603 //
John Kessenich140f3df2015-06-26 16:58:36 -06002604 glslang::TIntermSequence& glslangOperands = node->getSequence();
2605 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002606 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002607 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002608 // special case l-value operands; there are just a few
2609 bool lvalue = false;
2610 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002611 case glslang::EOpModf:
2612 if (arg == 1)
2613 lvalue = true;
2614 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002615#ifndef GLSLANG_WEB
2616 case glslang::EOpFrexp:
2617 if (arg == 1)
2618 lvalue = true;
2619 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002620 case glslang::EOpInterpolateAtSample:
2621 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002622 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002623 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002624 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002625
2626 // Does it need a swizzle inversion? If so, evaluation is inverted;
2627 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002628 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002629 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2630 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2631 }
Rex Xu7a26c172015-12-08 17:12:09 +08002632 break;
Rex Xud4782c12015-09-06 16:30:11 +08002633 case glslang::EOpAtomicAdd:
2634 case glslang::EOpAtomicMin:
2635 case glslang::EOpAtomicMax:
2636 case glslang::EOpAtomicAnd:
2637 case glslang::EOpAtomicOr:
2638 case glslang::EOpAtomicXor:
2639 case glslang::EOpAtomicExchange:
2640 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002641 case glslang::EOpAtomicLoad:
2642 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002643 case glslang::EOpAtomicCounterAdd:
2644 case glslang::EOpAtomicCounterSubtract:
2645 case glslang::EOpAtomicCounterMin:
2646 case glslang::EOpAtomicCounterMax:
2647 case glslang::EOpAtomicCounterAnd:
2648 case glslang::EOpAtomicCounterOr:
2649 case glslang::EOpAtomicCounterXor:
2650 case glslang::EOpAtomicCounterExchange:
2651 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002652 if (arg == 0)
2653 lvalue = true;
2654 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002655 case glslang::EOpAddCarry:
2656 case glslang::EOpSubBorrow:
2657 if (arg == 2)
2658 lvalue = true;
2659 break;
2660 case glslang::EOpUMulExtended:
2661 case glslang::EOpIMulExtended:
2662 if (arg >= 2)
2663 lvalue = true;
2664 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002665 case glslang::EOpCooperativeMatrixLoad:
2666 if (arg == 0 || arg == 1)
2667 lvalue = true;
2668 break;
2669 case glslang::EOpCooperativeMatrixStore:
2670 if (arg == 1)
2671 lvalue = true;
2672 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002673#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002674 default:
2675 break;
2676 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002677 builder.clearAccessChain();
2678 if (invertedType != spv::NoType && arg == 0)
2679 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2680 else
2681 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002682
2683 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2684 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2685
2686 if (arg == 1) {
2687 // fold "element" parameter into the access chain
2688 spv::Builder::AccessChain save = builder.getAccessChain();
2689 builder.clearAccessChain();
2690 glslangOperands[2]->traverse(this);
2691
2692 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2693
2694 builder.setAccessChain(save);
2695
2696 // Point to the first element of the array.
2697 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002698 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002699
2700 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2701 unsigned int alignment = builder.getAccessChain().alignment;
2702
2703 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2704 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2705 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2706 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2707 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2708 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2709 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2710 }
2711
2712 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2713
2714 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2715 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2716 }
2717
2718 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2719 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2720 }
2721 } else if (arg == 2) {
2722 continue;
2723 }
2724 }
2725
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002726 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002727 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002728 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2729 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2730 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002731 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002732 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002733 }
John Kessenich140f3df2015-06-26 16:58:36 -06002734 }
John Kessenich426394d2015-07-23 10:22:48 -06002735
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002736 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002737 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2738 std::vector<spv::IdImmediate> idImmOps;
2739
2740 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2741 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2742 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2743 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2744 // get the pointee type
2745 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2746 assert(builder.isCooperativeMatrixType(typeId));
2747 // do the op
2748 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2749 // store the result to the pointer (out param 'm')
2750 builder.createStore(result, operands[0]);
2751 result = 0;
2752 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2753 std::vector<spv::IdImmediate> idImmOps;
2754
2755 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2756 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2757 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2758 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2759 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2760
2761 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2762 result = 0;
2763 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002764 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002765 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002766 } else {
2767 // Pass through to generic operations.
2768 switch (glslangOperands.size()) {
2769 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002770 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002771 break;
2772 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002773 {
2774 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002775 TranslateNoContractionDecoration(node->getType().getQualifier()),
2776 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002777 result = createUnaryOperation(
2778 node->getOp(), decorations,
2779 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002780 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002781 }
John Kessenich426394d2015-07-23 10:22:48 -06002782 break;
2783 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002784 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002785 break;
2786 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002787 if (invertedType)
2788 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002789 }
2790
2791 if (noReturnValue)
2792 return false;
2793
2794 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002795 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002796 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002797 } else {
2798 builder.clearAccessChain();
2799 builder.setAccessChainRValue(result);
2800 return false;
2801 }
2802}
2803
John Kessenich433e9ff2017-01-26 20:31:11 -07002804// This path handles both if-then-else and ?:
2805// The if-then-else has a node type of void, while
2806// ?: has either a void or a non-void node type
2807//
2808// Leaving the result, when not void:
2809// GLSL only has r-values as the result of a :?, but
2810// if we have an l-value, that can be more efficient if it will
2811// become the base of a complex r-value expression, because the
2812// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002813bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2814{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002815 // see if OpSelect can handle it
2816 const auto isOpSelectable = [&]() {
2817 if (node->getBasicType() == glslang::EbtVoid)
2818 return false;
2819 // OpSelect can do all other types starting with SPV 1.4
2820 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2821 // pre-1.4, only scalars and vectors can be handled
2822 if ((!node->getType().isScalar() && !node->getType().isVector()))
2823 return false;
2824 }
2825 return true;
2826 };
2827
John Kessenich4bee5312018-02-20 21:29:05 -07002828 // See if it simple and safe, or required, to execute both sides.
2829 // Crucially, side effects must be either semantically required or avoided,
2830 // and there are performance trade-offs.
2831 // Return true if required or a good idea (and safe) to execute both sides,
2832 // false otherwise.
2833 const auto bothSidesPolicy = [&]() -> bool {
2834 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002835 if (node->getTrueBlock() == nullptr ||
2836 node->getFalseBlock() == nullptr)
2837 return false;
2838
John Kessenich4bee5312018-02-20 21:29:05 -07002839 // required? (unless we write additional code to look for side effects
2840 // and make performance trade-offs if none are present)
2841 if (!node->getShortCircuit())
2842 return true;
2843
2844 // if not required to execute both, decide based on performance/practicality...
2845
John Kessenich0c1e71a2019-01-10 18:23:06 +07002846 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002847 return false;
2848
John Kessenich433e9ff2017-01-26 20:31:11 -07002849 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2850 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2851
2852 // return true if a single operand to ? : is okay for OpSelect
2853 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002854 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002855 };
2856
2857 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2858 operandOkay(node->getFalseBlock()->getAsTyped());
2859 };
2860
John Kessenich4bee5312018-02-20 21:29:05 -07002861 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2862 // emit the condition before doing anything with selection
2863 node->getCondition()->traverse(this);
2864 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2865
2866 // Find a way of executing both sides and selecting the right result.
2867 const auto executeBothSides = [&]() -> void {
2868 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002869 node->getTrueBlock()->traverse(this);
2870 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2871 node->getFalseBlock()->traverse(this);
2872 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2873
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002874 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002875
John Kessenich4bee5312018-02-20 21:29:05 -07002876 // done if void
2877 if (node->getBasicType() == glslang::EbtVoid)
2878 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002879
John Kessenich4bee5312018-02-20 21:29:05 -07002880 // emit code to select between trueValue and falseValue
2881
2882 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002883 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002884 // Emit OpSelect for this selection.
2885
2886 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002887 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2888 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002889 condition = builder.smearScalar(spv::NoPrecision, condition,
2890 builder.makeVectorType(builder.makeBoolType(),
2891 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002892 }
John Kessenich4bee5312018-02-20 21:29:05 -07002893
2894 // OpSelect
2895 result = builder.createTriOp(spv::OpSelect,
2896 convertGlslangToSpvType(node->getType()), condition,
2897 trueValue, falseValue);
2898
2899 builder.clearAccessChain();
2900 builder.setAccessChainRValue(result);
2901 } else {
2902 // We need control flow to select the result.
2903 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2904 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2905
2906 // Selection control:
2907 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2908
2909 // make an "if" based on the value created by the condition
2910 spv::Builder::If ifBuilder(condition, control, builder);
2911
2912 // emit the "then" statement
2913 builder.createStore(trueValue, result);
2914 ifBuilder.makeBeginElse();
2915 // emit the "else" statement
2916 builder.createStore(falseValue, result);
2917
2918 // finish off the control flow
2919 ifBuilder.makeEndIf();
2920
2921 builder.clearAccessChain();
2922 builder.setAccessChainLValue(result);
2923 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002924 };
2925
John Kessenich4bee5312018-02-20 21:29:05 -07002926 // Execute the one side needed, as per the condition
2927 const auto executeOneSide = [&]() {
2928 // Always emit control flow.
2929 if (node->getBasicType() != glslang::EbtVoid)
2930 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002931
John Kessenich4bee5312018-02-20 21:29:05 -07002932 // Selection control:
2933 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2934
2935 // make an "if" based on the value created by the condition
2936 spv::Builder::If ifBuilder(condition, control, builder);
2937
2938 // emit the "then" statement
2939 if (node->getTrueBlock() != nullptr) {
2940 node->getTrueBlock()->traverse(this);
2941 if (result != spv::NoResult)
2942 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2943 }
2944
2945 if (node->getFalseBlock() != nullptr) {
2946 ifBuilder.makeBeginElse();
2947 // emit the "else" statement
2948 node->getFalseBlock()->traverse(this);
2949 if (result != spv::NoResult)
2950 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2951 }
2952
2953 // finish off the control flow
2954 ifBuilder.makeEndIf();
2955
2956 if (result != spv::NoResult) {
2957 builder.clearAccessChain();
2958 builder.setAccessChainLValue(result);
2959 }
2960 };
2961
2962 // Try for OpSelect (or a requirement to execute both sides)
2963 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002964 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2965 if (node->getType().getQualifier().isSpecConstant())
2966 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002967 executeBothSides();
2968 } else
2969 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002970
2971 return false;
2972}
2973
2974bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2975{
2976 // emit and get the condition before doing anything with switch
2977 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002978 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002979
Rex Xu57e65922017-07-04 23:23:40 +08002980 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002981 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002982
John Kessenich140f3df2015-06-26 16:58:36 -06002983 // browse the children to sort out code segments
2984 int defaultSegment = -1;
2985 std::vector<TIntermNode*> codeSegments;
2986 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2987 std::vector<int> caseValues;
2988 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2989 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2990 TIntermNode* child = *c;
2991 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002992 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002993 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002994 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002995 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2996 } else
2997 codeSegments.push_back(child);
2998 }
2999
qining25262b32016-05-06 17:25:16 -04003000 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003001 // statements between the last case and the end of the switch statement
3002 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3003 (int)codeSegments.size() == defaultSegment)
3004 codeSegments.push_back(nullptr);
3005
3006 // make the switch statement
3007 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003008 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003009
3010 // emit all the code in the segments
3011 breakForLoop.push(false);
3012 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3013 builder.nextSwitchSegment(segmentBlocks, s);
3014 if (codeSegments[s])
3015 codeSegments[s]->traverse(this);
3016 else
3017 builder.addSwitchBreak();
3018 }
3019 breakForLoop.pop();
3020
3021 builder.endSwitch(segmentBlocks);
3022
3023 return false;
3024}
3025
3026void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3027{
3028 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003029 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003030
3031 builder.clearAccessChain();
3032 builder.setAccessChainRValue(constant);
3033}
3034
3035bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3036{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003037 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003038 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003039
3040 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003041 std::vector<unsigned int> operands;
3042 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003043
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003044 // Spec requires back edges to target header blocks, and every header block
3045 // must dominate its merge block. Make a header block first to ensure these
3046 // conditions are met. By definition, it will contain OpLoopMerge, followed
3047 // by a block-ending branch. But we don't want to put any other body/test
3048 // instructions in it, since the body/test may have arbitrary instructions,
3049 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003050 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003051 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003052 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003053 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003054 spv::Block& test = builder.makeNewBlock();
3055 builder.createBranch(&test);
3056
3057 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003058 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003059 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003060 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3061
3062 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003063 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003064 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003065 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003066 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003067 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003068
3069 builder.setBuildPoint(&blocks.continue_target);
3070 if (node->getTerminal())
3071 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003072 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003073 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003074 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003075 builder.createBranch(&blocks.body);
3076
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003077 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003078 builder.setBuildPoint(&blocks.body);
3079 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003080 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003081 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003082 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003083
3084 builder.setBuildPoint(&blocks.continue_target);
3085 if (node->getTerminal())
3086 node->getTerminal()->traverse(this);
3087 if (node->getTest()) {
3088 node->getTest()->traverse(this);
3089 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003090 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003091 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003092 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003093 // TODO: unless there was a break/return/discard instruction
3094 // somewhere in the body, this is an infinite loop, so we should
3095 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003096 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003097 }
John Kessenich140f3df2015-06-26 16:58:36 -06003098 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003099 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003100 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003101 return false;
3102}
3103
3104bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3105{
3106 if (node->getExpression())
3107 node->getExpression()->traverse(this);
3108
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003109 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003110
John Kessenich140f3df2015-06-26 16:58:36 -06003111 switch (node->getFlowOp()) {
3112 case glslang::EOpKill:
3113 builder.makeDiscard();
3114 break;
3115 case glslang::EOpBreak:
3116 if (breakForLoop.top())
3117 builder.createLoopExit();
3118 else
3119 builder.addSwitchBreak();
3120 break;
3121 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003122 builder.createLoopContinue();
3123 break;
3124 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003125 if (node->getExpression()) {
3126 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3127 spv::Id returnId = accessChainLoad(glslangReturnType);
3128 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3129 builder.clearAccessChain();
3130 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3131 builder.setAccessChainLValue(copyId);
3132 multiTypeStore(glslangReturnType, returnId);
3133 returnId = builder.createLoad(copyId);
3134 }
3135 builder.makeReturn(false, returnId);
3136 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003137 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003138
3139 builder.clearAccessChain();
3140 break;
3141
Jeff Bolzba6170b2019-07-01 09:23:23 -05003142 case glslang::EOpDemote:
3143 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3144 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3145 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3146 break;
3147
John Kessenich140f3df2015-06-26 16:58:36 -06003148 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003149 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 }
3152
3153 return false;
3154}
3155
John Kessenich9c14f772019-06-17 08:38:35 -06003156spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003157{
qining25262b32016-05-06 17:25:16 -04003158 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003159 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003160 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003161 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003162 spv::Id result = createSpvConstant(*node);
3163 if (result != spv::NoResult)
3164 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003165 }
3166
3167 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003168 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003169 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3170 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003171
Rex Xucabbb782017-03-24 13:41:14 +08003172 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3173 node->getType().containsBasicType(glslang::EbtInt16) ||
3174 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003175 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003176 switch (storageClass) {
3177 case spv::StorageClassInput:
3178 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003179 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003180 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003181 break;
3182 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003183 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003184 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003185 break;
3186 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003187 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003188 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3189 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003190 else
3191 builder.addCapability(spv::CapabilityStorageUniform16);
3192 break;
3193 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003194 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003195 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3196 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3197 break;
3198 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003199 if (node->getType().containsBasicType(glslang::EbtFloat16))
3200 builder.addCapability(spv::CapabilityFloat16);
3201 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3202 node->getType().containsBasicType(glslang::EbtUint16))
3203 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003204 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003205 }
3206 }
Rex Xuf89ad982017-04-07 23:22:33 +08003207
John Kessenich312dcfb2018-07-03 13:19:51 -06003208 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3209 node->getType().containsBasicType(glslang::EbtUint8);
3210 if (contains8BitType) {
3211 if (storageClass == spv::StorageClassPushConstant) {
3212 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3213 builder.addCapability(spv::CapabilityStoragePushConstant8);
3214 } else if (storageClass == spv::StorageClassUniform) {
3215 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3216 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003217 } else if (storageClass == spv::StorageClassStorageBuffer) {
3218 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3219 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003220 } else {
3221 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003222 }
3223 }
3224
John Kessenich140f3df2015-06-26 16:58:36 -06003225 const char* name = node->getName().c_str();
3226 if (glslang::IsAnonymous(name))
3227 name = "";
3228
3229 return builder.createVariable(storageClass, spvType, name);
3230}
3231
3232// Return type Id of the sampled type.
3233spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3234{
3235 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003236 case glslang::EbtInt: return builder.makeIntType(32);
3237 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003238 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003239#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003240 case glslang::EbtFloat16:
3241 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3242 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3243 return builder.makeFloatType(16);
3244#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003245 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003247 return builder.makeFloatType(32);
3248 }
3249}
3250
John Kessenich8c8505c2016-07-26 12:50:38 -06003251// If node is a swizzle operation, return the type that should be used if
3252// the swizzle base is first consumed by another operation, before the swizzle
3253// is applied.
3254spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3255{
John Kessenichecba76f2017-01-06 00:34:48 -07003256 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003257 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3258 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3259 else
3260 return spv::NoType;
3261}
3262
3263// When inverting a swizzle with a parent op, this function
3264// will apply the swizzle operation to a completed parent operation.
3265spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3266{
3267 std::vector<unsigned> swizzle;
3268 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3269 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3270}
3271
John Kessenich8c8505c2016-07-26 12:50:38 -06003272// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3273void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3274{
3275 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3276 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3277 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3278}
3279
John Kessenich3ac051e2015-12-20 11:29:16 -07003280// Convert from a glslang type to an SPV type, by calling into a
3281// recursive version of this function. This establishes the inherited
3282// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003283spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003284{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003285 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003286}
3287
3288// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003289// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003290// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003291spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003292 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3293 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003294{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003295 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003296
3297 switch (type.getBasicType()) {
3298 case glslang::EbtVoid:
3299 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003300 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003301 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003302 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003303 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3304 // a 32-bit int where non-0 means true.
3305 if (explicitLayout != glslang::ElpNone)
3306 spvType = builder.makeUintType(32);
3307 else
3308 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003309 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003310 case glslang::EbtInt:
3311 spvType = builder.makeIntType(32);
3312 break;
3313 case glslang::EbtUint:
3314 spvType = builder.makeUintType(32);
3315 break;
3316 case glslang::EbtFloat:
3317 spvType = builder.makeFloatType(32);
3318 break;
3319#ifndef GLSLANG_WEB
3320 case glslang::EbtDouble:
3321 spvType = builder.makeFloatType(64);
3322 break;
3323 case glslang::EbtFloat16:
3324 spvType = builder.makeFloatType(16);
3325 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003326 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003327 spvType = builder.makeIntType(8);
3328 break;
3329 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003330 spvType = builder.makeUintType(8);
3331 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003332 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003333 spvType = builder.makeIntType(16);
3334 break;
3335 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003336 spvType = builder.makeUintType(16);
3337 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003338 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003339 spvType = builder.makeIntType(64);
3340 break;
3341 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003342 spvType = builder.makeUintType(64);
3343 break;
John Kessenich426394d2015-07-23 10:22:48 -06003344 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003345 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003346 spvType = builder.makeUintType(32);
3347 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003348 case glslang::EbtAccStructNV:
3349 spvType = builder.makeAccelerationStructureNVType();
3350 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003351 case glslang::EbtReference:
3352 {
3353 // Make the forward pointer, then recurse to convert the structure type, then
3354 // patch up the forward pointer with a real pointer type.
3355 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3356 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3357 forwardPointers[type.getReferentType()] = forwardId;
3358 }
3359 spvType = forwardPointers[type.getReferentType()];
3360 if (!forwardReferenceOnly) {
3361 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3362 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3363 forwardPointers[type.getReferentType()],
3364 referentType);
3365 }
3366 }
3367 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003368#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003369 case glslang::EbtSampler:
3370 {
3371 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003372 if (sampler.sampler) {
3373 // pure sampler
3374 spvType = builder.makeSamplerType();
3375 } else {
3376 // an image is present, make its type
3377 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3378 sampler.image ? 2 : 1, TranslateImageFormat(type));
3379 if (sampler.combined) {
3380 // already has both image and sampler, make the combined type
3381 spvType = builder.makeSampledImageType(spvType);
3382 }
John Kessenich55e7d112015-11-15 21:33:39 -07003383 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003384 }
John Kessenich140f3df2015-06-26 16:58:36 -06003385 break;
3386 case glslang::EbtStruct:
3387 case glslang::EbtBlock:
3388 {
3389 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003390 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003391
3392 // Try to share structs for different layouts, but not yet for other
3393 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003394 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003395 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003396 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003397 break;
3398
3399 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003400 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003401 memberRemapper[glslangMembers].resize(glslangMembers->size());
3402 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003403 }
3404 break;
3405 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003406 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 }
3409
3410 if (type.isMatrix())
3411 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3412 else {
3413 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3414 if (type.getVectorSize() > 1)
3415 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3416 }
3417
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003418 if (type.isCoopMat()) {
3419 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3420 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3421 if (type.getBasicType() == glslang::EbtFloat16)
3422 builder.addCapability(spv::CapabilityFloat16);
3423
3424 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3425 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3426 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3427
3428 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3429 }
3430
John Kessenich140f3df2015-06-26 16:58:36 -06003431 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003432 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3433
John Kessenichc9a80832015-09-12 12:17:44 -06003434 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003435 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003436 // We need to decorate array strides for types needing explicit layout, except blocks.
3437 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003438 // Use a dummy glslang type for querying internal strides of
3439 // arrays of arrays, but using just a one-dimensional array.
3440 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003441 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3442 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003443
3444 // Will compute the higher-order strides here, rather than making a whole
3445 // pile of types and doing repetitive recursion on their contents.
3446 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3447 }
John Kessenichf8842e52016-01-04 19:22:56 -07003448
3449 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003450 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003451 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003452 if (stride > 0)
3453 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003454 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003455 }
3456 } else {
3457 // single-dimensional array, and don't yet have stride
3458
John Kessenichf8842e52016-01-04 19:22:56 -07003459 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003460 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3461 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003462 }
John Kessenich31ed4832015-09-09 17:51:38 -06003463
John Kessenichead86222018-03-28 18:01:20 -06003464 // Do the outer dimension, which might not be known for a runtime-sized array.
3465 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3466 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003467 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003468 else {
3469 if (!lastBufferBlockMember) {
3470 builder.addExtension("SPV_EXT_descriptor_indexing");
3471 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3472 }
John Kessenichead86222018-03-28 18:01:20 -06003473 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003474 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003475 if (stride > 0)
3476 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003477 }
3478
3479 return spvType;
3480}
3481
John Kessenich0e737842017-03-24 18:38:16 -06003482// TODO: this functionality should exist at a higher level, in creating the AST
3483//
3484// Identify interface members that don't have their required extension turned on.
3485//
3486bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3487{
John Kessenicha28f7a72019-08-06 07:00:58 -06003488#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003489 auto& extensions = glslangIntermediate->getRequestedExtensions();
3490
Rex Xubcf291a2017-03-29 23:01:36 +08003491 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3492 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3493 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003494 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3495 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3496 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003497
3498 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3499 if (member.getFieldName() == "gl_ViewportMask" &&
3500 extensions.find("GL_NV_viewport_array2") == extensions.end())
3501 return true;
3502 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3503 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3504 return true;
3505 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3506 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3507 return true;
3508 }
3509#endif
John Kessenich0e737842017-03-24 18:38:16 -06003510
3511 return false;
3512};
3513
John Kessenich6090df02016-06-30 21:18:02 -06003514// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3515// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3516// Mutually recursive with convertGlslangToSpvType().
3517spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3518 const glslang::TTypeList* glslangMembers,
3519 glslang::TLayoutPacking explicitLayout,
3520 const glslang::TQualifier& qualifier)
3521{
3522 // Create a vector of struct types for SPIR-V to consume
3523 std::vector<spv::Id> spvMembers;
3524 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003525 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003526 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3527 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3528 if (glslangMember.hiddenMember()) {
3529 ++memberDelta;
3530 if (type.getBasicType() == glslang::EbtBlock)
3531 memberRemapper[glslangMembers][i] = -1;
3532 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003533 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003534 if (filterMember(glslangMember)) {
3535 memberDelta++;
3536 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003537 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003538 }
3539 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003540 }
John Kessenich6090df02016-06-30 21:18:02 -06003541 // modify just this child's view of the qualifier
3542 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3543 InheritQualifiers(memberQualifier, qualifier);
3544
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003545 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003546 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003547 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003548
3549 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003550 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3551 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003552
3553 // Make forward pointers for any pointer members, and create a list of members to
3554 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003555 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003556 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3557 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3558 }
3559 spvMembers.push_back(
3560 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3561 } else {
3562 spvMembers.push_back(
3563 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3564 }
John Kessenich6090df02016-06-30 21:18:02 -06003565 }
3566 }
3567
3568 // Make the SPIR-V type
3569 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003570 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003571 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3572
3573 // Decorate it
3574 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3575
John Kessenichd72f4882019-01-16 14:55:37 +07003576 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003577 auto it = deferredForwardPointers[i];
3578 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3579 }
3580
John Kessenich6090df02016-06-30 21:18:02 -06003581 return spvType;
3582}
3583
3584void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3585 const glslang::TTypeList* glslangMembers,
3586 glslang::TLayoutPacking explicitLayout,
3587 const glslang::TQualifier& qualifier,
3588 spv::Id spvType)
3589{
3590 // Name and decorate the non-hidden members
3591 int offset = -1;
3592 int locationOffset = 0; // for use within the members of this struct
3593 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3594 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3595 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003596 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003597 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003598 if (filterMember(glslangMember))
3599 continue;
3600 }
John Kessenich6090df02016-06-30 21:18:02 -06003601
3602 // modify just this child's view of the qualifier
3603 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3604 InheritQualifiers(memberQualifier, qualifier);
3605
3606 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003607 if (member < 0)
3608 continue;
3609
3610 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3611 builder.addMemberDecoration(spvType, member,
3612 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3613 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3614 // Add interpolation and auxiliary storage decorations only to
3615 // top-level members of Input and Output storage classes
3616 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3617 type.getQualifier().storage == glslang::EvqVaryingOut) {
3618 if (type.getBasicType() == glslang::EbtBlock ||
3619 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3620 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3621 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003622#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003623 addMeshNVDecoration(spvType, member, memberQualifier);
3624#endif
John Kessenich6090df02016-06-30 21:18:02 -06003625 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003626 }
3627 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003628
John Kessenich5d610ee2018-03-07 18:05:55 -07003629 if (type.getBasicType() == glslang::EbtBlock &&
3630 qualifier.storage == glslang::EvqBuffer) {
3631 // Add memory decorations only to top-level members of shader storage block
3632 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003633 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003634 for (unsigned int i = 0; i < memory.size(); ++i)
3635 builder.addMemberDecoration(spvType, member, memory[i]);
3636 }
John Kessenich6090df02016-06-30 21:18:02 -06003637
John Kessenich5d610ee2018-03-07 18:05:55 -07003638 // Location assignment was already completed correctly by the front end,
3639 // just track whether a member needs to be decorated.
3640 // Ignore member locations if the container is an array, as that's
3641 // ill-specified and decisions have been made to not allow this.
3642 if (! type.isArray() && memberQualifier.hasLocation())
3643 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003644
John Kessenich5d610ee2018-03-07 18:05:55 -07003645 if (qualifier.hasLocation()) // track for upcoming inheritance
3646 locationOffset += glslangIntermediate->computeTypeLocationSize(
3647 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003648
John Kessenich5d610ee2018-03-07 18:05:55 -07003649 // component, XFB, others
3650 if (glslangMember.getQualifier().hasComponent())
3651 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3652 glslangMember.getQualifier().layoutComponent);
3653 if (glslangMember.getQualifier().hasXfbOffset())
3654 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3655 glslangMember.getQualifier().layoutXfbOffset);
3656 else if (explicitLayout != glslang::ElpNone) {
3657 // figure out what to do with offset, which is accumulating
3658 int nextOffset;
3659 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3660 if (offset >= 0)
3661 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3662 offset = nextOffset;
3663 }
John Kessenich6090df02016-06-30 21:18:02 -06003664
John Kessenich5d610ee2018-03-07 18:05:55 -07003665 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3666 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3667 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003668
John Kessenich5d610ee2018-03-07 18:05:55 -07003669 // built-in variable decorations
3670 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3671 if (builtIn != spv::BuiltInMax)
3672 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003673
John Kessenich5611c6d2018-04-05 11:25:02 -06003674 // nonuniform
3675 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3676
John Kessenichead86222018-03-28 18:01:20 -06003677 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3678 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3679 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3680 memberQualifier.semanticName);
3681 }
3682
John Kessenicha28f7a72019-08-06 07:00:58 -06003683#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003684 if (builtIn == spv::BuiltInLayer) {
3685 // SPV_NV_viewport_array2 extension
3686 if (glslangMember.getQualifier().layoutViewportRelative){
3687 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3688 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3689 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003690 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003691 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3692 builder.addMemberDecoration(spvType, member,
3693 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3694 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3695 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3696 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003697 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003698 }
3699 if (glslangMember.getQualifier().layoutPassthrough) {
3700 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3701 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3702 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3703 }
chaoc771d89f2017-01-13 01:10:53 -08003704#endif
John Kessenich6090df02016-06-30 21:18:02 -06003705 }
3706
3707 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003708 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3709 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003710}
3711
John Kessenich6c292d32016-02-15 20:58:50 -07003712// Turn the expression forming the array size into an id.
3713// This is not quite trivial, because of specialization constants.
3714// Sometimes, a raw constant is turned into an Id, and sometimes
3715// a specialization constant expression is.
3716spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3717{
3718 // First, see if this is sized with a node, meaning a specialization constant:
3719 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3720 if (specNode != nullptr) {
3721 builder.clearAccessChain();
3722 specNode->traverse(this);
3723 return accessChainLoad(specNode->getAsTyped()->getType());
3724 }
qining25262b32016-05-06 17:25:16 -04003725
John Kessenich6c292d32016-02-15 20:58:50 -07003726 // Otherwise, need a compile-time (front end) size, get it:
3727 int size = arraySizes.getDimSize(dim);
3728 assert(size > 0);
3729 return builder.makeUintConstant(size);
3730}
3731
John Kessenich103bef92016-02-08 21:38:15 -07003732// Wrap the builder's accessChainLoad to:
3733// - localize handling of RelaxedPrecision
3734// - use the SPIR-V inferred type instead of another conversion of the glslang type
3735// (avoids unnecessary work and possible type punning for structures)
3736// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003737spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3738{
John Kessenich103bef92016-02-08 21:38:15 -07003739 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003740
3741 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3742 coherentFlags |= TranslateCoherent(type);
3743
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003744 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003745 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003746
John Kessenich5611c6d2018-04-05 11:25:02 -06003747 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003748 TranslateNonUniformDecoration(type.getQualifier()),
3749 nominalTypeId,
3750 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003751 TranslateMemoryScope(coherentFlags),
3752 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003753
3754 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003755 if (type.getBasicType() == glslang::EbtBool) {
3756 if (builder.isScalarType(nominalTypeId)) {
3757 // Conversion for bool
3758 spv::Id boolType = builder.makeBoolType();
3759 if (nominalTypeId != boolType)
3760 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3761 } else if (builder.isVectorType(nominalTypeId)) {
3762 // Conversion for bvec
3763 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3764 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3765 if (nominalTypeId != bvecType)
3766 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3767 }
3768 }
John Kessenich103bef92016-02-08 21:38:15 -07003769
3770 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003771}
3772
Rex Xu27253232016-02-23 17:51:09 +08003773// Wrap the builder's accessChainStore to:
3774// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003775//
3776// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003777void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3778{
3779 // Need to convert to abstract types when necessary
3780 if (type.getBasicType() == glslang::EbtBool) {
3781 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3782
3783 if (builder.isScalarType(nominalTypeId)) {
3784 // Conversion for bool
3785 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003786 if (nominalTypeId != boolType) {
3787 // keep these outside arguments, for determinant order-of-evaluation
3788 spv::Id one = builder.makeUintConstant(1);
3789 spv::Id zero = builder.makeUintConstant(0);
3790 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3791 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003792 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003793 } else if (builder.isVectorType(nominalTypeId)) {
3794 // Conversion for bvec
3795 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3796 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003797 if (nominalTypeId != bvecType) {
3798 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003799 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3800 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3801 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003802 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003803 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3804 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003805 }
3806 }
3807
Jeff Bolz36831c92018-09-05 10:11:41 -05003808 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3809 coherentFlags |= TranslateCoherent(type);
3810
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003811 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003812 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003813
Jeff Bolz36831c92018-09-05 10:11:41 -05003814 builder.accessChainStore(rvalue,
3815 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003816 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003817}
3818
John Kessenich4bf71552016-09-02 11:20:21 -06003819// For storing when types match at the glslang level, but not might match at the
3820// SPIR-V level.
3821//
3822// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003823// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003824// as in a member-decorated way.
3825//
3826// NOTE: This function can handle any store request; if it's not special it
3827// simplifies to a simple OpStore.
3828//
3829// Implicitly uses the existing builder.accessChain as the storage target.
3830void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3831{
John Kessenichb3e24e42016-09-11 12:33:43 -06003832 // we only do the complex path here if it's an aggregate
3833 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003834 accessChainStore(type, rValue);
3835 return;
3836 }
3837
John Kessenichb3e24e42016-09-11 12:33:43 -06003838 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003839 spv::Id rType = builder.getTypeId(rValue);
3840 spv::Id lValue = builder.accessChainGetLValue();
3841 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3842 if (lType == rType) {
3843 accessChainStore(type, rValue);
3844 return;
3845 }
3846
John Kessenichb3e24e42016-09-11 12:33:43 -06003847 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003848 // where the two types were the same type in GLSL. This requires member
3849 // by member copy, recursively.
3850
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003851 // SPIR-V 1.4 added an instruction to do help do this.
3852 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3853 // However, bool in uniform space is changed to int, so
3854 // OpCopyLogical does not work for that.
3855 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3856 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3857 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3858 if (lBool == rBool) {
3859 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3860 accessChainStore(type, logicalCopy);
3861 return;
3862 }
3863 }
3864
John Kessenichb3e24e42016-09-11 12:33:43 -06003865 // If an array, copy element by element.
3866 if (type.isArray()) {
3867 glslang::TType glslangElementType(type, 0);
3868 spv::Id elementRType = builder.getContainedTypeId(rType);
3869 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3870 // get the source member
3871 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003872
John Kessenichb3e24e42016-09-11 12:33:43 -06003873 // set up the target storage
3874 builder.clearAccessChain();
3875 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003876 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003877
John Kessenichb3e24e42016-09-11 12:33:43 -06003878 // store the member
3879 multiTypeStore(glslangElementType, elementRValue);
3880 }
3881 } else {
3882 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003883
John Kessenichb3e24e42016-09-11 12:33:43 -06003884 // loop over structure members
3885 const glslang::TTypeList& members = *type.getStruct();
3886 for (int m = 0; m < (int)members.size(); ++m) {
3887 const glslang::TType& glslangMemberType = *members[m].type;
3888
3889 // get the source member
3890 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3891 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3892
3893 // set up the target storage
3894 builder.clearAccessChain();
3895 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003896 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003897
3898 // store the member
3899 multiTypeStore(glslangMemberType, memberRValue);
3900 }
John Kessenich4bf71552016-09-02 11:20:21 -06003901 }
3902}
3903
John Kessenichf85e8062015-12-19 13:57:10 -07003904// Decide whether or not this type should be
3905// decorated with offsets and strides, and if so
3906// whether std140 or std430 rules should be applied.
3907glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003908{
John Kessenichf85e8062015-12-19 13:57:10 -07003909 // has to be a block
3910 if (type.getBasicType() != glslang::EbtBlock)
3911 return glslang::ElpNone;
3912
Chao Chen3c366992018-09-19 11:41:59 -07003913 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003914 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003915 type.getQualifier().storage != glslang::EvqBuffer &&
3916 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003917 return glslang::ElpNone;
3918
3919 // return the layout to use
3920 switch (type.getQualifier().layoutPacking) {
3921 case glslang::ElpStd140:
3922 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003923 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003924 return type.getQualifier().layoutPacking;
3925 default:
3926 return glslang::ElpNone;
3927 }
John Kessenich31ed4832015-09-09 17:51:38 -06003928}
3929
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003930// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003931int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003932{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003933 int size;
John Kessenich49987892015-12-29 17:11:44 -07003934 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003935 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003936
3937 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003938}
3939
John Kessenich49987892015-12-29 17:11:44 -07003940// 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 -07003941// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003942int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003943{
John Kessenich49987892015-12-29 17:11:44 -07003944 glslang::TType elementType;
3945 elementType.shallowCopy(matrixType);
3946 elementType.clearArraySizes();
3947
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003948 int size;
John Kessenich49987892015-12-29 17:11:44 -07003949 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003950 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003951
3952 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003953}
3954
John Kessenich5e4b1242015-08-06 22:53:06 -06003955// Given a member type of a struct, realign the current offset for it, and compute
3956// the next (not yet aligned) offset for the next member, which will get aligned
3957// on the next call.
3958// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3959// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3960// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003961void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003962 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003963{
3964 // this will get a positive value when deemed necessary
3965 nextOffset = -1;
3966
John Kessenich5e4b1242015-08-06 22:53:06 -06003967 // override anything in currentOffset with user-set offset
3968 if (memberType.getQualifier().hasOffset())
3969 currentOffset = memberType.getQualifier().layoutOffset;
3970
3971 // It could be that current linker usage in glslang updated all the layoutOffset,
3972 // in which case the following code does not matter. But, that's not quite right
3973 // once cross-compilation unit GLSL validation is done, as the original user
3974 // settings are needed in layoutOffset, and then the following will come into play.
3975
John Kessenichf85e8062015-12-19 13:57:10 -07003976 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003977 if (! memberType.getQualifier().hasOffset())
3978 currentOffset = -1;
3979
3980 return;
3981 }
3982
John Kessenichf85e8062015-12-19 13:57:10 -07003983 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003984 if (currentOffset < 0)
3985 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003986
John Kessenich5e4b1242015-08-06 22:53:06 -06003987 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3988 // but possibly not yet correctly aligned.
3989
3990 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003991 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003992 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003993
3994 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003995 // TODO: make this consistent in early phases of code:
3996 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3997 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3998 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003999 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004000 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004001 int dummySize;
4002 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4003 if (componentAlignment <= 4)
4004 memberAlignment = componentAlignment;
4005 }
4006
4007 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004008 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004009
4010 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004011 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004012 glslang::RoundToPow2(currentOffset, 16);
4013
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 nextOffset = currentOffset + memberSize;
4015}
4016
David Netoa901ffe2016-06-08 14:11:40 +01004017void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004018{
David Netoa901ffe2016-06-08 14:11:40 +01004019 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4020 switch (glslangBuiltIn)
4021 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004022 case glslang::EbvPointSize:
4023#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004024 case glslang::EbvClipDistance:
4025 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004026 case glslang::EbvViewportMaskNV:
4027 case glslang::EbvSecondaryPositionNV:
4028 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004029 case glslang::EbvPositionPerViewNV:
4030 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004031 case glslang::EbvTaskCountNV:
4032 case glslang::EbvPrimitiveCountNV:
4033 case glslang::EbvPrimitiveIndicesNV:
4034 case glslang::EbvClipDistancePerViewNV:
4035 case glslang::EbvCullDistancePerViewNV:
4036 case glslang::EbvLayerPerViewNV:
4037 case glslang::EbvMeshViewCountNV:
4038 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004039#endif
David Netoa901ffe2016-06-08 14:11:40 +01004040 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4041 // Alternately, we could just call this for any glslang built-in, since the
4042 // capability already guards against duplicates.
4043 TranslateBuiltInDecoration(glslangBuiltIn, false);
4044 break;
4045 default:
4046 // Capabilities were already generated when the struct was declared.
4047 break;
4048 }
John Kessenichebb50532016-05-16 19:22:05 -06004049}
4050
John Kessenich6fccb3c2016-09-19 16:01:41 -06004051bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004052{
John Kessenicheee9d532016-09-19 18:09:30 -06004053 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004054}
4055
John Kessenichd41993d2017-09-10 15:21:05 -06004056// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004057// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4058// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004059bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004060{
John Kessenich6a14f782017-12-04 02:48:10 -07004061 assert(qualifier == glslang::EvqIn ||
4062 qualifier == glslang::EvqOut ||
4063 qualifier == glslang::EvqInOut ||
4064 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004065 return qualifier != glslang::EvqConstReadOnly;
4066}
4067
4068// Is parameter pass-by-original?
4069bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4070 bool implicitThisParam)
4071{
4072 if (implicitThisParam) // implicit this
4073 return true;
4074 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004075 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004076 return paramType.containsOpaque() || // sampler, etc.
4077 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4078}
4079
John Kessenich140f3df2015-06-26 16:58:36 -06004080// Make all the functions, skeletally, without actually visiting their bodies.
4081void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4082{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004083 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004084 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4085 if (paramPrecision != spv::NoPrecision)
4086 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004087 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004088 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004089 // Original and non-writable params pass the pointer directly and
4090 // use restrict/aliased, others are stored to a pointer in Function
4091 // memory and use RestrictPointer/AliasedPointer.
4092 if (originalParam(type.getQualifier().storage, type, false) ||
4093 !writableParam(type.getQualifier().storage)) {
4094 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4095 } else {
4096 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4097 }
4098 }
John Kessenichfad62972017-07-18 02:35:46 -06004099 };
4100
John Kessenich140f3df2015-06-26 16:58:36 -06004101 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4102 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004103 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004104 continue;
4105
4106 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004107 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004108 //
qining25262b32016-05-06 17:25:16 -04004109 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004110 // function. What it is an address of varies:
4111 //
John Kessenich4bf71552016-09-02 11:20:21 -06004112 // - "in" parameters not marked as "const" can be written to without modifying the calling
4113 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004114 //
4115 // - "const in" parameters can just be the r-value, as no writes need occur.
4116 //
John Kessenich4bf71552016-09-02 11:20:21 -06004117 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4118 // 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 -06004119
4120 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004121 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004122 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4123
John Kessenichfad62972017-07-18 02:35:46 -06004124 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4125 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06004126
John Kessenichfad62972017-07-18 02:35:46 -06004127 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004128 for (int p = 0; p < (int)parameters.size(); ++p) {
4129 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4130 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004131 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004132 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004133 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004134 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4135 else
John Kessenich4bf71552016-09-02 11:20:21 -06004136 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004137 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004138 paramTypes.push_back(typeId);
4139 }
4140
4141 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004142 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4143 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004144 glslFunction->getName().c_str(), paramTypes,
4145 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004146 if (implicitThis)
4147 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004148
4149 // Track function to emit/call later
4150 functionMap[glslFunction->getName().c_str()] = function;
4151
4152 // Set the parameter id's
4153 for (int p = 0; p < (int)parameters.size(); ++p) {
4154 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4155 // give a name too
4156 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004157
4158 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4159 if (paramType.containsBasicType(glslang::EbtInt8) ||
4160 paramType.containsBasicType(glslang::EbtUint8))
4161 builder.addCapability(spv::CapabilityInt8);
4162 if (paramType.containsBasicType(glslang::EbtInt16) ||
4163 paramType.containsBasicType(glslang::EbtUint16))
4164 builder.addCapability(spv::CapabilityInt16);
4165 if (paramType.containsBasicType(glslang::EbtFloat16))
4166 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004167 }
4168 }
4169}
4170
4171// Process all the initializers, while skipping the functions and link objects
4172void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4173{
4174 builder.setBuildPoint(shaderEntry->getLastBlock());
4175 for (int i = 0; i < (int)initializers.size(); ++i) {
4176 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4177 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4178
4179 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004180 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004181 initializer->traverse(this);
4182 }
4183 }
4184}
4185
4186// Process all the functions, while skipping initializers.
4187void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4188{
4189 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4190 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004191 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004192 node->traverse(this);
4193 }
4194}
4195
4196void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4197{
qining25262b32016-05-06 17:25:16 -04004198 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004199 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004200 currentFunction = functionMap[node->getName().c_str()];
4201 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004202 builder.setBuildPoint(functionBlock);
4203}
4204
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004205void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004206{
Rex Xufc618912015-09-09 16:42:49 +08004207 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004208
4209 glslang::TSampler sampler = {};
4210 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004211#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004212 bool f16ShadowCompare = false;
4213#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004214 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004215 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4216 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004217#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004218 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4219#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004220 }
4221
John Kessenich140f3df2015-06-26 16:58:36 -06004222 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4223 builder.clearAccessChain();
4224 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004225
John Kessenicha28f7a72019-08-06 07:00:58 -06004226#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004227 // Special case l-value operands
4228 bool lvalue = false;
4229 switch (node.getOp()) {
4230 case glslang::EOpImageAtomicAdd:
4231 case glslang::EOpImageAtomicMin:
4232 case glslang::EOpImageAtomicMax:
4233 case glslang::EOpImageAtomicAnd:
4234 case glslang::EOpImageAtomicOr:
4235 case glslang::EOpImageAtomicXor:
4236 case glslang::EOpImageAtomicExchange:
4237 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004238 case glslang::EOpImageAtomicLoad:
4239 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004240 if (i == 0)
4241 lvalue = true;
4242 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004243 case glslang::EOpSparseImageLoad:
4244 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4245 lvalue = true;
4246 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004247 case glslang::EOpSparseTexture:
4248 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4249 lvalue = true;
4250 break;
4251 case glslang::EOpSparseTextureClamp:
4252 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4253 lvalue = true;
4254 break;
4255 case glslang::EOpSparseTextureLod:
4256 case glslang::EOpSparseTextureOffset:
4257 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4258 lvalue = true;
4259 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004260 case glslang::EOpSparseTextureFetch:
4261 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4262 lvalue = true;
4263 break;
4264 case glslang::EOpSparseTextureFetchOffset:
4265 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4266 lvalue = true;
4267 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004268 case glslang::EOpSparseTextureLodOffset:
4269 case glslang::EOpSparseTextureGrad:
4270 case glslang::EOpSparseTextureOffsetClamp:
4271 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4272 lvalue = true;
4273 break;
4274 case glslang::EOpSparseTextureGradOffset:
4275 case glslang::EOpSparseTextureGradClamp:
4276 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4277 lvalue = true;
4278 break;
4279 case glslang::EOpSparseTextureGradOffsetClamp:
4280 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4281 lvalue = true;
4282 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004283 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004284 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4285 lvalue = true;
4286 break;
4287 case glslang::EOpSparseTextureGatherOffset:
4288 case glslang::EOpSparseTextureGatherOffsets:
4289 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4290 lvalue = true;
4291 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004292 case glslang::EOpSparseTextureGatherLod:
4293 if (i == 3)
4294 lvalue = true;
4295 break;
4296 case glslang::EOpSparseTextureGatherLodOffset:
4297 case glslang::EOpSparseTextureGatherLodOffsets:
4298 if (i == 4)
4299 lvalue = true;
4300 break;
Rex Xu129799a2017-07-05 17:23:28 +08004301 case glslang::EOpSparseImageLoadLod:
4302 if (i == 3)
4303 lvalue = true;
4304 break;
Chao Chen3a137962018-09-19 11:41:27 -07004305 case glslang::EOpImageSampleFootprintNV:
4306 if (i == 4)
4307 lvalue = true;
4308 break;
4309 case glslang::EOpImageSampleFootprintClampNV:
4310 case glslang::EOpImageSampleFootprintLodNV:
4311 if (i == 5)
4312 lvalue = true;
4313 break;
4314 case glslang::EOpImageSampleFootprintGradNV:
4315 if (i == 6)
4316 lvalue = true;
4317 break;
4318 case glslang::EOpImageSampleFootprintGradClampNV:
4319 if (i == 7)
4320 lvalue = true;
4321 break;
Rex Xufc618912015-09-09 16:42:49 +08004322 default:
4323 break;
4324 }
4325
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004326 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004327 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004328 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4329 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4330 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004331#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004332 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004333 }
4334}
4335
John Kessenichfc51d282015-08-19 13:34:18 -06004336void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004337{
John Kessenichfc51d282015-08-19 13:34:18 -06004338 builder.clearAccessChain();
4339 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004340 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004341}
John Kessenich140f3df2015-06-26 16:58:36 -06004342
John Kessenichfc51d282015-08-19 13:34:18 -06004343spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4344{
John Kesseniche485c7a2017-05-31 18:50:53 -06004345 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004346 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004347
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004348 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004349
John Kessenichfc51d282015-08-19 13:34:18 -06004350 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004351
John Kessenichf43c7392019-03-31 10:51:57 -06004352 const glslang::TType &imageType = node->getAsAggregate()
4353 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4354 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004355 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004356#ifdef GLSLANG_WEB
4357 const bool f16ShadowCompare = false;
4358#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004359 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004360 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4361 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004362#endif
4363
John Kessenichf43c7392019-03-31 10:51:57 -06004364 const auto signExtensionMask = [&]() {
4365 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4366 if (sampler.type == glslang::EbtUint)
4367 return spv::ImageOperandsZeroExtendMask;
4368 else if (sampler.type == glslang::EbtInt)
4369 return spv::ImageOperandsSignExtendMask;
4370 }
4371 return spv::ImageOperandsMaskNone;
4372 };
4373
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004374 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4375
John Kessenichfc51d282015-08-19 13:34:18 -06004376 std::vector<spv::Id> arguments;
4377 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004378 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004379 else
4380 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004381 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004382
4383 spv::Builder::TextureParameters params = { };
4384 params.sampler = arguments[0];
4385
Rex Xu04db3f52015-09-16 11:44:02 +08004386 glslang::TCrackedTextureOp cracked;
4387 node->crackTexture(sampler, cracked);
4388
amhagan05506bb2017-06-13 16:53:02 -04004389 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004390
John Kessenichfc51d282015-08-19 13:34:18 -06004391 // Check for queries
4392 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004393 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4394 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004395 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004396
John Kessenichfc51d282015-08-19 13:34:18 -06004397 switch (node->getOp()) {
4398 case glslang::EOpImageQuerySize:
4399 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004400 if (arguments.size() > 1) {
4401 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004402 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004403 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004404 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004405#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004406 case glslang::EOpImageQuerySamples:
4407 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004408 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004409 case glslang::EOpTextureQueryLod:
4410 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004411 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004412 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004413 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004414 case glslang::EOpSparseTexelsResident:
4415 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004416#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004417 default:
4418 assert(0);
4419 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004420 }
John Kessenich140f3df2015-06-26 16:58:36 -06004421 }
4422
LoopDawg4425f242018-02-18 11:40:01 -07004423 int components = node->getType().getVectorSize();
4424
4425 if (node->getOp() == glslang::EOpTextureFetch) {
4426 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4427 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4428 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4429 // here around e.g. which ones return scalars or other types.
4430 components = 4;
4431 }
4432
4433 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4434
4435 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4436
Rex Xufc618912015-09-09 16:42:49 +08004437 // Check for image functions other than queries
4438 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004439 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004440 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004441 spv::IdImmediate image = { true, *(opIt++) };
4442 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004443
4444 // Handle subpass operations
4445 // TODO: GLSL should change to have the "MS" only on the type rather than the
4446 // built-in function.
4447 if (cracked.subpass) {
4448 // add on the (0,0) coordinate
4449 spv::Id zero = builder.makeIntConstant(0);
4450 std::vector<spv::Id> comps;
4451 comps.push_back(zero);
4452 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004453 spv::IdImmediate coord = { true,
4454 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4455 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004456 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4457 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004458 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004459 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4460 }
4461 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004462 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004463 if (sampler.ms) {
4464 spv::IdImmediate imageOperand = { true, *(opIt++) };
4465 operands.push_back(imageOperand);
4466 }
John Kessenich6c292d32016-02-15 20:58:50 -07004467 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004468 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4469 builder.setPrecision(result, precision);
4470 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004471 }
4472
John Kessenich149afc32018-08-14 13:31:43 -06004473 spv::IdImmediate coord = { true, *(opIt++) };
4474 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004475 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004476 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004477 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004478 mask = mask | spv::ImageOperandsSampleMask;
4479 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004480 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004481 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4482 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004483 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004484 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004485 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4486 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004487 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004488 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004489 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4490 operands.push_back(imageOperands);
4491 }
4492 if (mask & spv::ImageOperandsSampleMask) {
4493 spv::IdImmediate imageOperand = { true, *opIt++ };
4494 operands.push_back(imageOperand);
4495 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004496 if (mask & spv::ImageOperandsLodMask) {
4497 spv::IdImmediate imageOperand = { true, *opIt++ };
4498 operands.push_back(imageOperand);
4499 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004500 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004501 spv::IdImmediate imageOperand = { true,
4502 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004503 operands.push_back(imageOperand);
4504 }
4505
John Kessenich149afc32018-08-14 13:31:43 -06004506 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004507 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004508
John Kessenich149afc32018-08-14 13:31:43 -06004509 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004510 builder.setPrecision(result[0], precision);
4511
4512 // If needed, add a conversion constructor to the proper size.
4513 if (components != node->getType().getVectorSize())
4514 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4515
4516 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004517 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004518
Jeff Bolz36831c92018-09-05 10:11:41 -05004519 // Push the texel value before the operands
Jeff Bolz36831c92018-09-05 10:11:41 -05004520 if (sampler.ms || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004521 spv::IdImmediate texel = { true, *(opIt + 1) };
4522 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004523 } else {
4524 spv::IdImmediate texel = { true, *opIt };
4525 operands.push_back(texel);
4526 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004527
4528 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4529 if (sampler.ms) {
4530 mask = mask | spv::ImageOperandsSampleMask;
4531 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004532 if (cracked.lod) {
4533 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4534 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4535 mask = mask | spv::ImageOperandsLodMask;
4536 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004537 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4538 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004539 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004540 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004541 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4542 operands.push_back(imageOperands);
4543 }
4544 if (mask & spv::ImageOperandsSampleMask) {
4545 spv::IdImmediate imageOperand = { true, *opIt++ };
4546 operands.push_back(imageOperand);
4547 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004548 if (mask & spv::ImageOperandsLodMask) {
4549 spv::IdImmediate imageOperand = { true, *opIt++ };
4550 operands.push_back(imageOperand);
4551 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004552 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004553 spv::IdImmediate imageOperand = { true,
4554 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004555 operands.push_back(imageOperand);
4556 }
4557
John Kessenich56bab042015-09-16 10:54:31 -06004558 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004559 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004560 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004561 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004562 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4563 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004564 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004565 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004566 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4567
Jeff Bolz36831c92018-09-05 10:11:41 -05004568 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004569 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004570 mask = mask | spv::ImageOperandsSampleMask;
4571 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004572 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004573 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4574 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4575
Jeff Bolz36831c92018-09-05 10:11:41 -05004576 mask = mask | spv::ImageOperandsLodMask;
4577 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004578 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4579 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004580 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004581 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004582 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004583 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004584 }
4585 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004586 spv::IdImmediate imageOperand = { true, *opIt++ };
4587 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004588 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004589 if (mask & spv::ImageOperandsLodMask) {
4590 spv::IdImmediate imageOperand = { true, *opIt++ };
4591 operands.push_back(imageOperand);
4592 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004593 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4594 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4595 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004596 }
4597
4598 // Create the return type that was a special structure
4599 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004600 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004601 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4602 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4603
4604 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4605
4606 // Decode the return type
4607 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4608 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004609 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004610 // Process image atomic operations
4611
4612 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4613 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004614 // For non-MS, the sample value should be 0
4615 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4616 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004617
Jeff Bolz36831c92018-09-05 10:11:41 -05004618 spv::Id resultTypeId;
4619 // imageAtomicStore has a void return type so base the pointer type on
4620 // the type of the value operand.
4621 if (node->getOp() == glslang::EOpImageAtomicStore) {
4622 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4623 } else {
4624 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4625 }
John Kessenich56bab042015-09-16 10:54:31 -06004626 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004627
4628 std::vector<spv::Id> operands;
4629 operands.push_back(pointer);
4630 for (; opIt != arguments.end(); ++opIt)
4631 operands.push_back(*opIt);
4632
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004633 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004634 }
4635 }
4636
John Kessenicha28f7a72019-08-06 07:00:58 -06004637#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004638 // Check for fragment mask functions other than queries
4639 if (cracked.fragMask) {
4640 assert(sampler.ms);
4641
4642 auto opIt = arguments.begin();
4643 std::vector<spv::Id> operands;
4644
4645 // Extract the image if necessary
4646 if (builder.isSampledImage(params.sampler))
4647 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4648
4649 operands.push_back(params.sampler);
4650 ++opIt;
4651
4652 if (sampler.isSubpass()) {
4653 // add on the (0,0) coordinate
4654 spv::Id zero = builder.makeIntConstant(0);
4655 std::vector<spv::Id> comps;
4656 comps.push_back(zero);
4657 comps.push_back(zero);
4658 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4659 }
4660
4661 for (; opIt != arguments.end(); ++opIt)
4662 operands.push_back(*opIt);
4663
4664 spv::Op fragMaskOp = spv::OpNop;
4665 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4666 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4667 else if (node->getOp() == glslang::EOpFragmentFetch)
4668 fragMaskOp = spv::OpFragmentFetchAMD;
4669
4670 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4671 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4672 return builder.createOp(fragMaskOp, resultType(), operands);
4673 }
4674#endif
4675
Rex Xufc618912015-09-09 16:42:49 +08004676 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004677 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004678 bool imageFootprint = node->isImageFootprint();
Rex Xu71519fe2015-11-11 15:35:47 +08004679 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4680
John Kessenichfc51d282015-08-19 13:34:18 -06004681 // check for bias argument
4682 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004683 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004684 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004685 if (cracked.gather)
4686 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004687
4688 if (f16ShadowCompare)
4689 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004690 if (cracked.offset)
4691 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004692 else if (cracked.offsets)
4693 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004694 if (cracked.grad)
4695 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004696 if (cracked.lodClamp)
4697 ++nonBiasArgCount;
4698 if (sparse)
4699 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004700 if (imageFootprint)
4701 //Following three extra arguments
4702 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4703 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004704 if ((int)arguments.size() > nonBiasArgCount)
4705 bias = true;
4706 }
4707
John Kessenicha5c33d62016-06-02 23:45:21 -06004708 // See if the sampler param should really be just the SPV image part
4709 if (cracked.fetch) {
4710 // a fetch needs to have the image extracted first
4711 if (builder.isSampledImage(params.sampler))
4712 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4713 }
4714
John Kessenicha28f7a72019-08-06 07:00:58 -06004715#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004716 if (cracked.gather) {
4717 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4718 if (bias || cracked.lod ||
4719 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4720 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004721 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004722 }
4723 }
4724#endif
4725
John Kessenichfc51d282015-08-19 13:34:18 -06004726 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004727
John Kessenichfc51d282015-08-19 13:34:18 -06004728 params.coords = arguments[1];
4729 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004730 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004731
4732 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004733 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004734 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004735 ++extraArgs;
4736 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004737 params.Dref = arguments[2];
4738 ++extraArgs;
4739 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004740 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004741 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004742 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004743 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004744 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004745 dRefComp = builder.getNumComponents(params.coords) - 1;
4746 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004747 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4748 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004749
4750 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004751 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004752 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004753 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004754 } else if (glslangIntermediate->getStage() != EShLangFragment
John Kessenicha28f7a72019-08-06 07:00:58 -06004755#ifndef GLSLANG_WEB
Chao Chenbeae2252018-09-19 11:40:45 -07004756 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4757 && !(glslangIntermediate->getStage() == EShLangCompute &&
4758 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4759#endif
4760 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004761 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4762 noImplicitLod = true;
4763 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004764
4765 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004766 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004767 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004768 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004769 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004770
4771 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004772 if (cracked.grad) {
4773 params.gradX = arguments[2 + extraArgs];
4774 params.gradY = arguments[3 + extraArgs];
4775 extraArgs += 2;
4776 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004777
4778 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004779 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004780 params.offset = arguments[2 + extraArgs];
4781 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004782 } else if (cracked.offsets) {
4783 params.offsets = arguments[2 + extraArgs];
4784 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004785 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004786
4787 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004788 if (cracked.lodClamp) {
4789 params.lodClamp = arguments[2 + extraArgs];
4790 ++extraArgs;
4791 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004792 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004793 if (sparse) {
4794 params.texelOut = arguments[2 + extraArgs];
4795 ++extraArgs;
4796 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004797
John Kessenich76d4dfc2016-06-16 12:43:23 -06004798 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004799 if (cracked.gather && ! sampler.shadow) {
4800 // default component is 0, if missing, otherwise an argument
4801 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004802 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004803 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004804 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004805 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004806 }
John Kessenicha28f7a72019-08-06 07:00:58 -06004807#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004808 spv::Id resultStruct = spv::NoResult;
4809 if (imageFootprint) {
4810 //Following three extra arguments
4811 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4812 params.granularity = arguments[2 + extraArgs];
4813 params.coarse = arguments[3 + extraArgs];
4814 resultStruct = arguments[4 + extraArgs];
4815 extraArgs += 3;
4816 }
4817#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004818 // bias
4819 if (bias) {
4820 params.bias = arguments[2 + extraArgs];
4821 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004822 }
John Kessenichfc51d282015-08-19 13:34:18 -06004823
John Kessenicha28f7a72019-08-06 07:00:58 -06004824#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004825 if (imageFootprint) {
4826 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4827 builder.addCapability(spv::CapabilityImageFootprintNV);
4828
4829
4830 //resultStructType(OpenGL type) contains 5 elements:
4831 //struct gl_TextureFootprint2DNV {
4832 // uvec2 anchor;
4833 // uvec2 offset;
4834 // uvec2 mask;
4835 // uint lod;
4836 // uint granularity;
4837 //};
4838 //or
4839 //struct gl_TextureFootprint3DNV {
4840 // uvec3 anchor;
4841 // uvec3 offset;
4842 // uvec2 mask;
4843 // uint lod;
4844 // uint granularity;
4845 //};
4846 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4847 assert(builder.isStructType(resultStructType));
4848
4849 //resType (SPIR-V type) contains 6 elements:
4850 //Member 0 must be a Boolean type scalar(LOD),
4851 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4852 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4853 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4854 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4855 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4856 std::vector<spv::Id> members;
4857 members.push_back(resultType());
4858 for (int i = 0; i < 5; i++) {
4859 members.push_back(builder.getContainedTypeId(resultStructType, i));
4860 }
4861 spv::Id resType = builder.makeStructType(members, "ResType");
4862
4863 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004864 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4865 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004866
4867 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4868 for (int i = 0; i < 5; i++) {
4869 builder.clearAccessChain();
4870 builder.setAccessChainLValue(resultStruct);
4871
4872 //Accessing to a struct we created, no coherent flag is set
4873 spv::Builder::AccessChain::CoherentFlags flags;
4874 flags.clear();
4875
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004876 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004877 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4878 }
4879 return builder.createCompositeExtract(res, resultType(), 0);
4880 }
4881#endif
4882
John Kessenich65336482016-06-16 14:06:26 -06004883 // projective component (might not to move)
4884 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4885 // are divided by the last component of P."
4886 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4887 // unused components will appear after all used components."
4888 if (cracked.proj) {
4889 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4890 int projTargetComp;
4891 switch (sampler.dim) {
4892 case glslang::Esd1D: projTargetComp = 1; break;
4893 case glslang::Esd2D: projTargetComp = 2; break;
4894 case glslang::EsdRect: projTargetComp = 2; break;
4895 default: projTargetComp = projSourceComp; break;
4896 }
4897 // copy the projective coordinate if we have to
4898 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004899 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004900 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4901 projSourceComp);
4902 params.coords = builder.createCompositeInsert(projComp, params.coords,
4903 builder.getTypeId(params.coords), projTargetComp);
4904 }
4905 }
4906
Jeff Bolz36831c92018-09-05 10:11:41 -05004907 // nonprivate
4908 if (imageType.getQualifier().nonprivate) {
4909 params.nonprivate = true;
4910 }
4911
4912 // volatile
4913 if (imageType.getQualifier().volatil) {
4914 params.volatil = true;
4915 }
4916
St0fFa1184dd2018-04-09 21:08:14 +02004917 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004918 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4919 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004920 );
LoopDawg4425f242018-02-18 11:40:01 -07004921
4922 if (components != node->getType().getVectorSize())
4923 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4924
4925 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004926}
4927
4928spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4929{
4930 // Grab the function's pointer from the previously created function
4931 spv::Function* function = functionMap[node->getName().c_str()];
4932 if (! function)
4933 return 0;
4934
4935 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4936 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4937
4938 // See comments in makeFunctions() for details about the semantics for parameter passing.
4939 //
4940 // These imply we need a four step process:
4941 // 1. Evaluate the arguments
4942 // 2. Allocate and make copies of in, out, and inout arguments
4943 // 3. Make the call
4944 // 4. Copy back the results
4945
John Kessenichd3ed90b2018-05-04 11:43:03 -06004946 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004947 std::vector<spv::Builder::AccessChain> lValues;
4948 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004949 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004950 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004951 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004952 // build l-value
4953 builder.clearAccessChain();
4954 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004955 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004956 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004957 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004958 // save l-value
4959 lValues.push_back(builder.getAccessChain());
4960 } else {
4961 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004962 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004963 }
4964 }
4965
4966 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4967 // copy the original into that space.
4968 //
4969 // Also, build up the list of actual arguments to pass in for the call
4970 int lValueCount = 0;
4971 int rValueCount = 0;
4972 std::vector<spv::Id> spvArgs;
4973 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4974 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004975 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004976 builder.setAccessChain(lValues[lValueCount]);
4977 arg = builder.accessChainGetLValue();
4978 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004979 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004980 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004981 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004982 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4983 // need to copy the input into output space
4984 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004985 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004986 builder.clearAccessChain();
4987 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004988 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004989 }
4990 ++lValueCount;
4991 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004992 // process r-value, which involves a copy for a type mismatch
4993 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4994 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4995 builder.clearAccessChain();
4996 builder.setAccessChainLValue(argCopy);
4997 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4998 arg = builder.createLoad(argCopy);
4999 } else
5000 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005001 ++rValueCount;
5002 }
5003 spvArgs.push_back(arg);
5004 }
5005
5006 // 3. Make the call.
5007 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005008 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005009
5010 // 4. Copy back out an "out" arguments.
5011 lValueCount = 0;
5012 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005013 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005014 ++lValueCount;
5015 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005016 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5017 spv::Id copy = builder.createLoad(spvArgs[a]);
5018 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005019 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005020 }
5021 ++lValueCount;
5022 }
5023 }
5024
5025 return result;
5026}
5027
5028// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005029spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005030 spv::Id typeId, spv::Id left, spv::Id right,
5031 glslang::TBasicType typeProxy, bool reduceComparison)
5032{
John Kessenich66011cb2018-03-06 16:12:04 -07005033 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5034 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005035 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005036
5037 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005038 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005039 bool comparison = false;
5040
5041 switch (op) {
5042 case glslang::EOpAdd:
5043 case glslang::EOpAddAssign:
5044 if (isFloat)
5045 binOp = spv::OpFAdd;
5046 else
5047 binOp = spv::OpIAdd;
5048 break;
5049 case glslang::EOpSub:
5050 case glslang::EOpSubAssign:
5051 if (isFloat)
5052 binOp = spv::OpFSub;
5053 else
5054 binOp = spv::OpISub;
5055 break;
5056 case glslang::EOpMul:
5057 case glslang::EOpMulAssign:
5058 if (isFloat)
5059 binOp = spv::OpFMul;
5060 else
5061 binOp = spv::OpIMul;
5062 break;
5063 case glslang::EOpVectorTimesScalar:
5064 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005065 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005066 if (builder.isVector(right))
5067 std::swap(left, right);
5068 assert(builder.isScalar(right));
5069 needMatchingVectors = false;
5070 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005071 } else if (isFloat)
5072 binOp = spv::OpFMul;
5073 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005074 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005075 break;
5076 case glslang::EOpVectorTimesMatrix:
5077 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005078 binOp = spv::OpVectorTimesMatrix;
5079 break;
5080 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005081 binOp = spv::OpMatrixTimesVector;
5082 break;
5083 case glslang::EOpMatrixTimesScalar:
5084 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005085 binOp = spv::OpMatrixTimesScalar;
5086 break;
5087 case glslang::EOpMatrixTimesMatrix:
5088 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005089 binOp = spv::OpMatrixTimesMatrix;
5090 break;
5091 case glslang::EOpOuterProduct:
5092 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005093 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005094 break;
5095
5096 case glslang::EOpDiv:
5097 case glslang::EOpDivAssign:
5098 if (isFloat)
5099 binOp = spv::OpFDiv;
5100 else if (isUnsigned)
5101 binOp = spv::OpUDiv;
5102 else
5103 binOp = spv::OpSDiv;
5104 break;
5105 case glslang::EOpMod:
5106 case glslang::EOpModAssign:
5107 if (isFloat)
5108 binOp = spv::OpFMod;
5109 else if (isUnsigned)
5110 binOp = spv::OpUMod;
5111 else
5112 binOp = spv::OpSMod;
5113 break;
5114 case glslang::EOpRightShift:
5115 case glslang::EOpRightShiftAssign:
5116 if (isUnsigned)
5117 binOp = spv::OpShiftRightLogical;
5118 else
5119 binOp = spv::OpShiftRightArithmetic;
5120 break;
5121 case glslang::EOpLeftShift:
5122 case glslang::EOpLeftShiftAssign:
5123 binOp = spv::OpShiftLeftLogical;
5124 break;
5125 case glslang::EOpAnd:
5126 case glslang::EOpAndAssign:
5127 binOp = spv::OpBitwiseAnd;
5128 break;
5129 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005130 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005131 binOp = spv::OpLogicalAnd;
5132 break;
5133 case glslang::EOpInclusiveOr:
5134 case glslang::EOpInclusiveOrAssign:
5135 binOp = spv::OpBitwiseOr;
5136 break;
5137 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005138 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005139 binOp = spv::OpLogicalOr;
5140 break;
5141 case glslang::EOpExclusiveOr:
5142 case glslang::EOpExclusiveOrAssign:
5143 binOp = spv::OpBitwiseXor;
5144 break;
5145 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005146 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005147 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005148 break;
5149
5150 case glslang::EOpLessThan:
5151 case glslang::EOpGreaterThan:
5152 case glslang::EOpLessThanEqual:
5153 case glslang::EOpGreaterThanEqual:
5154 case glslang::EOpEqual:
5155 case glslang::EOpNotEqual:
5156 case glslang::EOpVectorEqual:
5157 case glslang::EOpVectorNotEqual:
5158 comparison = true;
5159 break;
5160 default:
5161 break;
5162 }
5163
John Kessenich7c1aa102015-10-15 13:29:11 -06005164 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005165 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005166 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005167 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5168 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005169 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005170
5171 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005172 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005173 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005174
qining25262b32016-05-06 17:25:16 -04005175 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005176 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005177 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005178 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005179 }
5180
5181 if (! comparison)
5182 return 0;
5183
John Kessenich7c1aa102015-10-15 13:29:11 -06005184 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005185
John Kessenich4583b612016-08-07 19:14:22 -06005186 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005187 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5188 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005189 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005190 return result;
5191 }
John Kessenich140f3df2015-06-26 16:58:36 -06005192
5193 switch (op) {
5194 case glslang::EOpLessThan:
5195 if (isFloat)
5196 binOp = spv::OpFOrdLessThan;
5197 else if (isUnsigned)
5198 binOp = spv::OpULessThan;
5199 else
5200 binOp = spv::OpSLessThan;
5201 break;
5202 case glslang::EOpGreaterThan:
5203 if (isFloat)
5204 binOp = spv::OpFOrdGreaterThan;
5205 else if (isUnsigned)
5206 binOp = spv::OpUGreaterThan;
5207 else
5208 binOp = spv::OpSGreaterThan;
5209 break;
5210 case glslang::EOpLessThanEqual:
5211 if (isFloat)
5212 binOp = spv::OpFOrdLessThanEqual;
5213 else if (isUnsigned)
5214 binOp = spv::OpULessThanEqual;
5215 else
5216 binOp = spv::OpSLessThanEqual;
5217 break;
5218 case glslang::EOpGreaterThanEqual:
5219 if (isFloat)
5220 binOp = spv::OpFOrdGreaterThanEqual;
5221 else if (isUnsigned)
5222 binOp = spv::OpUGreaterThanEqual;
5223 else
5224 binOp = spv::OpSGreaterThanEqual;
5225 break;
5226 case glslang::EOpEqual:
5227 case glslang::EOpVectorEqual:
5228 if (isFloat)
5229 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005230 else if (isBool)
5231 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 else
5233 binOp = spv::OpIEqual;
5234 break;
5235 case glslang::EOpNotEqual:
5236 case glslang::EOpVectorNotEqual:
5237 if (isFloat)
5238 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005239 else if (isBool)
5240 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005241 else
5242 binOp = spv::OpINotEqual;
5243 break;
5244 default:
5245 break;
5246 }
5247
qining25262b32016-05-06 17:25:16 -04005248 if (binOp != spv::OpNop) {
5249 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005250 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005251 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005252 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005253 }
John Kessenich140f3df2015-06-26 16:58:36 -06005254
5255 return 0;
5256}
5257
John Kessenich04bb8a02015-12-12 12:28:14 -07005258//
5259// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5260// These can be any of:
5261//
5262// matrix * scalar
5263// scalar * matrix
5264// matrix * matrix linear algebraic
5265// matrix * vector
5266// vector * matrix
5267// matrix * matrix componentwise
5268// matrix op matrix op in {+, -, /}
5269// matrix op scalar op in {+, -, /}
5270// scalar op matrix op in {+, -, /}
5271//
John Kessenichead86222018-03-28 18:01:20 -06005272spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5273 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005274{
5275 bool firstClass = true;
5276
5277 // First, handle first-class matrix operations (* and matrix/scalar)
5278 switch (op) {
5279 case spv::OpFDiv:
5280 if (builder.isMatrix(left) && builder.isScalar(right)) {
5281 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005282 spv::Id resultType = builder.getTypeId(right);
5283 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005284 op = spv::OpMatrixTimesScalar;
5285 } else
5286 firstClass = false;
5287 break;
5288 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005289 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005290 std::swap(left, right);
5291 assert(builder.isScalar(right));
5292 break;
5293 case spv::OpVectorTimesMatrix:
5294 assert(builder.isVector(left));
5295 assert(builder.isMatrix(right));
5296 break;
5297 case spv::OpMatrixTimesVector:
5298 assert(builder.isMatrix(left));
5299 assert(builder.isVector(right));
5300 break;
5301 case spv::OpMatrixTimesMatrix:
5302 assert(builder.isMatrix(left));
5303 assert(builder.isMatrix(right));
5304 break;
5305 default:
5306 firstClass = false;
5307 break;
5308 }
5309
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005310 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5311 firstClass = true;
5312
qining25262b32016-05-06 17:25:16 -04005313 if (firstClass) {
5314 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005315 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005316 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005317 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005318 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005319
LoopDawg592860c2016-06-09 08:57:35 -06005320 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005321 // The result type of all of them is the same type as the (a) matrix operand.
5322 // The algorithm is to:
5323 // - break the matrix(es) into vectors
5324 // - smear any scalar to a vector
5325 // - do vector operations
5326 // - make a matrix out the vector results
5327 switch (op) {
5328 case spv::OpFAdd:
5329 case spv::OpFSub:
5330 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005331 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005332 case spv::OpFMul:
5333 {
5334 // one time set up...
5335 bool leftMat = builder.isMatrix(left);
5336 bool rightMat = builder.isMatrix(right);
5337 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5338 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5339 spv::Id scalarType = builder.getScalarTypeId(typeId);
5340 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5341 std::vector<spv::Id> results;
5342 spv::Id smearVec = spv::NoResult;
5343 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005344 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005345 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005346 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005347
5348 // do each vector op
5349 for (unsigned int c = 0; c < numCols; ++c) {
5350 std::vector<unsigned int> indexes;
5351 indexes.push_back(c);
5352 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5353 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005354 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005355 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005356 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005357 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005358 }
5359
5360 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005361 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005362 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005363 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005364 }
5365 default:
5366 assert(0);
5367 return spv::NoResult;
5368 }
5369}
5370
John Kessenichead86222018-03-28 18:01:20 -06005371spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005372 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005373{
5374 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005375 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005376 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005377 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5378 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005379
5380 switch (op) {
5381 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005382 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005383 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005384 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005385 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005386 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005387 unaryOp = spv::OpSNegate;
5388 break;
5389
5390 case glslang::EOpLogicalNot:
5391 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005392 unaryOp = spv::OpLogicalNot;
5393 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005394 case glslang::EOpBitwiseNot:
5395 unaryOp = spv::OpNot;
5396 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005397
John Kessenich140f3df2015-06-26 16:58:36 -06005398 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005399 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005400 break;
5401 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005402 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005403 break;
5404 case glslang::EOpTranspose:
5405 unaryOp = spv::OpTranspose;
5406 break;
5407
5408 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005409 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005410 break;
5411 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005412 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005413 break;
5414 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005415 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005416 break;
5417 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005418 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005419 break;
5420 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005421 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005422 break;
5423 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005424 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005425 break;
5426 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005427 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005428 break;
5429 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005430 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005431 break;
5432
5433 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005434 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005435 break;
5436 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005437 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005438 break;
5439 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005440 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005441 break;
5442 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005443 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005444 break;
5445 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005446 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005447 break;
5448 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005449 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005450 break;
5451
5452 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005453 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005454 break;
5455 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005456 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005457 break;
5458
5459 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005460 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005461 break;
5462 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005463 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005464 break;
5465 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005466 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005467 break;
5468 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005469 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005470 break;
5471 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005472 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005473 break;
5474 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005475 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005476 break;
5477
5478 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005479 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005480 break;
5481 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005482 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005483 break;
5484 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005485 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005486 break;
5487 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005488 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005489 break;
5490 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005491 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005492 break;
5493 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005494 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005495 break;
5496
5497 case glslang::EOpIsNan:
5498 unaryOp = spv::OpIsNan;
5499 break;
5500 case glslang::EOpIsInf:
5501 unaryOp = spv::OpIsInf;
5502 break;
LoopDawg592860c2016-06-09 08:57:35 -06005503 case glslang::EOpIsFinite:
5504 unaryOp = spv::OpIsFinite;
5505 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005506
Rex Xucbc426e2015-12-15 16:03:10 +08005507 case glslang::EOpFloatBitsToInt:
5508 case glslang::EOpFloatBitsToUint:
5509 case glslang::EOpIntBitsToFloat:
5510 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005511 case glslang::EOpDoubleBitsToInt64:
5512 case glslang::EOpDoubleBitsToUint64:
5513 case glslang::EOpInt64BitsToDouble:
5514 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005515 case glslang::EOpFloat16BitsToInt16:
5516 case glslang::EOpFloat16BitsToUint16:
5517 case glslang::EOpInt16BitsToFloat16:
5518 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005519 unaryOp = spv::OpBitcast;
5520 break;
5521
John Kessenich140f3df2015-06-26 16:58:36 -06005522 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005523 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005524 break;
5525 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005526 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005527 break;
5528 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005529 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005530 break;
5531 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005532 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005533 break;
5534 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005535 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005536 break;
5537 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005538 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005539 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005540 case glslang::EOpPackSnorm4x8:
5541 libCall = spv::GLSLstd450PackSnorm4x8;
5542 break;
5543 case glslang::EOpUnpackSnorm4x8:
5544 libCall = spv::GLSLstd450UnpackSnorm4x8;
5545 break;
5546 case glslang::EOpPackUnorm4x8:
5547 libCall = spv::GLSLstd450PackUnorm4x8;
5548 break;
5549 case glslang::EOpUnpackUnorm4x8:
5550 libCall = spv::GLSLstd450UnpackUnorm4x8;
5551 break;
5552 case glslang::EOpPackDouble2x32:
5553 libCall = spv::GLSLstd450PackDouble2x32;
5554 break;
5555 case glslang::EOpUnpackDouble2x32:
5556 libCall = spv::GLSLstd450UnpackDouble2x32;
5557 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005558
Rex Xu8ff43de2016-04-22 16:51:45 +08005559 case glslang::EOpPackInt2x32:
5560 case glslang::EOpUnpackInt2x32:
5561 case glslang::EOpPackUint2x32:
5562 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005563 case glslang::EOpPack16:
5564 case glslang::EOpPack32:
5565 case glslang::EOpPack64:
5566 case glslang::EOpUnpack32:
5567 case glslang::EOpUnpack16:
5568 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005569 case glslang::EOpPackInt2x16:
5570 case glslang::EOpUnpackInt2x16:
5571 case glslang::EOpPackUint2x16:
5572 case glslang::EOpUnpackUint2x16:
5573 case glslang::EOpPackInt4x16:
5574 case glslang::EOpUnpackInt4x16:
5575 case glslang::EOpPackUint4x16:
5576 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005577 case glslang::EOpPackFloat2x16:
5578 case glslang::EOpUnpackFloat2x16:
5579 unaryOp = spv::OpBitcast;
5580 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005581
John Kessenich140f3df2015-06-26 16:58:36 -06005582 case glslang::EOpDPdx:
5583 unaryOp = spv::OpDPdx;
5584 break;
5585 case glslang::EOpDPdy:
5586 unaryOp = spv::OpDPdy;
5587 break;
5588 case glslang::EOpFwidth:
5589 unaryOp = spv::OpFwidth;
5590 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005591
John Kessenich140f3df2015-06-26 16:58:36 -06005592 case glslang::EOpAny:
5593 unaryOp = spv::OpAny;
5594 break;
5595 case glslang::EOpAll:
5596 unaryOp = spv::OpAll;
5597 break;
5598
5599 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005600 if (isFloat)
5601 libCall = spv::GLSLstd450FAbs;
5602 else
5603 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005604 break;
5605 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005606 if (isFloat)
5607 libCall = spv::GLSLstd450FSign;
5608 else
5609 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005610 break;
5611
John Kessenicha28f7a72019-08-06 07:00:58 -06005612#ifndef GLSLANG_WEB
5613 case glslang::EOpDPdxFine:
5614 unaryOp = spv::OpDPdxFine;
5615 break;
5616 case glslang::EOpDPdyFine:
5617 unaryOp = spv::OpDPdyFine;
5618 break;
5619 case glslang::EOpFwidthFine:
5620 unaryOp = spv::OpFwidthFine;
5621 break;
5622 case glslang::EOpDPdxCoarse:
5623 unaryOp = spv::OpDPdxCoarse;
5624 break;
5625 case glslang::EOpDPdyCoarse:
5626 unaryOp = spv::OpDPdyCoarse;
5627 break;
5628 case glslang::EOpFwidthCoarse:
5629 unaryOp = spv::OpFwidthCoarse;
5630 break;
5631 case glslang::EOpInterpolateAtCentroid:
5632 if (typeProxy == glslang::EbtFloat16)
5633 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5634 libCall = spv::GLSLstd450InterpolateAtCentroid;
5635 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005636 case glslang::EOpAtomicCounterIncrement:
5637 case glslang::EOpAtomicCounterDecrement:
5638 case glslang::EOpAtomicCounter:
5639 {
5640 // Handle all of the atomics in one place, in createAtomicOperation()
5641 std::vector<spv::Id> operands;
5642 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005643 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005644 }
5645
John Kessenichfc51d282015-08-19 13:34:18 -06005646 case glslang::EOpBitFieldReverse:
5647 unaryOp = spv::OpBitReverse;
5648 break;
5649 case glslang::EOpBitCount:
5650 unaryOp = spv::OpBitCount;
5651 break;
5652 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005653 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005654 break;
5655 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005656 if (isUnsigned)
5657 libCall = spv::GLSLstd450FindUMsb;
5658 else
5659 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005660 break;
5661
Rex Xu574ab042016-04-14 16:53:07 +08005662 case glslang::EOpBallot:
5663 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005664 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005665 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005666 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005667 case glslang::EOpMinInvocations:
5668 case glslang::EOpMaxInvocations:
5669 case glslang::EOpAddInvocations:
5670 case glslang::EOpMinInvocationsNonUniform:
5671 case glslang::EOpMaxInvocationsNonUniform:
5672 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005673 case glslang::EOpMinInvocationsInclusiveScan:
5674 case glslang::EOpMaxInvocationsInclusiveScan:
5675 case glslang::EOpAddInvocationsInclusiveScan:
5676 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5677 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5678 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5679 case glslang::EOpMinInvocationsExclusiveScan:
5680 case glslang::EOpMaxInvocationsExclusiveScan:
5681 case glslang::EOpAddInvocationsExclusiveScan:
5682 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5683 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5684 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005685 {
5686 std::vector<spv::Id> operands;
5687 operands.push_back(operand);
5688 return createInvocationsOperation(op, typeId, operands, typeProxy);
5689 }
John Kessenich66011cb2018-03-06 16:12:04 -07005690 case glslang::EOpSubgroupAll:
5691 case glslang::EOpSubgroupAny:
5692 case glslang::EOpSubgroupAllEqual:
5693 case glslang::EOpSubgroupBroadcastFirst:
5694 case glslang::EOpSubgroupBallot:
5695 case glslang::EOpSubgroupInverseBallot:
5696 case glslang::EOpSubgroupBallotBitCount:
5697 case glslang::EOpSubgroupBallotInclusiveBitCount:
5698 case glslang::EOpSubgroupBallotExclusiveBitCount:
5699 case glslang::EOpSubgroupBallotFindLSB:
5700 case glslang::EOpSubgroupBallotFindMSB:
5701 case glslang::EOpSubgroupAdd:
5702 case glslang::EOpSubgroupMul:
5703 case glslang::EOpSubgroupMin:
5704 case glslang::EOpSubgroupMax:
5705 case glslang::EOpSubgroupAnd:
5706 case glslang::EOpSubgroupOr:
5707 case glslang::EOpSubgroupXor:
5708 case glslang::EOpSubgroupInclusiveAdd:
5709 case glslang::EOpSubgroupInclusiveMul:
5710 case glslang::EOpSubgroupInclusiveMin:
5711 case glslang::EOpSubgroupInclusiveMax:
5712 case glslang::EOpSubgroupInclusiveAnd:
5713 case glslang::EOpSubgroupInclusiveOr:
5714 case glslang::EOpSubgroupInclusiveXor:
5715 case glslang::EOpSubgroupExclusiveAdd:
5716 case glslang::EOpSubgroupExclusiveMul:
5717 case glslang::EOpSubgroupExclusiveMin:
5718 case glslang::EOpSubgroupExclusiveMax:
5719 case glslang::EOpSubgroupExclusiveAnd:
5720 case glslang::EOpSubgroupExclusiveOr:
5721 case glslang::EOpSubgroupExclusiveXor:
5722 case glslang::EOpSubgroupQuadSwapHorizontal:
5723 case glslang::EOpSubgroupQuadSwapVertical:
5724 case glslang::EOpSubgroupQuadSwapDiagonal: {
5725 std::vector<spv::Id> operands;
5726 operands.push_back(operand);
5727 return createSubgroupOperation(op, typeId, operands, typeProxy);
5728 }
Rex Xu9d93a232016-05-05 12:30:44 +08005729 case glslang::EOpMbcnt:
5730 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5731 libCall = spv::MbcntAMD;
5732 break;
5733
5734 case glslang::EOpCubeFaceIndex:
5735 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5736 libCall = spv::CubeFaceIndexAMD;
5737 break;
5738
5739 case glslang::EOpCubeFaceCoord:
5740 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5741 libCall = spv::CubeFaceCoordAMD;
5742 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005743 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005744 unaryOp = spv::OpGroupNonUniformPartitionNV;
5745 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005746 case glslang::EOpConstructReference:
5747 unaryOp = spv::OpBitcast;
5748 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005749#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005750
5751 case glslang::EOpCopyObject:
5752 unaryOp = spv::OpCopyObject;
5753 break;
5754
John Kessenich140f3df2015-06-26 16:58:36 -06005755 default:
5756 return 0;
5757 }
5758
5759 spv::Id id;
5760 if (libCall >= 0) {
5761 std::vector<spv::Id> args;
5762 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005763 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005764 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005765 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005766 }
John Kessenich140f3df2015-06-26 16:58:36 -06005767
John Kessenichead86222018-03-28 18:01:20 -06005768 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005769 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005770 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005771}
5772
John Kessenich7a53f762016-01-20 11:19:27 -07005773// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005774spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5775 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005776{
5777 // Handle unary operations vector by vector.
5778 // The result type is the same type as the original type.
5779 // The algorithm is to:
5780 // - break the matrix into vectors
5781 // - apply the operation to each vector
5782 // - make a matrix out the vector results
5783
5784 // get the types sorted out
5785 int numCols = builder.getNumColumns(operand);
5786 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005787 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5788 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005789 std::vector<spv::Id> results;
5790
5791 // do each vector op
5792 for (int c = 0; c < numCols; ++c) {
5793 std::vector<unsigned int> indexes;
5794 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005795 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5796 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005797 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005798 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005799 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005800 }
5801
5802 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005803 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005804 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005805 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005806}
5807
John Kessenichad7645f2018-06-04 19:11:25 -06005808// For converting integers where both the bitwidth and the signedness could
5809// change, but only do the width change here. The caller is still responsible
5810// for the signedness conversion.
5811spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005812{
John Kessenichad7645f2018-06-04 19:11:25 -06005813 // Get the result type width, based on the type to convert to.
5814 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005815 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005816 case glslang::EOpConvInt16ToUint8:
5817 case glslang::EOpConvIntToUint8:
5818 case glslang::EOpConvInt64ToUint8:
5819 case glslang::EOpConvUint16ToInt8:
5820 case glslang::EOpConvUintToInt8:
5821 case glslang::EOpConvUint64ToInt8:
5822 width = 8;
5823 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005824 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005825 case glslang::EOpConvIntToUint16:
5826 case glslang::EOpConvInt64ToUint16:
5827 case glslang::EOpConvUint8ToInt16:
5828 case glslang::EOpConvUintToInt16:
5829 case glslang::EOpConvUint64ToInt16:
5830 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005831 break;
5832 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005833 case glslang::EOpConvInt16ToUint:
5834 case glslang::EOpConvInt64ToUint:
5835 case glslang::EOpConvUint8ToInt:
5836 case glslang::EOpConvUint16ToInt:
5837 case glslang::EOpConvUint64ToInt:
5838 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005839 break;
5840 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005841 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005842 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005843 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005844 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005845 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005846 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005847 break;
5848
5849 default:
5850 assert(false && "Default missing");
5851 break;
5852 }
5853
John Kessenichad7645f2018-06-04 19:11:25 -06005854 // Get the conversion operation and result type,
5855 // based on the target width, but the source type.
5856 spv::Id type = spv::NoType;
5857 spv::Op convOp = spv::OpNop;
5858 switch(op) {
5859 case glslang::EOpConvInt8ToUint16:
5860 case glslang::EOpConvInt8ToUint:
5861 case glslang::EOpConvInt8ToUint64:
5862 case glslang::EOpConvInt16ToUint8:
5863 case glslang::EOpConvInt16ToUint:
5864 case glslang::EOpConvInt16ToUint64:
5865 case glslang::EOpConvIntToUint8:
5866 case glslang::EOpConvIntToUint16:
5867 case glslang::EOpConvIntToUint64:
5868 case glslang::EOpConvInt64ToUint8:
5869 case glslang::EOpConvInt64ToUint16:
5870 case glslang::EOpConvInt64ToUint:
5871 convOp = spv::OpSConvert;
5872 type = builder.makeIntType(width);
5873 break;
5874 default:
5875 convOp = spv::OpUConvert;
5876 type = builder.makeUintType(width);
5877 break;
5878 }
5879
John Kessenich66011cb2018-03-06 16:12:04 -07005880 if (vectorSize > 0)
5881 type = builder.makeVectorType(type, vectorSize);
5882
John Kessenichad7645f2018-06-04 19:11:25 -06005883 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005884}
5885
John Kessenichead86222018-03-28 18:01:20 -06005886spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5887 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005888{
5889 spv::Op convOp = spv::OpNop;
5890 spv::Id zero = 0;
5891 spv::Id one = 0;
5892
5893 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5894
5895 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005896 case glslang::EOpConvInt8ToBool:
5897 case glslang::EOpConvUint8ToBool:
5898 zero = builder.makeUint8Constant(0);
5899 zero = makeSmearedConstant(zero, vectorSize);
5900 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005901 case glslang::EOpConvInt16ToBool:
5902 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005903 zero = builder.makeUint16Constant(0);
5904 zero = makeSmearedConstant(zero, vectorSize);
5905 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5906 case glslang::EOpConvIntToBool:
5907 case glslang::EOpConvUintToBool:
5908 zero = builder.makeUintConstant(0);
5909 zero = makeSmearedConstant(zero, vectorSize);
5910 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5911 case glslang::EOpConvInt64ToBool:
5912 case glslang::EOpConvUint64ToBool:
5913 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005914 zero = makeSmearedConstant(zero, vectorSize);
5915 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5916
5917 case glslang::EOpConvFloatToBool:
5918 zero = builder.makeFloatConstant(0.0F);
5919 zero = makeSmearedConstant(zero, vectorSize);
5920 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5921
5922 case glslang::EOpConvDoubleToBool:
5923 zero = builder.makeDoubleConstant(0.0);
5924 zero = makeSmearedConstant(zero, vectorSize);
5925 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5926
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005927 case glslang::EOpConvFloat16ToBool:
5928 zero = builder.makeFloat16Constant(0.0F);
5929 zero = makeSmearedConstant(zero, vectorSize);
5930 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005931
John Kessenich140f3df2015-06-26 16:58:36 -06005932 case glslang::EOpConvBoolToFloat:
5933 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005934 zero = builder.makeFloatConstant(0.0F);
5935 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005936 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005937
John Kessenich140f3df2015-06-26 16:58:36 -06005938 case glslang::EOpConvBoolToDouble:
5939 convOp = spv::OpSelect;
5940 zero = builder.makeDoubleConstant(0.0);
5941 one = builder.makeDoubleConstant(1.0);
5942 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005943
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005944 case glslang::EOpConvBoolToFloat16:
5945 convOp = spv::OpSelect;
5946 zero = builder.makeFloat16Constant(0.0F);
5947 one = builder.makeFloat16Constant(1.0F);
5948 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005949
5950 case glslang::EOpConvBoolToInt8:
5951 zero = builder.makeInt8Constant(0);
5952 one = builder.makeInt8Constant(1);
5953 convOp = spv::OpSelect;
5954 break;
5955
5956 case glslang::EOpConvBoolToUint8:
5957 zero = builder.makeUint8Constant(0);
5958 one = builder.makeUint8Constant(1);
5959 convOp = spv::OpSelect;
5960 break;
5961
5962 case glslang::EOpConvBoolToInt16:
5963 zero = builder.makeInt16Constant(0);
5964 one = builder.makeInt16Constant(1);
5965 convOp = spv::OpSelect;
5966 break;
5967
5968 case glslang::EOpConvBoolToUint16:
5969 zero = builder.makeUint16Constant(0);
5970 one = builder.makeUint16Constant(1);
5971 convOp = spv::OpSelect;
5972 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005973
John Kessenich140f3df2015-06-26 16:58:36 -06005974 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005975 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005976 if (op == glslang::EOpConvBoolToInt64)
5977 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005978 else
5979 zero = builder.makeIntConstant(0);
5980
5981 if (op == glslang::EOpConvBoolToInt64)
5982 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005983 else
5984 one = builder.makeIntConstant(1);
5985
John Kessenich140f3df2015-06-26 16:58:36 -06005986 convOp = spv::OpSelect;
5987 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005988
John Kessenich140f3df2015-06-26 16:58:36 -06005989 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005990 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005991 if (op == glslang::EOpConvBoolToUint64)
5992 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005993 else
5994 zero = builder.makeUintConstant(0);
5995
5996 if (op == glslang::EOpConvBoolToUint64)
5997 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005998 else
5999 one = builder.makeUintConstant(1);
6000
John Kessenich140f3df2015-06-26 16:58:36 -06006001 convOp = spv::OpSelect;
6002 break;
6003
John Kessenich66011cb2018-03-06 16:12:04 -07006004 case glslang::EOpConvInt8ToFloat16:
6005 case glslang::EOpConvInt8ToFloat:
6006 case glslang::EOpConvInt8ToDouble:
6007 case glslang::EOpConvInt16ToFloat16:
6008 case glslang::EOpConvInt16ToFloat:
6009 case glslang::EOpConvInt16ToDouble:
6010 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006011 case glslang::EOpConvIntToFloat:
6012 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006013 case glslang::EOpConvInt64ToFloat:
6014 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006015 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006016 convOp = spv::OpConvertSToF;
6017 break;
6018
John Kessenich66011cb2018-03-06 16:12:04 -07006019 case glslang::EOpConvUint8ToFloat16:
6020 case glslang::EOpConvUint8ToFloat:
6021 case glslang::EOpConvUint8ToDouble:
6022 case glslang::EOpConvUint16ToFloat16:
6023 case glslang::EOpConvUint16ToFloat:
6024 case glslang::EOpConvUint16ToDouble:
6025 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006026 case glslang::EOpConvUintToFloat:
6027 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006028 case glslang::EOpConvUint64ToFloat:
6029 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006030 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006031 convOp = spv::OpConvertUToF;
6032 break;
6033
6034 case glslang::EOpConvDoubleToFloat:
6035 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006036 case glslang::EOpConvDoubleToFloat16:
6037 case glslang::EOpConvFloat16ToDouble:
6038 case glslang::EOpConvFloatToFloat16:
6039 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06006040 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08006041 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06006042 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06006043 break;
6044
John Kessenich66011cb2018-03-06 16:12:04 -07006045 case glslang::EOpConvFloat16ToInt8:
6046 case glslang::EOpConvFloatToInt8:
6047 case glslang::EOpConvDoubleToInt8:
6048 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006049 case glslang::EOpConvFloatToInt16:
6050 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006051 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006052 case glslang::EOpConvFloatToInt:
6053 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006054 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006055 case glslang::EOpConvFloatToInt64:
6056 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006057 convOp = spv::OpConvertFToS;
6058 break;
6059
John Kessenich66011cb2018-03-06 16:12:04 -07006060 case glslang::EOpConvUint8ToInt8:
6061 case glslang::EOpConvInt8ToUint8:
6062 case glslang::EOpConvUint16ToInt16:
6063 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006064 case glslang::EOpConvUintToInt:
6065 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006066 case glslang::EOpConvUint64ToInt64:
6067 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006068 if (builder.isInSpecConstCodeGenMode()) {
6069 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006070 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6071 zero = builder.makeUint8Constant(0);
6072 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006073 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006074 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6075 zero = builder.makeUint64Constant(0);
6076 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006077 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006078 }
qining189b2032016-04-12 23:16:20 -04006079 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006080 // Use OpIAdd, instead of OpBitcast to do the conversion when
6081 // generating for OpSpecConstantOp instruction.
6082 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6083 }
6084 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006085 convOp = spv::OpBitcast;
6086 break;
6087
John Kessenich66011cb2018-03-06 16:12:04 -07006088 case glslang::EOpConvFloat16ToUint8:
6089 case glslang::EOpConvFloatToUint8:
6090 case glslang::EOpConvDoubleToUint8:
6091 case glslang::EOpConvFloat16ToUint16:
6092 case glslang::EOpConvFloatToUint16:
6093 case glslang::EOpConvDoubleToUint16:
6094 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006095 case glslang::EOpConvFloatToUint:
6096 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006097 case glslang::EOpConvFloatToUint64:
6098 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006099 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006100 convOp = spv::OpConvertFToU;
6101 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006102
John Kessenich66011cb2018-03-06 16:12:04 -07006103 case glslang::EOpConvInt8ToInt16:
6104 case glslang::EOpConvInt8ToInt:
6105 case glslang::EOpConvInt8ToInt64:
6106 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006107 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006108 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006109 case glslang::EOpConvIntToInt8:
6110 case glslang::EOpConvIntToInt16:
6111 case glslang::EOpConvIntToInt64:
6112 case glslang::EOpConvInt64ToInt8:
6113 case glslang::EOpConvInt64ToInt16:
6114 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006115 convOp = spv::OpSConvert;
6116 break;
6117
John Kessenich66011cb2018-03-06 16:12:04 -07006118 case glslang::EOpConvUint8ToUint16:
6119 case glslang::EOpConvUint8ToUint:
6120 case glslang::EOpConvUint8ToUint64:
6121 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006122 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006123 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006124 case glslang::EOpConvUintToUint8:
6125 case glslang::EOpConvUintToUint16:
6126 case glslang::EOpConvUintToUint64:
6127 case glslang::EOpConvUint64ToUint8:
6128 case glslang::EOpConvUint64ToUint16:
6129 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006130 convOp = spv::OpUConvert;
6131 break;
6132
John Kessenich66011cb2018-03-06 16:12:04 -07006133 case glslang::EOpConvInt8ToUint16:
6134 case glslang::EOpConvInt8ToUint:
6135 case glslang::EOpConvInt8ToUint64:
6136 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006137 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006138 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006139 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006140 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006141 case glslang::EOpConvIntToUint64:
6142 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006143 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006144 case glslang::EOpConvInt64ToUint:
6145 case glslang::EOpConvUint8ToInt16:
6146 case glslang::EOpConvUint8ToInt:
6147 case glslang::EOpConvUint8ToInt64:
6148 case glslang::EOpConvUint16ToInt8:
6149 case glslang::EOpConvUint16ToInt:
6150 case glslang::EOpConvUint16ToInt64:
6151 case glslang::EOpConvUintToInt8:
6152 case glslang::EOpConvUintToInt16:
6153 case glslang::EOpConvUintToInt64:
6154 case glslang::EOpConvUint64ToInt8:
6155 case glslang::EOpConvUint64ToInt16:
6156 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006157 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006158 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006159
6160 if (builder.isInSpecConstCodeGenMode()) {
6161 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006162 switch(op) {
6163 case glslang::EOpConvInt16ToUint8:
6164 case glslang::EOpConvIntToUint8:
6165 case glslang::EOpConvInt64ToUint8:
6166 case glslang::EOpConvUint16ToInt8:
6167 case glslang::EOpConvUintToInt8:
6168 case glslang::EOpConvUint64ToInt8:
6169 zero = builder.makeUint8Constant(0);
6170 break;
6171 case glslang::EOpConvInt8ToUint16:
6172 case glslang::EOpConvIntToUint16:
6173 case glslang::EOpConvInt64ToUint16:
6174 case glslang::EOpConvUint8ToInt16:
6175 case glslang::EOpConvUintToInt16:
6176 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006177 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006178 break;
6179 case glslang::EOpConvInt8ToUint:
6180 case glslang::EOpConvInt16ToUint:
6181 case glslang::EOpConvInt64ToUint:
6182 case glslang::EOpConvUint8ToInt:
6183 case glslang::EOpConvUint16ToInt:
6184 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006185 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006186 break;
6187 case glslang::EOpConvInt8ToUint64:
6188 case glslang::EOpConvInt16ToUint64:
6189 case glslang::EOpConvIntToUint64:
6190 case glslang::EOpConvUint8ToInt64:
6191 case glslang::EOpConvUint16ToInt64:
6192 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006193 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006194 break;
6195 default:
6196 assert(false && "Default missing");
6197 break;
6198 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006199 zero = makeSmearedConstant(zero, vectorSize);
6200 // Use OpIAdd, instead of OpBitcast to do the conversion when
6201 // generating for OpSpecConstantOp instruction.
6202 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6203 }
6204 // For normal run-time conversion instruction, use OpBitcast.
6205 convOp = spv::OpBitcast;
6206 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006207 case glslang::EOpConvUint64ToPtr:
6208 convOp = spv::OpConvertUToPtr;
6209 break;
6210 case glslang::EOpConvPtrToUint64:
6211 convOp = spv::OpConvertPtrToU;
6212 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006213 default:
6214 break;
6215 }
6216
6217 spv::Id result = 0;
6218 if (convOp == spv::OpNop)
6219 return result;
6220
6221 if (convOp == spv::OpSelect) {
6222 zero = makeSmearedConstant(zero, vectorSize);
6223 one = makeSmearedConstant(one, vectorSize);
6224 result = builder.createTriOp(convOp, destType, operand, one, zero);
6225 } else
6226 result = builder.createUnaryOp(convOp, destType, operand);
6227
John Kessenichead86222018-03-28 18:01:20 -06006228 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006229 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006230 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006231}
6232
6233spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6234{
6235 if (vectorSize == 0)
6236 return constant;
6237
6238 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6239 std::vector<spv::Id> components;
6240 for (int c = 0; c < vectorSize; ++c)
6241 components.push_back(constant);
6242 return builder.makeCompositeConstant(vectorTypeId, components);
6243}
6244
John Kessenich426394d2015-07-23 10:22:48 -06006245// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006246spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006247{
6248 spv::Op opCode = spv::OpNop;
6249
6250 switch (op) {
6251 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006252 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006253 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006254 opCode = spv::OpAtomicIAdd;
6255 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006256 case glslang::EOpAtomicCounterSubtract:
6257 opCode = spv::OpAtomicISub;
6258 break;
John Kessenich426394d2015-07-23 10:22:48 -06006259 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006260 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006261 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006262 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006263 break;
6264 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006265 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006266 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006267 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006268 break;
6269 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006270 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006271 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006272 opCode = spv::OpAtomicAnd;
6273 break;
6274 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006275 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006276 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006277 opCode = spv::OpAtomicOr;
6278 break;
6279 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006280 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006281 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006282 opCode = spv::OpAtomicXor;
6283 break;
6284 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006285 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006286 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006287 opCode = spv::OpAtomicExchange;
6288 break;
6289 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006290 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006291 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006292 opCode = spv::OpAtomicCompareExchange;
6293 break;
6294 case glslang::EOpAtomicCounterIncrement:
6295 opCode = spv::OpAtomicIIncrement;
6296 break;
6297 case glslang::EOpAtomicCounterDecrement:
6298 opCode = spv::OpAtomicIDecrement;
6299 break;
6300 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006301 case glslang::EOpImageAtomicLoad:
6302 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006303 opCode = spv::OpAtomicLoad;
6304 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006305 case glslang::EOpAtomicStore:
6306 case glslang::EOpImageAtomicStore:
6307 opCode = spv::OpAtomicStore;
6308 break;
John Kessenich426394d2015-07-23 10:22:48 -06006309 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006310 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006311 break;
6312 }
6313
Rex Xue8fe8b02017-09-26 15:42:56 +08006314 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6315 builder.addCapability(spv::CapabilityInt64Atomics);
6316
John Kessenich426394d2015-07-23 10:22:48 -06006317 // Sort out the operands
6318 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006319 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006320 // - compare-exchange swaps the value and comparator
6321 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006322 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006323 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6324 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6325 spv::Id scopeId;
6326 if (glslangIntermediate->usingVulkanMemoryModel()) {
6327 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6328 } else {
6329 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6330 }
6331 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006332 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006333 spv::Id semanticsId2 = semanticsId;
6334
6335 pointerId = operands[0];
6336 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6337 // no additional operands
6338 } else if (opCode == spv::OpAtomicCompareExchange) {
6339 compareId = operands[1];
6340 valueId = operands[2];
6341 if (operands.size() > 3) {
6342 scopeId = operands[3];
6343 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6344 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6345 }
6346 } else if (opCode == spv::OpAtomicLoad) {
6347 if (operands.size() > 1) {
6348 scopeId = operands[1];
6349 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6350 }
6351 } else {
6352 // atomic store or RMW
6353 valueId = operands[1];
6354 if (operands.size() > 2) {
6355 scopeId = operands[2];
6356 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6357 }
Rex Xu04db3f52015-09-16 11:44:02 +08006358 }
John Kessenich426394d2015-07-23 10:22:48 -06006359
Jeff Bolz36831c92018-09-05 10:11:41 -05006360 // Check for capabilities
6361 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006362 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6363 spv::MemorySemanticsMakeVisibleKHRMask |
6364 spv::MemorySemanticsOutputMemoryKHRMask |
6365 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006366 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6367 }
John Kessenich426394d2015-07-23 10:22:48 -06006368
Jeff Bolz36831c92018-09-05 10:11:41 -05006369 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6370 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6371 }
John Kessenich48d6e792017-10-06 21:21:48 -06006372
Jeff Bolz36831c92018-09-05 10:11:41 -05006373 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6374 spvAtomicOperands.push_back(pointerId);
6375 spvAtomicOperands.push_back(scopeId);
6376 spvAtomicOperands.push_back(semanticsId);
6377 if (opCode == spv::OpAtomicCompareExchange) {
6378 spvAtomicOperands.push_back(semanticsId2);
6379 spvAtomicOperands.push_back(valueId);
6380 spvAtomicOperands.push_back(compareId);
6381 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6382 spvAtomicOperands.push_back(valueId);
6383 }
John Kessenich48d6e792017-10-06 21:21:48 -06006384
Jeff Bolz36831c92018-09-05 10:11:41 -05006385 if (opCode == spv::OpAtomicStore) {
6386 builder.createNoResultOp(opCode, spvAtomicOperands);
6387 return 0;
6388 } else {
6389 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6390
6391 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6392 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6393 if (op == glslang::EOpAtomicCounterDecrement)
6394 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6395
6396 return resultId;
6397 }
John Kessenich426394d2015-07-23 10:22:48 -06006398}
6399
John Kessenicha28f7a72019-08-06 07:00:58 -06006400#ifndef GLSLANG_WEB
6401
John Kessenich91cef522016-05-05 16:45:40 -06006402// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006403spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006404{
John Kessenich66011cb2018-03-06 16:12:04 -07006405 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6406 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006407
Rex Xu51596642016-09-21 18:56:12 +08006408 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006409 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006410 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6411
chaocf200da82016-12-20 12:44:35 -08006412 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6413 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006414 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6415 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006416 } else if (op == glslang::EOpAnyInvocation ||
6417 op == glslang::EOpAllInvocations ||
6418 op == glslang::EOpAllInvocationsEqual) {
6419 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6420 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006421 } else {
6422 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006423 if (op == glslang::EOpMinInvocationsNonUniform ||
6424 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006425 op == glslang::EOpAddInvocationsNonUniform ||
6426 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6427 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6428 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6429 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6430 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6431 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006432 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006433
Rex Xu430ef402016-10-14 17:22:23 +08006434 switch (op) {
6435 case glslang::EOpMinInvocations:
6436 case glslang::EOpMaxInvocations:
6437 case glslang::EOpAddInvocations:
6438 case glslang::EOpMinInvocationsNonUniform:
6439 case glslang::EOpMaxInvocationsNonUniform:
6440 case glslang::EOpAddInvocationsNonUniform:
6441 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006442 break;
6443 case glslang::EOpMinInvocationsInclusiveScan:
6444 case glslang::EOpMaxInvocationsInclusiveScan:
6445 case glslang::EOpAddInvocationsInclusiveScan:
6446 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6447 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6448 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6449 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006450 break;
6451 case glslang::EOpMinInvocationsExclusiveScan:
6452 case glslang::EOpMaxInvocationsExclusiveScan:
6453 case glslang::EOpAddInvocationsExclusiveScan:
6454 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6455 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6456 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6457 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006458 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006459 default:
6460 break;
Rex Xu430ef402016-10-14 17:22:23 +08006461 }
John Kessenich149afc32018-08-14 13:31:43 -06006462 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6463 spvGroupOperands.push_back(scope);
6464 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006465 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006466 spvGroupOperands.push_back(groupOp);
6467 }
Rex Xu51596642016-09-21 18:56:12 +08006468 }
6469
John Kessenich149afc32018-08-14 13:31:43 -06006470 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6471 spv::IdImmediate op = { true, *opIt };
6472 spvGroupOperands.push_back(op);
6473 }
John Kessenich91cef522016-05-05 16:45:40 -06006474
6475 switch (op) {
6476 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006477 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006478 break;
John Kessenich91cef522016-05-05 16:45:40 -06006479 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006480 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006481 break;
John Kessenich91cef522016-05-05 16:45:40 -06006482 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006483 opCode = spv::OpSubgroupAllEqualKHR;
6484 break;
Rex Xu51596642016-09-21 18:56:12 +08006485 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006486 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006487 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006488 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006489 break;
6490 case glslang::EOpReadFirstInvocation:
6491 opCode = spv::OpSubgroupFirstInvocationKHR;
6492 break;
6493 case glslang::EOpBallot:
6494 {
6495 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6496 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6497 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6498 //
6499 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6500 //
6501 spv::Id uintType = builder.makeUintType(32);
6502 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6503 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6504
6505 std::vector<spv::Id> components;
6506 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6507 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6508
6509 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6510 return builder.createUnaryOp(spv::OpBitcast, typeId,
6511 builder.createCompositeConstruct(uvec2Type, components));
6512 }
6513
Rex Xu9d93a232016-05-05 12:30:44 +08006514 case glslang::EOpMinInvocations:
6515 case glslang::EOpMaxInvocations:
6516 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006517 case glslang::EOpMinInvocationsInclusiveScan:
6518 case glslang::EOpMaxInvocationsInclusiveScan:
6519 case glslang::EOpAddInvocationsInclusiveScan:
6520 case glslang::EOpMinInvocationsExclusiveScan:
6521 case glslang::EOpMaxInvocationsExclusiveScan:
6522 case glslang::EOpAddInvocationsExclusiveScan:
6523 if (op == glslang::EOpMinInvocations ||
6524 op == glslang::EOpMinInvocationsInclusiveScan ||
6525 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006526 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006527 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006528 else {
6529 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006530 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006531 else
Rex Xu51596642016-09-21 18:56:12 +08006532 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006533 }
Rex Xu430ef402016-10-14 17:22:23 +08006534 } else if (op == glslang::EOpMaxInvocations ||
6535 op == glslang::EOpMaxInvocationsInclusiveScan ||
6536 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006537 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006538 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006539 else {
6540 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006541 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006542 else
Rex Xu51596642016-09-21 18:56:12 +08006543 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006544 }
6545 } else {
6546 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006547 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006548 else
Rex Xu51596642016-09-21 18:56:12 +08006549 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006550 }
6551
Rex Xu2bbbe062016-08-23 15:41:05 +08006552 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006553 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006554
6555 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006556 case glslang::EOpMinInvocationsNonUniform:
6557 case glslang::EOpMaxInvocationsNonUniform:
6558 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006559 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6560 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6561 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6562 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6563 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6564 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6565 if (op == glslang::EOpMinInvocationsNonUniform ||
6566 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6567 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006568 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006569 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006570 else {
6571 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006572 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006573 else
Rex Xu51596642016-09-21 18:56:12 +08006574 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006575 }
6576 }
Rex Xu430ef402016-10-14 17:22:23 +08006577 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6578 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6579 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006580 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006581 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006582 else {
6583 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006584 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006585 else
Rex Xu51596642016-09-21 18:56:12 +08006586 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006587 }
6588 }
6589 else {
6590 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006591 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006592 else
Rex Xu51596642016-09-21 18:56:12 +08006593 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006594 }
6595
Rex Xu2bbbe062016-08-23 15:41:05 +08006596 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006597 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006598
6599 break;
John Kessenich91cef522016-05-05 16:45:40 -06006600 default:
6601 logger->missingFunctionality("invocation operation");
6602 return spv::NoResult;
6603 }
Rex Xu51596642016-09-21 18:56:12 +08006604
6605 assert(opCode != spv::OpNop);
6606 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006607}
6608
Rex Xu2bbbe062016-08-23 15:41:05 +08006609// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006610spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6611 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006612{
6613 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6614 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006615 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006616 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006617 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6618 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6619 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6620
6621 // Handle group invocation operations scalar by scalar.
6622 // The result type is the same type as the original type.
6623 // The algorithm is to:
6624 // - break the vector into scalars
6625 // - apply the operation to each scalar
6626 // - make a vector out the scalar results
6627
6628 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006629 int numComponents = builder.getNumComponents(operands[0]);
6630 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006631 std::vector<spv::Id> results;
6632
6633 // do each scalar op
6634 for (int comp = 0; comp < numComponents; ++comp) {
6635 std::vector<unsigned int> indexes;
6636 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006637 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6638 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006639 if (op == spv::OpSubgroupReadInvocationKHR) {
6640 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006641 spv::IdImmediate operand = { true, operands[1] };
6642 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006643 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006644 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6645 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006646 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006647 spv::IdImmediate operand = { true, operands[1] };
6648 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006649 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006650 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6651 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006652 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006653 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006654 spvGroupOperands.push_back(scalar);
6655 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006656
Rex Xub7072052016-09-26 15:53:40 +08006657 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006658 }
6659
6660 // put the pieces together
6661 return builder.createCompositeConstruct(typeId, results);
6662}
Rex Xu2bbbe062016-08-23 15:41:05 +08006663
John Kessenich66011cb2018-03-06 16:12:04 -07006664// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006665spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6666 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006667{
6668 // Add the required capabilities.
6669 switch (op) {
6670 case glslang::EOpSubgroupElect:
6671 builder.addCapability(spv::CapabilityGroupNonUniform);
6672 break;
6673 case glslang::EOpSubgroupAll:
6674 case glslang::EOpSubgroupAny:
6675 case glslang::EOpSubgroupAllEqual:
6676 builder.addCapability(spv::CapabilityGroupNonUniform);
6677 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6678 break;
6679 case glslang::EOpSubgroupBroadcast:
6680 case glslang::EOpSubgroupBroadcastFirst:
6681 case glslang::EOpSubgroupBallot:
6682 case glslang::EOpSubgroupInverseBallot:
6683 case glslang::EOpSubgroupBallotBitExtract:
6684 case glslang::EOpSubgroupBallotBitCount:
6685 case glslang::EOpSubgroupBallotInclusiveBitCount:
6686 case glslang::EOpSubgroupBallotExclusiveBitCount:
6687 case glslang::EOpSubgroupBallotFindLSB:
6688 case glslang::EOpSubgroupBallotFindMSB:
6689 builder.addCapability(spv::CapabilityGroupNonUniform);
6690 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6691 break;
6692 case glslang::EOpSubgroupShuffle:
6693 case glslang::EOpSubgroupShuffleXor:
6694 builder.addCapability(spv::CapabilityGroupNonUniform);
6695 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6696 break;
6697 case glslang::EOpSubgroupShuffleUp:
6698 case glslang::EOpSubgroupShuffleDown:
6699 builder.addCapability(spv::CapabilityGroupNonUniform);
6700 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6701 break;
6702 case glslang::EOpSubgroupAdd:
6703 case glslang::EOpSubgroupMul:
6704 case glslang::EOpSubgroupMin:
6705 case glslang::EOpSubgroupMax:
6706 case glslang::EOpSubgroupAnd:
6707 case glslang::EOpSubgroupOr:
6708 case glslang::EOpSubgroupXor:
6709 case glslang::EOpSubgroupInclusiveAdd:
6710 case glslang::EOpSubgroupInclusiveMul:
6711 case glslang::EOpSubgroupInclusiveMin:
6712 case glslang::EOpSubgroupInclusiveMax:
6713 case glslang::EOpSubgroupInclusiveAnd:
6714 case glslang::EOpSubgroupInclusiveOr:
6715 case glslang::EOpSubgroupInclusiveXor:
6716 case glslang::EOpSubgroupExclusiveAdd:
6717 case glslang::EOpSubgroupExclusiveMul:
6718 case glslang::EOpSubgroupExclusiveMin:
6719 case glslang::EOpSubgroupExclusiveMax:
6720 case glslang::EOpSubgroupExclusiveAnd:
6721 case glslang::EOpSubgroupExclusiveOr:
6722 case glslang::EOpSubgroupExclusiveXor:
6723 builder.addCapability(spv::CapabilityGroupNonUniform);
6724 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6725 break;
6726 case glslang::EOpSubgroupClusteredAdd:
6727 case glslang::EOpSubgroupClusteredMul:
6728 case glslang::EOpSubgroupClusteredMin:
6729 case glslang::EOpSubgroupClusteredMax:
6730 case glslang::EOpSubgroupClusteredAnd:
6731 case glslang::EOpSubgroupClusteredOr:
6732 case glslang::EOpSubgroupClusteredXor:
6733 builder.addCapability(spv::CapabilityGroupNonUniform);
6734 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6735 break;
6736 case glslang::EOpSubgroupQuadBroadcast:
6737 case glslang::EOpSubgroupQuadSwapHorizontal:
6738 case glslang::EOpSubgroupQuadSwapVertical:
6739 case glslang::EOpSubgroupQuadSwapDiagonal:
6740 builder.addCapability(spv::CapabilityGroupNonUniform);
6741 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6742 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006743 case glslang::EOpSubgroupPartitionedAdd:
6744 case glslang::EOpSubgroupPartitionedMul:
6745 case glslang::EOpSubgroupPartitionedMin:
6746 case glslang::EOpSubgroupPartitionedMax:
6747 case glslang::EOpSubgroupPartitionedAnd:
6748 case glslang::EOpSubgroupPartitionedOr:
6749 case glslang::EOpSubgroupPartitionedXor:
6750 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6751 case glslang::EOpSubgroupPartitionedInclusiveMul:
6752 case glslang::EOpSubgroupPartitionedInclusiveMin:
6753 case glslang::EOpSubgroupPartitionedInclusiveMax:
6754 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6755 case glslang::EOpSubgroupPartitionedInclusiveOr:
6756 case glslang::EOpSubgroupPartitionedInclusiveXor:
6757 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6758 case glslang::EOpSubgroupPartitionedExclusiveMul:
6759 case glslang::EOpSubgroupPartitionedExclusiveMin:
6760 case glslang::EOpSubgroupPartitionedExclusiveMax:
6761 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6762 case glslang::EOpSubgroupPartitionedExclusiveOr:
6763 case glslang::EOpSubgroupPartitionedExclusiveXor:
6764 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6765 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6766 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006767 default: assert(0 && "Unhandled subgroup operation!");
6768 }
6769
6770 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6771 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6772 const bool isBool = typeProxy == glslang::EbtBool;
6773
6774 spv::Op opCode = spv::OpNop;
6775
6776 // Figure out which opcode to use.
6777 switch (op) {
6778 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6779 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6780 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6781 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6782 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6783 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6784 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6785 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6786 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6787 case glslang::EOpSubgroupBallotBitCount:
6788 case glslang::EOpSubgroupBallotInclusiveBitCount:
6789 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6790 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6791 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6792 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6793 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6794 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6795 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6796 case glslang::EOpSubgroupAdd:
6797 case glslang::EOpSubgroupInclusiveAdd:
6798 case glslang::EOpSubgroupExclusiveAdd:
6799 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006800 case glslang::EOpSubgroupPartitionedAdd:
6801 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6802 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006803 if (isFloat) {
6804 opCode = spv::OpGroupNonUniformFAdd;
6805 } else {
6806 opCode = spv::OpGroupNonUniformIAdd;
6807 }
6808 break;
6809 case glslang::EOpSubgroupMul:
6810 case glslang::EOpSubgroupInclusiveMul:
6811 case glslang::EOpSubgroupExclusiveMul:
6812 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006813 case glslang::EOpSubgroupPartitionedMul:
6814 case glslang::EOpSubgroupPartitionedInclusiveMul:
6815 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006816 if (isFloat) {
6817 opCode = spv::OpGroupNonUniformFMul;
6818 } else {
6819 opCode = spv::OpGroupNonUniformIMul;
6820 }
6821 break;
6822 case glslang::EOpSubgroupMin:
6823 case glslang::EOpSubgroupInclusiveMin:
6824 case glslang::EOpSubgroupExclusiveMin:
6825 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006826 case glslang::EOpSubgroupPartitionedMin:
6827 case glslang::EOpSubgroupPartitionedInclusiveMin:
6828 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006829 if (isFloat) {
6830 opCode = spv::OpGroupNonUniformFMin;
6831 } else if (isUnsigned) {
6832 opCode = spv::OpGroupNonUniformUMin;
6833 } else {
6834 opCode = spv::OpGroupNonUniformSMin;
6835 }
6836 break;
6837 case glslang::EOpSubgroupMax:
6838 case glslang::EOpSubgroupInclusiveMax:
6839 case glslang::EOpSubgroupExclusiveMax:
6840 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006841 case glslang::EOpSubgroupPartitionedMax:
6842 case glslang::EOpSubgroupPartitionedInclusiveMax:
6843 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006844 if (isFloat) {
6845 opCode = spv::OpGroupNonUniformFMax;
6846 } else if (isUnsigned) {
6847 opCode = spv::OpGroupNonUniformUMax;
6848 } else {
6849 opCode = spv::OpGroupNonUniformSMax;
6850 }
6851 break;
6852 case glslang::EOpSubgroupAnd:
6853 case glslang::EOpSubgroupInclusiveAnd:
6854 case glslang::EOpSubgroupExclusiveAnd:
6855 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006856 case glslang::EOpSubgroupPartitionedAnd:
6857 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6858 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006859 if (isBool) {
6860 opCode = spv::OpGroupNonUniformLogicalAnd;
6861 } else {
6862 opCode = spv::OpGroupNonUniformBitwiseAnd;
6863 }
6864 break;
6865 case glslang::EOpSubgroupOr:
6866 case glslang::EOpSubgroupInclusiveOr:
6867 case glslang::EOpSubgroupExclusiveOr:
6868 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006869 case glslang::EOpSubgroupPartitionedOr:
6870 case glslang::EOpSubgroupPartitionedInclusiveOr:
6871 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006872 if (isBool) {
6873 opCode = spv::OpGroupNonUniformLogicalOr;
6874 } else {
6875 opCode = spv::OpGroupNonUniformBitwiseOr;
6876 }
6877 break;
6878 case glslang::EOpSubgroupXor:
6879 case glslang::EOpSubgroupInclusiveXor:
6880 case glslang::EOpSubgroupExclusiveXor:
6881 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006882 case glslang::EOpSubgroupPartitionedXor:
6883 case glslang::EOpSubgroupPartitionedInclusiveXor:
6884 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006885 if (isBool) {
6886 opCode = spv::OpGroupNonUniformLogicalXor;
6887 } else {
6888 opCode = spv::OpGroupNonUniformBitwiseXor;
6889 }
6890 break;
6891 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6892 case glslang::EOpSubgroupQuadSwapHorizontal:
6893 case glslang::EOpSubgroupQuadSwapVertical:
6894 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6895 default: assert(0 && "Unhandled subgroup operation!");
6896 }
6897
John Kessenich149afc32018-08-14 13:31:43 -06006898 // get the right Group Operation
6899 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006900 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006901 default:
6902 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006903 case glslang::EOpSubgroupBallotBitCount:
6904 case glslang::EOpSubgroupAdd:
6905 case glslang::EOpSubgroupMul:
6906 case glslang::EOpSubgroupMin:
6907 case glslang::EOpSubgroupMax:
6908 case glslang::EOpSubgroupAnd:
6909 case glslang::EOpSubgroupOr:
6910 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006911 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006912 break;
6913 case glslang::EOpSubgroupBallotInclusiveBitCount:
6914 case glslang::EOpSubgroupInclusiveAdd:
6915 case glslang::EOpSubgroupInclusiveMul:
6916 case glslang::EOpSubgroupInclusiveMin:
6917 case glslang::EOpSubgroupInclusiveMax:
6918 case glslang::EOpSubgroupInclusiveAnd:
6919 case glslang::EOpSubgroupInclusiveOr:
6920 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006921 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006922 break;
6923 case glslang::EOpSubgroupBallotExclusiveBitCount:
6924 case glslang::EOpSubgroupExclusiveAdd:
6925 case glslang::EOpSubgroupExclusiveMul:
6926 case glslang::EOpSubgroupExclusiveMin:
6927 case glslang::EOpSubgroupExclusiveMax:
6928 case glslang::EOpSubgroupExclusiveAnd:
6929 case glslang::EOpSubgroupExclusiveOr:
6930 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006931 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006932 break;
6933 case glslang::EOpSubgroupClusteredAdd:
6934 case glslang::EOpSubgroupClusteredMul:
6935 case glslang::EOpSubgroupClusteredMin:
6936 case glslang::EOpSubgroupClusteredMax:
6937 case glslang::EOpSubgroupClusteredAnd:
6938 case glslang::EOpSubgroupClusteredOr:
6939 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006940 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006941 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006942 case glslang::EOpSubgroupPartitionedAdd:
6943 case glslang::EOpSubgroupPartitionedMul:
6944 case glslang::EOpSubgroupPartitionedMin:
6945 case glslang::EOpSubgroupPartitionedMax:
6946 case glslang::EOpSubgroupPartitionedAnd:
6947 case glslang::EOpSubgroupPartitionedOr:
6948 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006949 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006950 break;
6951 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6952 case glslang::EOpSubgroupPartitionedInclusiveMul:
6953 case glslang::EOpSubgroupPartitionedInclusiveMin:
6954 case glslang::EOpSubgroupPartitionedInclusiveMax:
6955 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6956 case glslang::EOpSubgroupPartitionedInclusiveOr:
6957 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006958 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006959 break;
6960 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6961 case glslang::EOpSubgroupPartitionedExclusiveMul:
6962 case glslang::EOpSubgroupPartitionedExclusiveMin:
6963 case glslang::EOpSubgroupPartitionedExclusiveMax:
6964 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6965 case glslang::EOpSubgroupPartitionedExclusiveOr:
6966 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006967 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006968 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006969 }
6970
John Kessenich149afc32018-08-14 13:31:43 -06006971 // build the instruction
6972 std::vector<spv::IdImmediate> spvGroupOperands;
6973
6974 // Every operation begins with the Execution Scope operand.
6975 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6976 spvGroupOperands.push_back(executionScope);
6977
6978 // Next, for all operations that use a Group Operation, push that as an operand.
6979 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006980 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006981 spvGroupOperands.push_back(groupOperand);
6982 }
6983
John Kessenich66011cb2018-03-06 16:12:04 -07006984 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006985 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6986 spv::IdImmediate operand = { true, *opIt };
6987 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006988 }
6989
6990 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006991 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006992 switch (op) {
6993 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006994 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6995 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6996 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6997 }
6998 if (directionId != spv::NoResult) {
6999 spv::IdImmediate direction = { true, directionId };
7000 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007001 }
7002
7003 return builder.createOp(opCode, typeId, spvGroupOperands);
7004}
John Kessenicha28f7a72019-08-06 07:00:58 -06007005#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007006
John Kessenich5e4b1242015-08-06 22:53:06 -06007007spv::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 -06007008{
John Kessenich66011cb2018-03-06 16:12:04 -07007009 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7010 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007011
John Kessenich140f3df2015-06-26 16:58:36 -06007012 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007013 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007014 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007015 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007016 spv::Id typeId0 = 0;
7017 if (consumedOperands > 0)
7018 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007019 spv::Id typeId1 = 0;
7020 if (consumedOperands > 1)
7021 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007022 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007023
7024 switch (op) {
7025 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007026 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007027 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007028 else if (isUnsigned)
7029 libCall = spv::GLSLstd450UMin;
7030 else
7031 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007032 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007033 break;
7034 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007035 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007036 break;
7037 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007038 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007039 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007040 else if (isUnsigned)
7041 libCall = spv::GLSLstd450UMax;
7042 else
7043 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007044 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007045 break;
7046 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007047 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007048 break;
7049 case glslang::EOpDot:
7050 opCode = spv::OpDot;
7051 break;
7052 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007053 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007054 break;
7055
7056 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007057 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007058 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007059 else if (isUnsigned)
7060 libCall = spv::GLSLstd450UClamp;
7061 else
7062 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007063 builder.promoteScalar(precision, operands.front(), operands[1]);
7064 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007065 break;
7066 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007067 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7068 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007069 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007070 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007071 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007072 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007073 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007074 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007075 break;
7076 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007077 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007078 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007079 break;
7080 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007081 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007082 builder.promoteScalar(precision, operands[0], operands[2]);
7083 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007084 break;
7085
7086 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007087 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007088 break;
7089 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007090 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007091 break;
7092 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007093 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007094 break;
7095 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007096 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007097 break;
7098 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007099 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007100 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007101#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007102 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007103 if (typeProxy == glslang::EbtFloat16)
7104 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007105 libCall = spv::GLSLstd450InterpolateAtSample;
7106 break;
7107 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007108 if (typeProxy == glslang::EbtFloat16)
7109 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007110 libCall = spv::GLSLstd450InterpolateAtOffset;
7111 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007112 case glslang::EOpAddCarry:
7113 opCode = spv::OpIAddCarry;
7114 typeId = builder.makeStructResultType(typeId0, typeId0);
7115 consumedOperands = 2;
7116 break;
7117 case glslang::EOpSubBorrow:
7118 opCode = spv::OpISubBorrow;
7119 typeId = builder.makeStructResultType(typeId0, typeId0);
7120 consumedOperands = 2;
7121 break;
7122 case glslang::EOpUMulExtended:
7123 opCode = spv::OpUMulExtended;
7124 typeId = builder.makeStructResultType(typeId0, typeId0);
7125 consumedOperands = 2;
7126 break;
7127 case glslang::EOpIMulExtended:
7128 opCode = spv::OpSMulExtended;
7129 typeId = builder.makeStructResultType(typeId0, typeId0);
7130 consumedOperands = 2;
7131 break;
7132 case glslang::EOpBitfieldExtract:
7133 if (isUnsigned)
7134 opCode = spv::OpBitFieldUExtract;
7135 else
7136 opCode = spv::OpBitFieldSExtract;
7137 break;
7138 case glslang::EOpBitfieldInsert:
7139 opCode = spv::OpBitFieldInsert;
7140 break;
7141
7142 case glslang::EOpFma:
7143 libCall = spv::GLSLstd450Fma;
7144 break;
7145 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007146 {
7147 libCall = spv::GLSLstd450FrexpStruct;
7148 assert(builder.isPointerType(typeId1));
7149 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007150 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007151 if (width == 16)
7152 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7153 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007154 if (builder.getNumComponents(operands[0]) == 1)
7155 frexpIntType = builder.makeIntegerType(width, true);
7156 else
7157 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7158 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7159 consumedOperands = 1;
7160 }
John Kessenich55e7d112015-11-15 21:33:39 -07007161 break;
7162 case glslang::EOpLdexp:
7163 libCall = spv::GLSLstd450Ldexp;
7164 break;
7165
Rex Xu574ab042016-04-14 16:53:07 +08007166 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007167 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007168
John Kessenich66011cb2018-03-06 16:12:04 -07007169 case glslang::EOpSubgroupBroadcast:
7170 case glslang::EOpSubgroupBallotBitExtract:
7171 case glslang::EOpSubgroupShuffle:
7172 case glslang::EOpSubgroupShuffleXor:
7173 case glslang::EOpSubgroupShuffleUp:
7174 case glslang::EOpSubgroupShuffleDown:
7175 case glslang::EOpSubgroupClusteredAdd:
7176 case glslang::EOpSubgroupClusteredMul:
7177 case glslang::EOpSubgroupClusteredMin:
7178 case glslang::EOpSubgroupClusteredMax:
7179 case glslang::EOpSubgroupClusteredAnd:
7180 case glslang::EOpSubgroupClusteredOr:
7181 case glslang::EOpSubgroupClusteredXor:
7182 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007183 case glslang::EOpSubgroupPartitionedAdd:
7184 case glslang::EOpSubgroupPartitionedMul:
7185 case glslang::EOpSubgroupPartitionedMin:
7186 case glslang::EOpSubgroupPartitionedMax:
7187 case glslang::EOpSubgroupPartitionedAnd:
7188 case glslang::EOpSubgroupPartitionedOr:
7189 case glslang::EOpSubgroupPartitionedXor:
7190 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7191 case glslang::EOpSubgroupPartitionedInclusiveMul:
7192 case glslang::EOpSubgroupPartitionedInclusiveMin:
7193 case glslang::EOpSubgroupPartitionedInclusiveMax:
7194 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7195 case glslang::EOpSubgroupPartitionedInclusiveOr:
7196 case glslang::EOpSubgroupPartitionedInclusiveXor:
7197 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7198 case glslang::EOpSubgroupPartitionedExclusiveMul:
7199 case glslang::EOpSubgroupPartitionedExclusiveMin:
7200 case glslang::EOpSubgroupPartitionedExclusiveMax:
7201 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7202 case glslang::EOpSubgroupPartitionedExclusiveOr:
7203 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007204 return createSubgroupOperation(op, typeId, operands, typeProxy);
7205
Rex Xu9d93a232016-05-05 12:30:44 +08007206 case glslang::EOpSwizzleInvocations:
7207 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7208 libCall = spv::SwizzleInvocationsAMD;
7209 break;
7210 case glslang::EOpSwizzleInvocationsMasked:
7211 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7212 libCall = spv::SwizzleInvocationsMaskedAMD;
7213 break;
7214 case glslang::EOpWriteInvocation:
7215 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7216 libCall = spv::WriteInvocationAMD;
7217 break;
7218
7219 case glslang::EOpMin3:
7220 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7221 if (isFloat)
7222 libCall = spv::FMin3AMD;
7223 else {
7224 if (isUnsigned)
7225 libCall = spv::UMin3AMD;
7226 else
7227 libCall = spv::SMin3AMD;
7228 }
7229 break;
7230 case glslang::EOpMax3:
7231 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7232 if (isFloat)
7233 libCall = spv::FMax3AMD;
7234 else {
7235 if (isUnsigned)
7236 libCall = spv::UMax3AMD;
7237 else
7238 libCall = spv::SMax3AMD;
7239 }
7240 break;
7241 case glslang::EOpMid3:
7242 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7243 if (isFloat)
7244 libCall = spv::FMid3AMD;
7245 else {
7246 if (isUnsigned)
7247 libCall = spv::UMid3AMD;
7248 else
7249 libCall = spv::SMid3AMD;
7250 }
7251 break;
7252
7253 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007254 if (typeProxy == glslang::EbtFloat16)
7255 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007256 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7257 libCall = spv::InterpolateAtVertexAMD;
7258 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05007259 case glslang::EOpBarrier:
7260 {
7261 // This is for the extended controlBarrier function, with four operands.
7262 // The unextended barrier() goes through createNoArgOperation.
7263 assert(operands.size() == 4);
7264 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7265 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7266 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7267 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007268 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7269 spv::MemorySemanticsMakeVisibleKHRMask |
7270 spv::MemorySemanticsOutputMemoryKHRMask |
7271 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007272 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7273 }
7274 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7275 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7276 }
7277 return 0;
7278 }
7279 break;
7280 case glslang::EOpMemoryBarrier:
7281 {
7282 // This is for the extended memoryBarrier function, with three operands.
7283 // The unextended memoryBarrier() goes through createNoArgOperation.
7284 assert(operands.size() == 3);
7285 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7286 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7287 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007288 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7289 spv::MemorySemanticsMakeVisibleKHRMask |
7290 spv::MemorySemanticsOutputMemoryKHRMask |
7291 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007292 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7293 }
7294 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7295 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7296 }
7297 return 0;
7298 }
7299 break;
Chao Chen3c366992018-09-19 11:41:59 -07007300
Chao Chenb50c02e2018-09-19 11:42:24 -07007301 case glslang::EOpReportIntersectionNV:
7302 {
7303 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007304 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007305 }
7306 break;
7307 case glslang::EOpTraceNV:
7308 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007309 builder.createNoResultOp(spv::OpTraceNV, operands);
7310 return 0;
7311 }
7312 break;
7313 case glslang::EOpExecuteCallableNV:
7314 {
7315 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007316 return 0;
7317 }
7318 break;
Chao Chen3c366992018-09-19 11:41:59 -07007319 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7320 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7321 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007322 case glslang::EOpCooperativeMatrixMulAdd:
7323 opCode = spv::OpCooperativeMatrixMulAddNV;
7324 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007325#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007326 default:
7327 return 0;
7328 }
7329
7330 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007331 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007332 // Use an extended instruction from the standard library.
7333 // Construct the call arguments, without modifying the original operands vector.
7334 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7335 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007336 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007337 } else if (opCode == spv::OpDot && !isFloat) {
7338 // int dot(int, int)
7339 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7340 const int componentCount = builder.getNumComponents(operands[0]);
7341 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7342 builder.setPrecision(mulOp, precision);
7343 id = builder.createCompositeExtract(mulOp, typeId, 0);
7344 for (int i = 1; i < componentCount; ++i) {
7345 builder.setPrecision(id, precision);
7346 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7347 }
John Kessenich2359bd02015-12-06 19:29:11 -07007348 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007349 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007350 case 0:
7351 // should all be handled by visitAggregate and createNoArgOperation
7352 assert(0);
7353 return 0;
7354 case 1:
7355 // should all be handled by createUnaryOperation
7356 assert(0);
7357 return 0;
7358 case 2:
7359 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7360 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007361 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007362 // anything 3 or over doesn't have l-value operands, so all should be consumed
7363 assert(consumedOperands == operands.size());
7364 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007365 break;
7366 }
7367 }
7368
John Kessenich55e7d112015-11-15 21:33:39 -07007369 // Decode the return types that were structures
7370 switch (op) {
7371 case glslang::EOpAddCarry:
7372 case glslang::EOpSubBorrow:
7373 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7374 id = builder.createCompositeExtract(id, typeId0, 0);
7375 break;
7376 case glslang::EOpUMulExtended:
7377 case glslang::EOpIMulExtended:
7378 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7379 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7380 break;
7381 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007382 {
7383 assert(operands.size() == 2);
7384 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7385 // "exp" is floating-point type (from HLSL intrinsic)
7386 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7387 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7388 builder.createStore(member1, operands[1]);
7389 } else
7390 // "exp" is integer type (from GLSL built-in function)
7391 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7392 id = builder.createCompositeExtract(id, typeId0, 0);
7393 }
John Kessenich55e7d112015-11-15 21:33:39 -07007394 break;
7395 default:
7396 break;
7397 }
7398
John Kessenich32cfd492016-02-02 12:37:46 -07007399 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007400}
7401
Rex Xu9d93a232016-05-05 12:30:44 +08007402// Intrinsics with no arguments (or no return value, and no precision).
7403spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007404{
Jeff Bolz36831c92018-09-05 10:11:41 -05007405 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7406 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007407
7408 switch (op) {
John Kessenicha28f7a72019-08-06 07:00:58 -06007409#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007410 case glslang::EOpEmitVertex:
7411 builder.createNoResultOp(spv::OpEmitVertex);
7412 return 0;
7413 case glslang::EOpEndPrimitive:
7414 builder.createNoResultOp(spv::OpEndPrimitive);
7415 return 0;
7416 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007417 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007418 if (glslangIntermediate->usingVulkanMemoryModel()) {
7419 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7420 spv::MemorySemanticsOutputMemoryKHRMask |
7421 spv::MemorySemanticsAcquireReleaseMask);
7422 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7423 } else {
7424 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7425 }
John Kessenich82979362017-12-11 04:02:24 -07007426 } else {
7427 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7428 spv::MemorySemanticsWorkgroupMemoryMask |
7429 spv::MemorySemanticsAcquireReleaseMask);
7430 }
John Kessenich140f3df2015-06-26 16:58:36 -06007431 return 0;
7432 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007433 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7434 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007435 return 0;
7436 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007437 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7438 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007439 return 0;
7440 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007441 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7442 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007443 return 0;
7444 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007445 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7446 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007447 return 0;
7448 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007449 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7450 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007451 return 0;
7452 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007453 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7454 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007455 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007456 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007457 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007458 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007459 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007460 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007461 case glslang::EOpDeviceMemoryBarrier:
7462 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7463 spv::MemorySemanticsImageMemoryMask |
7464 spv::MemorySemanticsAcquireReleaseMask);
7465 return 0;
7466 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7467 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7468 spv::MemorySemanticsImageMemoryMask |
7469 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007470 return 0;
7471 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007472 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7473 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007474 return 0;
7475 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007476 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7477 spv::MemorySemanticsWorkgroupMemoryMask |
7478 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007479 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007480 case glslang::EOpSubgroupBarrier:
7481 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7482 spv::MemorySemanticsAcquireReleaseMask);
7483 return spv::NoResult;
7484 case glslang::EOpSubgroupMemoryBarrier:
7485 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7486 spv::MemorySemanticsAcquireReleaseMask);
7487 return spv::NoResult;
7488 case glslang::EOpSubgroupMemoryBarrierBuffer:
7489 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7490 spv::MemorySemanticsAcquireReleaseMask);
7491 return spv::NoResult;
7492 case glslang::EOpSubgroupMemoryBarrierImage:
7493 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7494 spv::MemorySemanticsAcquireReleaseMask);
7495 return spv::NoResult;
7496 case glslang::EOpSubgroupMemoryBarrierShared:
7497 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7498 spv::MemorySemanticsAcquireReleaseMask);
7499 return spv::NoResult;
7500 case glslang::EOpSubgroupElect: {
7501 std::vector<spv::Id> operands;
7502 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7503 }
Rex Xu9d93a232016-05-05 12:30:44 +08007504 case glslang::EOpTime:
7505 {
7506 std::vector<spv::Id> args; // Dummy arguments
7507 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7508 return builder.setPrecision(id, precision);
7509 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007510 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007511 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007512 return 0;
7513 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007514 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007515 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007516
7517 case glslang::EOpBeginInvocationInterlock:
7518 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7519 return 0;
7520 case glslang::EOpEndInvocationInterlock:
7521 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7522 return 0;
7523
Jeff Bolzba6170b2019-07-01 09:23:23 -05007524 case glslang::EOpIsHelperInvocation:
7525 {
7526 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007527 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7528 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7529 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007530 }
7531
amhagan91fb0092019-07-10 21:14:38 -04007532 case glslang::EOpReadClockSubgroupKHR: {
7533 std::vector<spv::Id> args;
7534 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7535 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7536 builder.addCapability(spv::CapabilityShaderClockKHR);
7537 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7538 }
7539
7540 case glslang::EOpReadClockDeviceKHR: {
7541 std::vector<spv::Id> args;
7542 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7543 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7544 builder.addCapability(spv::CapabilityShaderClockKHR);
7545 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7546 }
John Kessenicha28f7a72019-08-06 07:00:58 -06007547#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007548 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007549 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007550 return 0;
7551 }
7552}
7553
7554spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7555{
John Kessenich2f273362015-07-18 22:34:27 -06007556 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007557 spv::Id id;
7558 if (symbolValues.end() != iter) {
7559 id = iter->second;
7560 return id;
7561 }
7562
7563 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007564 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7565 auto forcedType = getForcedType(builtIn, symbol->getType());
7566 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007567 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007568 if (forcedType.second != spv::NoType)
7569 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007570
Rex Xuc884b4a2016-06-29 15:03:44 +08007571 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007572 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7573 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7574 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007575#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007576 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7577#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007578 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007579 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007580 if (symbol->getQualifier().hasIndex())
7581 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7582 if (symbol->getQualifier().hasComponent())
7583 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007584 // atomic counters use this:
7585 if (symbol->getQualifier().hasOffset())
7586 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007587 }
7588
scygan2c864272016-05-18 18:09:17 +02007589 if (symbol->getQualifier().hasLocation())
7590 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007591 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007592 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007593 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007594 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007595 }
John Kessenich140f3df2015-06-26 16:58:36 -06007596 if (symbol->getQualifier().hasSet())
7597 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007598 else if (IsDescriptorResource(symbol->getType())) {
7599 // default to 0
7600 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7601 }
John Kessenich140f3df2015-06-26 16:58:36 -06007602 if (symbol->getQualifier().hasBinding())
7603 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007604 else if (IsDescriptorResource(symbol->getType())) {
7605 // default to 0
7606 builder.addDecoration(id, spv::DecorationBinding, 0);
7607 }
John Kessenich6c292d32016-02-15 20:58:50 -07007608 if (symbol->getQualifier().hasAttachment())
7609 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich7015bd62019-08-01 03:28:08 -06007610#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007611 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007612 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007613 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007614 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007615 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7616 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7617 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7618 }
7619 if (symbol->getQualifier().hasXfbOffset())
7620 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007621 }
John Kessenich7015bd62019-08-01 03:28:08 -06007622#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007623
Rex Xu1da878f2016-02-21 20:59:01 +08007624 if (symbol->getType().isImage()) {
7625 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007626 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007627 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007628 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007629 }
7630
John Kessenich9c14f772019-06-17 08:38:35 -06007631 // add built-in variable decoration
7632 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007633 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007634 }
John Kessenich140f3df2015-06-26 16:58:36 -06007635
John Kessenich5611c6d2018-04-05 11:25:02 -06007636 // nonuniform
7637 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7638
John Kessenicha28f7a72019-08-06 07:00:58 -06007639#ifndef GLSLANG_WEB
chaoc0ad6a4e2016-12-19 16:29:34 -08007640 if (builtIn == spv::BuiltInSampleMask) {
7641 spv::Decoration decoration;
7642 // GL_NV_sample_mask_override_coverage extension
7643 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007644 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007645 else
7646 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007647 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007648 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007649 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007650 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7651 }
7652 }
chaoc771d89f2017-01-13 01:10:53 -08007653 else if (builtIn == spv::BuiltInLayer) {
7654 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007655 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007656 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007657 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7658 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7659 }
John Kessenichb41bff62017-08-11 13:07:17 -06007660 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007661 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7662 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007663 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7664 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7665 }
7666 }
7667
chaoc6e5acae2016-12-20 13:28:52 -08007668 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007669 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007670 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007671 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7672 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007673 if (symbol->getQualifier().pervertexNV) {
7674 builder.addDecoration(id, spv::DecorationPerVertexNV);
7675 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7676 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7677 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007678#endif
7679
John Kessenich5d610ee2018-03-07 18:05:55 -07007680 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7681 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7682 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7683 symbol->getType().getQualifier().semanticName);
7684 }
7685
John Kessenich7015bd62019-08-01 03:28:08 -06007686 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007687 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7688 }
7689
John Kessenich140f3df2015-06-26 16:58:36 -06007690 return id;
7691}
7692
John Kessenicha28f7a72019-08-06 07:00:58 -06007693#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007694// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7695void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7696{
7697 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007698 if (qualifier.perPrimitiveNV) {
7699 // Need to add capability/extension for fragment shader.
7700 // Mesh shader already adds this by default.
7701 if (glslangIntermediate->getStage() == EShLangFragment) {
7702 builder.addCapability(spv::CapabilityMeshShadingNV);
7703 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7704 }
Chao Chen3c366992018-09-19 11:41:59 -07007705 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007706 }
Chao Chen3c366992018-09-19 11:41:59 -07007707 if (qualifier.perViewNV)
7708 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7709 if (qualifier.perTaskNV)
7710 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7711 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007712 if (qualifier.perPrimitiveNV) {
7713 // Need to add capability/extension for fragment shader.
7714 // Mesh shader already adds this by default.
7715 if (glslangIntermediate->getStage() == EShLangFragment) {
7716 builder.addCapability(spv::CapabilityMeshShadingNV);
7717 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7718 }
Chao Chen3c366992018-09-19 11:41:59 -07007719 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007720 }
Chao Chen3c366992018-09-19 11:41:59 -07007721 if (qualifier.perViewNV)
7722 builder.addDecoration(id, spv::DecorationPerViewNV);
7723 if (qualifier.perTaskNV)
7724 builder.addDecoration(id, spv::DecorationPerTaskNV);
7725 }
7726}
7727#endif
7728
John Kessenich55e7d112015-11-15 21:33:39 -07007729// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007730// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007731//
7732// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7733//
7734// Recursively walk the nodes. The nodes form a tree whose leaves are
7735// regular constants, which themselves are trees that createSpvConstant()
7736// recursively walks. So, this function walks the "top" of the tree:
7737// - emit specialization constant-building instructions for specConstant
7738// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007739spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007740{
John Kessenich7cc0e282016-03-20 00:46:02 -06007741 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007742
qining4f4bb812016-04-03 23:55:17 -04007743 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007744 if (! node.getQualifier().specConstant) {
7745 // hand off to the non-spec-constant path
7746 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7747 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007748 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007749 nextConst, false);
7750 }
7751
7752 // We now know we have a specialization constant to build
7753
John Kessenichd94c0032016-05-30 19:29:40 -06007754 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007755 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7756 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7757 std::vector<spv::Id> dimConstId;
7758 for (int dim = 0; dim < 3; ++dim) {
7759 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7760 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007761 if (specConst) {
7762 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7763 glslangIntermediate->getLocalSizeSpecId(dim));
7764 }
qining4f4bb812016-04-03 23:55:17 -04007765 }
7766 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7767 }
7768
7769 // An AST node labelled as specialization constant should be a symbol node.
7770 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7771 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007772 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007773 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007774 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7775 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7776 // will set the builder into spec constant op instruction generating mode.
7777 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007778 result = accessChainLoad(sub_tree->getType());
7779 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007780 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007781 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007782 } else {
7783 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007784 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007785 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007786 builder.addName(result, sn->getName().c_str());
7787 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007788 }
qining4f4bb812016-04-03 23:55:17 -04007789
7790 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7791 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007792 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007793 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007794}
7795
John Kessenich140f3df2015-06-26 16:58:36 -06007796// Use 'consts' as the flattened glslang source of scalar constants to recursively
7797// build the aggregate SPIR-V constant.
7798//
7799// If there are not enough elements present in 'consts', 0 will be substituted;
7800// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7801//
qining08408382016-03-21 09:51:37 -04007802spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007803{
7804 // vector of constants for SPIR-V
7805 std::vector<spv::Id> spvConsts;
7806
7807 // Type is used for struct and array constants
7808 spv::Id typeId = convertGlslangToSpvType(glslangType);
7809
7810 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007811 glslang::TType elementType(glslangType, 0);
7812 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007813 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007814 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007815 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007816 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007817 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007818 } else if (glslangType.isCoopMat()) {
7819 glslang::TType componentType(glslangType.getBasicType());
7820 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007821 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007822 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7823 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007824 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007825 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007826 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7827 bool zero = nextConst >= consts.size();
7828 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007829 case glslang::EbtInt8:
7830 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7831 break;
7832 case glslang::EbtUint8:
7833 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7834 break;
7835 case glslang::EbtInt16:
7836 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7837 break;
7838 case glslang::EbtUint16:
7839 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7840 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007841 case glslang::EbtInt:
7842 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7843 break;
7844 case glslang::EbtUint:
7845 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7846 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007847 case glslang::EbtInt64:
7848 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7849 break;
7850 case glslang::EbtUint64:
7851 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7852 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007853 case glslang::EbtFloat:
7854 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7855 break;
7856 case glslang::EbtDouble:
7857 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7858 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007859 case glslang::EbtFloat16:
7860 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7861 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007862 case glslang::EbtBool:
7863 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7864 break;
7865 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007866 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007867 break;
7868 }
7869 ++nextConst;
7870 }
7871 } else {
7872 // we have a non-aggregate (scalar) constant
7873 bool zero = nextConst >= consts.size();
7874 spv::Id scalar = 0;
7875 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007876 case glslang::EbtInt8:
7877 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7878 break;
7879 case glslang::EbtUint8:
7880 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7881 break;
7882 case glslang::EbtInt16:
7883 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7884 break;
7885 case glslang::EbtUint16:
7886 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7887 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007888 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007889 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007890 break;
7891 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007892 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007893 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007894 case glslang::EbtInt64:
7895 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7896 break;
7897 case glslang::EbtUint64:
7898 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7899 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007900 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007901 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007902 break;
7903 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007904 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007905 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007906 case glslang::EbtFloat16:
7907 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7908 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007909 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007910 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007911 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007912 case glslang::EbtReference:
7913 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7914 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7915 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007916 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007917 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007918 break;
7919 }
7920 ++nextConst;
7921 return scalar;
7922 }
7923
7924 return builder.makeCompositeConstant(typeId, spvConsts);
7925}
7926
John Kessenich7c1aa102015-10-15 13:29:11 -06007927// Return true if the node is a constant or symbol whose reading has no
7928// non-trivial observable cost or effect.
7929bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7930{
7931 // don't know what this is
7932 if (node == nullptr)
7933 return false;
7934
7935 // a constant is safe
7936 if (node->getAsConstantUnion() != nullptr)
7937 return true;
7938
7939 // not a symbol means non-trivial
7940 if (node->getAsSymbolNode() == nullptr)
7941 return false;
7942
7943 // a symbol, depends on what's being read
7944 switch (node->getType().getQualifier().storage) {
7945 case glslang::EvqTemporary:
7946 case glslang::EvqGlobal:
7947 case glslang::EvqIn:
7948 case glslang::EvqInOut:
7949 case glslang::EvqConst:
7950 case glslang::EvqConstReadOnly:
7951 case glslang::EvqUniform:
7952 return true;
7953 default:
7954 return false;
7955 }
qining25262b32016-05-06 17:25:16 -04007956}
John Kessenich7c1aa102015-10-15 13:29:11 -06007957
7958// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007959// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007960// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007961// Return true if trivial.
7962bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7963{
7964 if (node == nullptr)
7965 return false;
7966
John Kessenich84cc15f2017-05-24 16:44:47 -06007967 // count non scalars as trivial, as well as anything coming from HLSL
7968 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007969 return true;
7970
John Kessenich7c1aa102015-10-15 13:29:11 -06007971 // symbols and constants are trivial
7972 if (isTrivialLeaf(node))
7973 return true;
7974
7975 // otherwise, it needs to be a simple operation or one or two leaf nodes
7976
7977 // not a simple operation
7978 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7979 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7980 if (binaryNode == nullptr && unaryNode == nullptr)
7981 return false;
7982
7983 // not on leaf nodes
7984 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7985 return false;
7986
7987 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7988 return false;
7989 }
7990
7991 switch (node->getAsOperator()->getOp()) {
7992 case glslang::EOpLogicalNot:
7993 case glslang::EOpConvIntToBool:
7994 case glslang::EOpConvUintToBool:
7995 case glslang::EOpConvFloatToBool:
7996 case glslang::EOpConvDoubleToBool:
7997 case glslang::EOpEqual:
7998 case glslang::EOpNotEqual:
7999 case glslang::EOpLessThan:
8000 case glslang::EOpGreaterThan:
8001 case glslang::EOpLessThanEqual:
8002 case glslang::EOpGreaterThanEqual:
8003 case glslang::EOpIndexDirect:
8004 case glslang::EOpIndexDirectStruct:
8005 case glslang::EOpLogicalXor:
8006 case glslang::EOpAny:
8007 case glslang::EOpAll:
8008 return true;
8009 default:
8010 return false;
8011 }
8012}
8013
8014// Emit short-circuiting code, where 'right' is never evaluated unless
8015// the left side is true (for &&) or false (for ||).
8016spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8017{
8018 spv::Id boolTypeId = builder.makeBoolType();
8019
8020 // emit left operand
8021 builder.clearAccessChain();
8022 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008023 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008024
8025 // Operands to accumulate OpPhi operands
8026 std::vector<spv::Id> phiOperands;
8027 // accumulate left operand's phi information
8028 phiOperands.push_back(leftId);
8029 phiOperands.push_back(builder.getBuildPoint()->getId());
8030
8031 // Make the two kinds of operation symmetric with a "!"
8032 // || => emit "if (! left) result = right"
8033 // && => emit "if ( left) result = right"
8034 //
8035 // TODO: this runtime "not" for || could be avoided by adding functionality
8036 // to 'builder' to have an "else" without an "then"
8037 if (op == glslang::EOpLogicalOr)
8038 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8039
8040 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008041 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008042
8043 // emit right operand as the "then" part of the "if"
8044 builder.clearAccessChain();
8045 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008046 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008047
8048 // accumulate left operand's phi information
8049 phiOperands.push_back(rightId);
8050 phiOperands.push_back(builder.getBuildPoint()->getId());
8051
8052 // finish the "if"
8053 ifBuilder.makeEndIf();
8054
8055 // phi together the two results
8056 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8057}
8058
John Kessenicha28f7a72019-08-06 07:00:58 -06008059#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008060// Return type Id of the imported set of extended instructions corresponds to the name.
8061// Import this set if it has not been imported yet.
8062spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8063{
8064 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8065 return extBuiltinMap[name];
8066 else {
Rex Xu51596642016-09-21 18:56:12 +08008067 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008068 spv::Id extBuiltins = builder.import(name);
8069 extBuiltinMap[name] = extBuiltins;
8070 return extBuiltins;
8071 }
8072}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008073#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008074
John Kessenich140f3df2015-06-26 16:58:36 -06008075}; // end anonymous namespace
8076
8077namespace glslang {
8078
John Kessenich68d78fd2015-07-12 19:28:10 -06008079void GetSpirvVersion(std::string& version)
8080{
John Kessenich9e55f632015-07-15 10:03:39 -06008081 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008082 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008083 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008084 version = buf;
8085}
8086
John Kessenicha372a3e2017-11-02 22:32:14 -06008087// For low-order part of the generator's magic number. Bump up
8088// when there is a change in the style (e.g., if SSA form changes,
8089// or a different instruction sequence to do something gets used).
8090int GetSpirvGeneratorVersion()
8091{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008092 // return 1; // start
8093 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008094 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008095 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008096 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008097 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8098 // versions 4 and 6 each generate OpArrayLength as it has long been done
8099 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008100}
8101
John Kessenich140f3df2015-06-26 16:58:36 -06008102// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008103void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008104{
8105 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008106 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008107 if (out.fail())
8108 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008109 for (int i = 0; i < (int)spirv.size(); ++i) {
8110 unsigned int word = spirv[i];
8111 out.write((const char*)&word, 4);
8112 }
8113 out.close();
8114}
8115
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008116// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008117void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008118{
8119 std::ofstream out;
8120 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008121 if (out.fail())
8122 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008123 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008124 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008125 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008126 if (varName != nullptr) {
8127 out << "\t #pragma once" << std::endl;
8128 out << "const uint32_t " << varName << "[] = {" << std::endl;
8129 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008130 const int WORDS_PER_LINE = 8;
8131 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8132 out << "\t";
8133 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8134 const unsigned int word = spirv[i + j];
8135 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8136 if (i + j + 1 < (int)spirv.size()) {
8137 out << ",";
8138 }
8139 }
8140 out << std::endl;
8141 }
Flavio15017db2017-02-15 14:29:33 -08008142 if (varName != nullptr) {
8143 out << "};";
8144 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008145 out.close();
8146}
8147
John Kessenich140f3df2015-06-26 16:58:36 -06008148//
8149// Set up the glslang traversal
8150//
John Kessenich4e11b612018-08-30 16:56:59 -06008151void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008152{
Lei Zhang17535f72016-05-04 15:55:59 -04008153 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008154 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008155}
8156
John Kessenich4e11b612018-08-30 16:56:59 -06008157void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008158 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008159{
John Kessenich140f3df2015-06-26 16:58:36 -06008160 TIntermNode* root = intermediate.getTreeRoot();
8161
8162 if (root == 0)
8163 return;
8164
John Kessenich4e11b612018-08-30 16:56:59 -06008165 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008166 if (options == nullptr)
8167 options = &defaultOptions;
8168
John Kessenich4e11b612018-08-30 16:56:59 -06008169 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008170
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008171 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008172 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008173 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008174 it.dumpSpv(spirv);
8175
GregFfb03a552018-03-29 11:49:14 -06008176#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008177 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8178 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008179 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8180 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008181 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008182 prelegalization = false;
8183 }
John Kessenich717c80a2018-08-23 15:17:10 -06008184
John Kessenich4e11b612018-08-30 16:56:59 -06008185 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008186 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008187
John Kessenich717c80a2018-08-23 15:17:10 -06008188 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008189 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008190
GregFcd1f1692017-09-21 18:40:22 -06008191#endif
8192
John Kessenich4e11b612018-08-30 16:56:59 -06008193 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008194}
8195
8196}; // end namespace glslang