blob: 24c7232b691cf267211e36403955edfd61f7b3cf [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 Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600173 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
174 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
176
John Kessenichead86222018-03-28 18:01:20 -0600177 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
178 glslang::TBasicType typeProxy, bool reduceComparison = true);
179 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
180 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500181 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600182 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600186 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500188 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 +0800189 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800190 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600192 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 +0800193 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700195#ifdef NV_EXTENSIONS
196 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
197#endif
qining08408382016-03-21 09:51:37 -0400198 spv::Id createSpvConstant(const glslang::TIntermTyped&);
199 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600200 bool isTrivialLeaf(const glslang::TIntermTyped* node);
201 bool isTrivial(const glslang::TIntermTyped* node);
202 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500203#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800204 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700206 void addPre13Extension(const char* ext)
207 {
208 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
209 builder.addExtension(ext);
210 }
John Kessenich9c14f772019-06-17 08:38:35 -0600211 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
212 spv::Id translateForcedType(spv::Id object);
John Kessenich140f3df2015-06-26 16:58:36 -0600213
John Kessenich121853f2017-05-31 17:11:16 -0600214 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600216 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700217 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600218 int sequenceDepth;
219
Lei Zhang17535f72016-05-04 15:55:59 -0400220 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400221
John Kessenich140f3df2015-06-26 16:58:36 -0600222 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
223 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700224 bool inEntryPoint;
225 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700226 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 -0700227 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600228 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600229 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600230 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800231 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600232
John Kessenich2f273362015-07-18 22:34:27 -0600233 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600234 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600235 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700236 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
238 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700240 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600241 // Map pointee types for EbtReference to their forward pointers
242 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600243 // Type forcing, for when SPIR-V wants a different type than the AST,
244 // requiring local translation to and from SPIR-V type on every access.
245 // Maps <builtin-variable-id -> AST-required-type-id>
246 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600247};
248
249//
250// Helper functions for translating glslang representations to SPIR-V enumerants.
251//
252
253// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700254spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600255{
John Kessenich66e2faf2016-03-12 18:34:36 -0700256 switch (source) {
257 case glslang::EShSourceGlsl:
258 switch (profile) {
259 case ENoProfile:
260 case ECoreProfile:
261 case ECompatibilityProfile:
262 return spv::SourceLanguageGLSL;
263 case EEsProfile:
264 return spv::SourceLanguageESSL;
265 default:
266 return spv::SourceLanguageUnknown;
267 }
268 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600269 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 default:
271 return spv::SourceLanguageUnknown;
272 }
273}
274
275// Translate glslang language (stage) to SPIR-V execution model.
276spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
277{
278 switch (stage) {
279 case EShLangVertex: return spv::ExecutionModelVertex;
280 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
281 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
282 case EShLangGeometry: return spv::ExecutionModelGeometry;
283 case EShLangFragment: return spv::ExecutionModelFragment;
284 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700285#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700286 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
287 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
288 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
289 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
290 case EShLangMissNV: return spv::ExecutionModelMissNV;
291 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700292 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
293 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
294#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600295 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700296 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600297 return spv::ExecutionModelFragment;
298 }
299}
300
John Kessenich140f3df2015-06-26 16:58:36 -0600301// Translate glslang sampler type to SPIR-V dimensionality.
302spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
303{
304 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700305 case glslang::Esd1D: return spv::Dim1D;
306 case glslang::Esd2D: return spv::Dim2D;
307 case glslang::Esd3D: return spv::Dim3D;
308 case glslang::EsdCube: return spv::DimCube;
309 case glslang::EsdRect: return spv::DimRect;
310 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700311 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600312 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700313 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600314 return spv::Dim2D;
315 }
316}
317
John Kessenichf6640762016-08-01 19:44:00 -0600318// Translate glslang precision to SPIR-V precision decorations.
319spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600320{
John Kessenichf6640762016-08-01 19:44:00 -0600321 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700322 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600323 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600324 default:
325 return spv::NoPrecision;
326 }
327}
328
John Kessenichf6640762016-08-01 19:44:00 -0600329// Translate glslang type to SPIR-V precision decorations.
330spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
331{
332 return TranslatePrecisionDecoration(type.getQualifier().precision);
333}
334
John Kessenich140f3df2015-06-26 16:58:36 -0600335// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600336spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600337{
338 if (type.getBasicType() == glslang::EbtBlock) {
339 switch (type.getQualifier().storage) {
340 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600341 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::EvqVaryingIn: return spv::DecorationBlock;
343 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700344#ifdef NV_EXTENSIONS
345 case glslang::EvqPayloadNV: return spv::DecorationBlock;
346 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
347 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700348 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
349 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700350#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600351 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700352 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600353 break;
354 }
355 }
356
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358}
359
Rex Xu1da878f2016-02-21 20:59:01 +0800360// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500361void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800362{
Jeff Bolz36831c92018-09-05 10:11:41 -0500363 if (!useVulkanMemoryModel) {
364 if (qualifier.coherent)
365 memory.push_back(spv::DecorationCoherent);
366 if (qualifier.volatil) {
367 memory.push_back(spv::DecorationVolatile);
368 memory.push_back(spv::DecorationCoherent);
369 }
John Kessenich14b85d32018-06-04 15:36:03 -0600370 }
Rex Xu1da878f2016-02-21 20:59:01 +0800371 if (qualifier.restrict)
372 memory.push_back(spv::DecorationRestrict);
373 if (qualifier.readonly)
374 memory.push_back(spv::DecorationNonWritable);
375 if (qualifier.writeonly)
376 memory.push_back(spv::DecorationNonReadable);
377}
378
John Kessenich140f3df2015-06-26 16:58:36 -0600379// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700380spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600381{
382 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700383 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600384 case glslang::ElmRowMajor:
385 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700386 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600387 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700388 default:
389 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600390 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600391 }
392 } else {
393 switch (type.getBasicType()) {
394 default:
John Kessenich4016e382016-07-15 11:53:56 -0600395 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 break;
397 case glslang::EbtBlock:
398 switch (type.getQualifier().storage) {
399 case glslang::EvqUniform:
400 case glslang::EvqBuffer:
401 switch (type.getQualifier().layoutPacking) {
402 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600403 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
404 default:
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600406 }
407 case glslang::EvqVaryingIn:
408 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700409 if (type.getQualifier().isTaskMemory()) {
410 switch (type.getQualifier().layoutPacking) {
411 case glslang::ElpShared: return spv::DecorationGLSLShared;
412 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
413 default: break;
414 }
415 } else {
416 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
417 }
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700419#ifdef NV_EXTENSIONS
420 case glslang::EvqPayloadNV:
421 case glslang::EvqPayloadInNV:
422 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700423 case glslang::EvqCallableDataNV:
424 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700425 return spv::DecorationMax;
426#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600427 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700428 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600429 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600430 }
431 }
432 }
433}
434
435// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600436// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700437// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800438spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600439{
Rex Xubbceed72016-05-21 09:40:44 +0800440 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700441 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600442 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800443 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700444 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700445 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600446 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800447#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800448 else if (qualifier.explicitInterp) {
449 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800450 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800451 }
Rex Xu9d93a232016-05-05 12:30:44 +0800452#endif
Rex Xubbceed72016-05-21 09:40:44 +0800453 else
John Kessenich4016e382016-07-15 11:53:56 -0600454 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800455}
456
457// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600458// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800459// should be applied.
460spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
461{
462 if (qualifier.patch)
463 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700464 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600465 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700466 else if (qualifier.sample) {
467 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600468 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700469 } else
John Kessenich4016e382016-07-15 11:53:56 -0600470 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600471}
472
John Kessenich92187592016-02-01 13:45:25 -0700473// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700474spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600475{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700476 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600477 return spv::DecorationInvariant;
478 else
John Kessenich4016e382016-07-15 11:53:56 -0600479 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600480}
481
qining9220dbb2016-05-04 17:34:38 -0400482// If glslang type is noContraction, return SPIR-V NoContraction decoration.
483spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
484{
485 if (qualifier.noContraction)
486 return spv::DecorationNoContraction;
487 else
John Kessenich4016e382016-07-15 11:53:56 -0600488 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400489}
490
John Kessenich5611c6d2018-04-05 11:25:02 -0600491// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
492spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
493{
494 if (qualifier.isNonUniform()) {
495 builder.addExtension("SPV_EXT_descriptor_indexing");
496 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
497 return spv::DecorationNonUniformEXT;
498 } else
499 return spv::DecorationMax;
500}
501
Jeff Bolz36831c92018-09-05 10:11:41 -0500502spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
503{
504 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
505 return spv::MemoryAccessMaskNone;
506 }
507 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
508 if (coherentFlags.volatil ||
509 coherentFlags.coherent ||
510 coherentFlags.devicecoherent ||
511 coherentFlags.queuefamilycoherent ||
512 coherentFlags.workgroupcoherent ||
513 coherentFlags.subgroupcoherent) {
514 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
515 spv::MemoryAccessMakePointerVisibleKHRMask;
516 }
517 if (coherentFlags.nonprivate) {
518 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
519 }
520 if (coherentFlags.volatil) {
521 mask = mask | spv::MemoryAccessVolatileMask;
522 }
523 if (mask != spv::MemoryAccessMaskNone) {
524 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
525 }
526 return mask;
527}
528
529spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
530{
531 if (!glslangIntermediate->usingVulkanMemoryModel()) {
532 return spv::ImageOperandsMaskNone;
533 }
534 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
535 if (coherentFlags.volatil ||
536 coherentFlags.coherent ||
537 coherentFlags.devicecoherent ||
538 coherentFlags.queuefamilycoherent ||
539 coherentFlags.workgroupcoherent ||
540 coherentFlags.subgroupcoherent) {
541 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
542 spv::ImageOperandsMakeTexelVisibleKHRMask;
543 }
544 if (coherentFlags.nonprivate) {
545 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
546 }
547 if (coherentFlags.volatil) {
548 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
549 }
550 if (mask != spv::ImageOperandsMaskNone) {
551 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
552 }
553 return mask;
554}
555
556spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
557{
558 spv::Builder::AccessChain::CoherentFlags flags;
559 flags.coherent = type.getQualifier().coherent;
560 flags.devicecoherent = type.getQualifier().devicecoherent;
561 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
562 // shared variables are implicitly workgroupcoherent in GLSL.
563 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
564 type.getQualifier().storage == glslang::EvqShared;
565 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500567 // *coherent variables are implicitly nonprivate in GLSL
568 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500569 flags.subgroupcoherent ||
570 flags.workgroupcoherent ||
571 flags.queuefamilycoherent ||
572 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600573 flags.coherent ||
574 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500575 flags.isImage = type.getBasicType() == glslang::EbtSampler;
576 return flags;
577}
578
579spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
580{
581 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600582 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500583 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
584 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
585 } else if (coherentFlags.devicecoherent) {
586 scope = spv::ScopeDevice;
587 } else if (coherentFlags.queuefamilycoherent) {
588 scope = spv::ScopeQueueFamilyKHR;
589 } else if (coherentFlags.workgroupcoherent) {
590 scope = spv::ScopeWorkgroup;
591 } else if (coherentFlags.subgroupcoherent) {
592 scope = spv::ScopeSubgroup;
593 } else {
594 scope = spv::ScopeMax;
595 }
596 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
597 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
598 }
599 return scope;
600}
601
David Netoa901ffe2016-06-08 14:11:40 +0100602// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
603// associated capabilities when required. For some built-in variables, a capability
604// is generated only when using the variable in an executable instruction, but not when
605// just declaring a struct member variable with it. This is true for PointSize,
606// ClipDistance, and CullDistance.
607spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600608{
609 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700610 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600611 // Defer adding the capability until the built-in is actually used.
612 if (! memberDeclaration) {
613 switch (glslangIntermediate->getStage()) {
614 case EShLangGeometry:
615 builder.addCapability(spv::CapabilityGeometryPointSize);
616 break;
617 case EShLangTessControl:
618 case EShLangTessEvaluation:
619 builder.addCapability(spv::CapabilityTessellationPointSize);
620 break;
621 default:
622 break;
623 }
John Kessenich92187592016-02-01 13:45:25 -0700624 }
625 return spv::BuiltInPointSize;
626
John Kessenichebb50532016-05-16 19:22:05 -0600627 // These *Distance capabilities logically belong here, but if the member is declared and
628 // then never used, consumers of SPIR-V prefer the capability not be declared.
629 // They are now generated when used, rather than here when declared.
630 // Potentially, the specification should be more clear what the minimum
631 // use needed is to trigger the capability.
632 //
John Kessenich92187592016-02-01 13:45:25 -0700633 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100634 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800635 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700636 return spv::BuiltInClipDistance;
637
638 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100639 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800640 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700641 return spv::BuiltInCullDistance;
642
643 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600644 builder.addCapability(spv::CapabilityMultiViewport);
645 if (glslangIntermediate->getStage() == EShLangVertex ||
646 glslangIntermediate->getStage() == EShLangTessControl ||
647 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800648
John Kessenichba6a3c22017-09-13 13:22:50 -0600649 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
650 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800651 }
John Kessenich92187592016-02-01 13:45:25 -0700652 return spv::BuiltInViewportIndex;
653
John Kessenich5e801132016-02-15 11:09:46 -0700654 case glslang::EbvSampleId:
655 builder.addCapability(spv::CapabilitySampleRateShading);
656 return spv::BuiltInSampleId;
657
658 case glslang::EbvSamplePosition:
659 builder.addCapability(spv::CapabilitySampleRateShading);
660 return spv::BuiltInSamplePosition;
661
662 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700663 return spv::BuiltInSampleMask;
664
John Kessenich78a45572016-07-08 14:05:15 -0600665 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700666#ifdef NV_EXTENSIONS
667 if (glslangIntermediate->getStage() == EShLangMeshNV) {
668 return spv::BuiltInLayer;
669 }
670#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600671 builder.addCapability(spv::CapabilityGeometry);
672 if (glslangIntermediate->getStage() == EShLangVertex ||
673 glslangIntermediate->getStage() == EShLangTessControl ||
674 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800675
John Kessenichba6a3c22017-09-13 13:22:50 -0600676 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
677 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800678 }
John Kessenich78a45572016-07-08 14:05:15 -0600679 return spv::BuiltInLayer;
680
John Kessenich140f3df2015-06-26 16:58:36 -0600681 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600682 case glslang::EbvVertexId: return spv::BuiltInVertexId;
683 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700684 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
685 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800686
John Kessenichda581a22015-10-14 14:10:30 -0600687 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700688 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800689 builder.addCapability(spv::CapabilityDrawParameters);
690 return spv::BuiltInBaseVertex;
691
John Kessenichda581a22015-10-14 14:10:30 -0600692 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700693 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800694 builder.addCapability(spv::CapabilityDrawParameters);
695 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200696
John Kessenichda581a22015-10-14 14:10:30 -0600697 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700698 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800699 builder.addCapability(spv::CapabilityDrawParameters);
700 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200701
702 case glslang::EbvPrimitiveId:
703 if (glslangIntermediate->getStage() == EShLangFragment)
704 builder.addCapability(spv::CapabilityGeometry);
705 return spv::BuiltInPrimitiveId;
706
Rex Xu37cdcee2017-06-29 17:46:34 +0800707 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800708 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
709 builder.addCapability(spv::CapabilityStencilExportEXT);
710 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800711
John Kessenich140f3df2015-06-26 16:58:36 -0600712 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
714 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
715 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
716 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
717 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
718 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
719 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600720 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
721 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
722 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
723 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
724 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
725 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
726 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
727 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800728
Rex Xu574ab042016-04-14 16:53:07 +0800729 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800730 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800731 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
732 return spv::BuiltInSubgroupSize;
733
Rex Xu574ab042016-04-14 16:53:07 +0800734 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800735 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800736 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
737 return spv::BuiltInSubgroupLocalInvocationId;
738
Rex Xu574ab042016-04-14 16:53:07 +0800739 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800740 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
741 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600742 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800743
Rex Xu574ab042016-04-14 16:53:07 +0800744 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800745 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
746 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600747 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800748
Rex Xu574ab042016-04-14 16:53:07 +0800749 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800750 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
751 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600752 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800753
Rex Xu574ab042016-04-14 16:53:07 +0800754 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800755 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
756 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600757 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800758
Rex Xu574ab042016-04-14 16:53:07 +0800759 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800760 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
761 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600762 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800763
John Kessenich66011cb2018-03-06 16:12:04 -0700764 case glslang::EbvNumSubgroups:
765 builder.addCapability(spv::CapabilityGroupNonUniform);
766 return spv::BuiltInNumSubgroups;
767
768 case glslang::EbvSubgroupID:
769 builder.addCapability(spv::CapabilityGroupNonUniform);
770 return spv::BuiltInSubgroupId;
771
772 case glslang::EbvSubgroupSize2:
773 builder.addCapability(spv::CapabilityGroupNonUniform);
774 return spv::BuiltInSubgroupSize;
775
776 case glslang::EbvSubgroupInvocation2:
777 builder.addCapability(spv::CapabilityGroupNonUniform);
778 return spv::BuiltInSubgroupLocalInvocationId;
779
780 case glslang::EbvSubgroupEqMask2:
781 builder.addCapability(spv::CapabilityGroupNonUniform);
782 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
783 return spv::BuiltInSubgroupEqMask;
784
785 case glslang::EbvSubgroupGeMask2:
786 builder.addCapability(spv::CapabilityGroupNonUniform);
787 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
788 return spv::BuiltInSubgroupGeMask;
789
790 case glslang::EbvSubgroupGtMask2:
791 builder.addCapability(spv::CapabilityGroupNonUniform);
792 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
793 return spv::BuiltInSubgroupGtMask;
794
795 case glslang::EbvSubgroupLeMask2:
796 builder.addCapability(spv::CapabilityGroupNonUniform);
797 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
798 return spv::BuiltInSubgroupLeMask;
799
800 case glslang::EbvSubgroupLtMask2:
801 builder.addCapability(spv::CapabilityGroupNonUniform);
802 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
803 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600804
Rex Xu9d93a232016-05-05 12:30:44 +0800805#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800806 case glslang::EbvBaryCoordNoPersp:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspAMD;
809
810 case glslang::EbvBaryCoordNoPerspCentroid:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
813
814 case glslang::EbvBaryCoordNoPerspSample:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordNoPerspSampleAMD;
817
818 case glslang::EbvBaryCoordSmooth:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothAMD;
821
822 case glslang::EbvBaryCoordSmoothCentroid:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordSmoothCentroidAMD;
825
826 case glslang::EbvBaryCoordSmoothSample:
827 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
828 return spv::BuiltInBaryCoordSmoothSampleAMD;
829
830 case glslang::EbvBaryCoordPullModel:
831 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
832 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800833#endif
chaoc771d89f2017-01-13 01:10:53 -0800834
John Kessenich6c8aaac2017-02-27 01:20:51 -0700835 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700836 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700837 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700838 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700839
840 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700841 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700842 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700843 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700844
Daniel Koch5154db52018-11-26 10:01:58 -0500845 case glslang::EbvFragSizeEXT:
846 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
847 builder.addCapability(spv::CapabilityFragmentDensityEXT);
848 return spv::BuiltInFragSizeEXT;
849
850 case glslang::EbvFragInvocationCountEXT:
851 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
852 builder.addCapability(spv::CapabilityFragmentDensityEXT);
853 return spv::BuiltInFragInvocationCountEXT;
854
chaoc771d89f2017-01-13 01:10:53 -0800855#ifdef NV_EXTENSIONS
856 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800857 if (!memberDeclaration) {
858 builder.addExtension(spv::E_SPV_NV_viewport_array2);
859 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
860 }
chaoc771d89f2017-01-13 01:10:53 -0800861 return spv::BuiltInViewportMaskNV;
862 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800863 if (!memberDeclaration) {
864 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
865 builder.addCapability(spv::CapabilityShaderStereoViewNV);
866 }
chaoc771d89f2017-01-13 01:10:53 -0800867 return spv::BuiltInSecondaryPositionNV;
868 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800869 if (!memberDeclaration) {
870 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
871 builder.addCapability(spv::CapabilityShaderStereoViewNV);
872 }
chaoc771d89f2017-01-13 01:10:53 -0800873 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800874 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800875 if (!memberDeclaration) {
876 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
877 builder.addCapability(spv::CapabilityPerViewAttributesNV);
878 }
chaocdf3956c2017-02-14 14:52:34 -0800879 return spv::BuiltInPositionPerViewNV;
880 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800881 if (!memberDeclaration) {
882 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
883 builder.addCapability(spv::CapabilityPerViewAttributesNV);
884 }
chaocdf3956c2017-02-14 14:52:34 -0800885 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700886 case glslang::EbvFragFullyCoveredNV:
887 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
888 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
889 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700890 case glslang::EbvFragmentSizeNV:
891 builder.addExtension(spv::E_SPV_NV_shading_rate);
892 builder.addCapability(spv::CapabilityShadingRateNV);
893 return spv::BuiltInFragmentSizeNV;
894 case glslang::EbvInvocationsPerPixelNV:
895 builder.addExtension(spv::E_SPV_NV_shading_rate);
896 builder.addCapability(spv::CapabilityShadingRateNV);
897 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898
Daniel Koch593a4e02019-05-27 16:46:31 -0400899 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700918 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700919 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700920 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700921 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700922 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700923 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700924 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700925 return spv::BuiltInWorldToObjectNV;
926 case glslang::EbvIncomingRayFlagsNV:
927 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400928
929 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700930 case glslang::EbvBaryCoordNV:
931 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
932 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
933 return spv::BuiltInBaryCoordNV;
934 case glslang::EbvBaryCoordNoPerspNV:
935 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
936 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
937 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400938
939 // mesh shaders
940 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700941 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700943 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700945 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400946 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700947 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400948 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700949 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400950 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700951 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400952 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700953 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400954 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700955 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400956#endif
Daniel Koch2cb2f192019-06-04 08:43:32 -0400957
958 // sm builtins
959 case glslang::EbvWarpsPerSM:
960 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
961 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
962 return spv::BuiltInWarpsPerSMNV;
963 case glslang::EbvSMCount:
964 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
965 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
966 return spv::BuiltInSMCountNV;
967 case glslang::EbvWarpID:
968 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
969 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
970 return spv::BuiltInWarpIDNV;
971 case glslang::EbvSMID:
972 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
973 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
974 return spv::BuiltInSMIDNV;
Rex Xu3e783f92017-02-22 16:44:48 +0800975 default:
976 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600977 }
978}
979
Rex Xufc618912015-09-09 16:42:49 +0800980// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700981spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800982{
983 assert(type.getBasicType() == glslang::EbtSampler);
984
John Kessenich5d0fa972016-02-15 11:57:00 -0700985 // Check for capabilities
986 switch (type.getQualifier().layoutFormat) {
987 case glslang::ElfRg32f:
988 case glslang::ElfRg16f:
989 case glslang::ElfR11fG11fB10f:
990 case glslang::ElfR16f:
991 case glslang::ElfRgba16:
992 case glslang::ElfRgb10A2:
993 case glslang::ElfRg16:
994 case glslang::ElfRg8:
995 case glslang::ElfR16:
996 case glslang::ElfR8:
997 case glslang::ElfRgba16Snorm:
998 case glslang::ElfRg16Snorm:
999 case glslang::ElfRg8Snorm:
1000 case glslang::ElfR16Snorm:
1001 case glslang::ElfR8Snorm:
1002
1003 case glslang::ElfRg32i:
1004 case glslang::ElfRg16i:
1005 case glslang::ElfRg8i:
1006 case glslang::ElfR16i:
1007 case glslang::ElfR8i:
1008
1009 case glslang::ElfRgb10a2ui:
1010 case glslang::ElfRg32ui:
1011 case glslang::ElfRg16ui:
1012 case glslang::ElfRg8ui:
1013 case glslang::ElfR16ui:
1014 case glslang::ElfR8ui:
1015 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1016 break;
1017
1018 default:
1019 break;
1020 }
1021
1022 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001023 switch (type.getQualifier().layoutFormat) {
1024 case glslang::ElfNone: return spv::ImageFormatUnknown;
1025 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1026 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1027 case glslang::ElfR32f: return spv::ImageFormatR32f;
1028 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1029 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1030 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1031 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1032 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1033 case glslang::ElfR16f: return spv::ImageFormatR16f;
1034 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1035 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1036 case glslang::ElfRg16: return spv::ImageFormatRg16;
1037 case glslang::ElfRg8: return spv::ImageFormatRg8;
1038 case glslang::ElfR16: return spv::ImageFormatR16;
1039 case glslang::ElfR8: return spv::ImageFormatR8;
1040 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1041 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1042 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1043 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1044 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1045 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1046 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1047 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1048 case glslang::ElfR32i: return spv::ImageFormatR32i;
1049 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1050 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1051 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1052 case glslang::ElfR16i: return spv::ImageFormatR16i;
1053 case glslang::ElfR8i: return spv::ImageFormatR8i;
1054 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1055 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1056 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1057 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1058 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1059 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1060 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1061 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1062 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1063 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001064 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001065 }
1066}
1067
John Kesseniche18fd202018-01-30 11:01:39 -07001068spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001069{
John Kesseniche18fd202018-01-30 11:01:39 -07001070 if (selectionNode.getFlatten())
1071 return spv::SelectionControlFlattenMask;
1072 if (selectionNode.getDontFlatten())
1073 return spv::SelectionControlDontFlattenMask;
1074 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001075}
1076
John Kesseniche18fd202018-01-30 11:01:39 -07001077spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001078{
John Kesseniche18fd202018-01-30 11:01:39 -07001079 if (switchNode.getFlatten())
1080 return spv::SelectionControlFlattenMask;
1081 if (switchNode.getDontFlatten())
1082 return spv::SelectionControlDontFlattenMask;
1083 return spv::SelectionControlMaskNone;
1084}
1085
John Kessenicha2858d92018-01-31 08:11:18 -07001086// return a non-0 dependency if the dependency argument must be set
1087spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001088 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001089{
1090 spv::LoopControlMask control = spv::LoopControlMaskNone;
1091
1092 if (loopNode.getDontUnroll())
1093 control = control | spv::LoopControlDontUnrollMask;
1094 if (loopNode.getUnroll())
1095 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001096 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001097 control = control | spv::LoopControlDependencyInfiniteMask;
1098 else if (loopNode.getLoopDependency() > 0) {
1099 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001100 operands.push_back((unsigned int)loopNode.getLoopDependency());
1101 }
1102 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1103 if (loopNode.getMinIterations() > 0) {
1104 control = control | spv::LoopControlMinIterationsMask;
1105 operands.push_back(loopNode.getMinIterations());
1106 }
1107 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1108 control = control | spv::LoopControlMaxIterationsMask;
1109 operands.push_back(loopNode.getMaxIterations());
1110 }
1111 if (loopNode.getIterationMultiple() > 1) {
1112 control = control | spv::LoopControlIterationMultipleMask;
1113 operands.push_back(loopNode.getIterationMultiple());
1114 }
1115 if (loopNode.getPeelCount() > 0) {
1116 control = control | spv::LoopControlPeelCountMask;
1117 operands.push_back(loopNode.getPeelCount());
1118 }
1119 if (loopNode.getPartialCount() > 0) {
1120 control = control | spv::LoopControlPartialCountMask;
1121 operands.push_back(loopNode.getPartialCount());
1122 }
John Kessenicha2858d92018-01-31 08:11:18 -07001123 }
John Kesseniche18fd202018-01-30 11:01:39 -07001124
1125 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001126}
1127
John Kessenicha5c5fb62017-05-05 05:09:58 -06001128// Translate glslang type to SPIR-V storage class.
1129spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1130{
1131 if (type.getQualifier().isPipeInput())
1132 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001133 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001134 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001135
1136 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1137 type.getQualifier().storage == glslang::EvqUniform) {
1138 if (type.getBasicType() == glslang::EbtAtomicUint)
1139 return spv::StorageClassAtomicCounter;
1140 if (type.containsOpaque())
1141 return spv::StorageClassUniformConstant;
1142 }
1143
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001144#ifdef NV_EXTENSIONS
1145 if (type.getQualifier().isUniformOrBuffer() &&
1146 type.getQualifier().layoutShaderRecordNV) {
1147 return spv::StorageClassShaderRecordBufferNV;
1148 }
1149#endif
1150
John Kessenichbed4e4f2017-09-08 02:38:07 -06001151 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001152 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001153 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001154 }
1155
1156 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001157 if (type.getQualifier().layoutPushConstant)
1158 return spv::StorageClassPushConstant;
1159 if (type.getBasicType() == glslang::EbtBlock)
1160 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001161 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001162 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001163
1164 switch (type.getQualifier().storage) {
1165 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1166 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1167 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1168 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001169#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001170 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1171 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1172 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1173 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1174 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001175#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001176 default:
1177 assert(0);
1178 break;
1179 }
1180
1181 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001182}
1183
John Kessenich5611c6d2018-04-05 11:25:02 -06001184// Add capabilities pertaining to how an array is indexed.
1185void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1186 const glslang::TType& indexType)
1187{
1188 if (indexType.getQualifier().isNonUniform()) {
1189 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001190 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001191 if (baseType.getBasicType() == glslang::EbtSampler) {
1192 if (baseType.getQualifier().hasAttachment())
1193 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1194 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1195 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1196 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1197 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1198 else if (baseType.isImage())
1199 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1200 else if (baseType.isTexture())
1201 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1202 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1203 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1204 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1205 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1206 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1207 }
1208 } else {
1209 // assume a dynamically uniform index
1210 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001211 if (baseType.getQualifier().hasAttachment()) {
1212 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001213 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001214 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1215 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001216 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001217 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1218 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001219 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001220 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001221 }
1222 }
1223}
1224
qining25262b32016-05-06 17:25:16 -04001225// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001226// descriptor set.
1227bool IsDescriptorResource(const glslang::TType& type)
1228{
John Kessenichf7497e22016-03-08 21:36:22 -07001229 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001230 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001231 return type.getQualifier().isUniformOrBuffer() &&
1232#ifdef NV_EXTENSIONS
1233 ! type.getQualifier().layoutShaderRecordNV &&
1234#endif
1235 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001236
1237 // non block...
1238 // basically samplerXXX/subpass/sampler/texture are all included
1239 // if they are the global-scope-class, not the function parameter
1240 // (or local, if they ever exist) class.
1241 if (type.getBasicType() == glslang::EbtSampler)
1242 return type.getQualifier().isUniformOrBuffer();
1243
1244 // None of the above.
1245 return false;
1246}
1247
John Kesseniche0b6cad2015-12-24 10:30:13 -07001248void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1249{
1250 if (child.layoutMatrix == glslang::ElmNone)
1251 child.layoutMatrix = parent.layoutMatrix;
1252
1253 if (parent.invariant)
1254 child.invariant = true;
1255 if (parent.nopersp)
1256 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001257#ifdef AMD_EXTENSIONS
1258 if (parent.explicitInterp)
1259 child.explicitInterp = true;
1260#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001261 if (parent.flat)
1262 child.flat = true;
1263 if (parent.centroid)
1264 child.centroid = true;
1265 if (parent.patch)
1266 child.patch = true;
1267 if (parent.sample)
1268 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001269 if (parent.coherent)
1270 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001271 if (parent.devicecoherent)
1272 child.devicecoherent = true;
1273 if (parent.queuefamilycoherent)
1274 child.queuefamilycoherent = true;
1275 if (parent.workgroupcoherent)
1276 child.workgroupcoherent = true;
1277 if (parent.subgroupcoherent)
1278 child.subgroupcoherent = true;
1279 if (parent.nonprivate)
1280 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001281 if (parent.volatil)
1282 child.volatil = true;
1283 if (parent.restrict)
1284 child.restrict = true;
1285 if (parent.readonly)
1286 child.readonly = true;
1287 if (parent.writeonly)
1288 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001289#ifdef NV_EXTENSIONS
1290 if (parent.perPrimitiveNV)
1291 child.perPrimitiveNV = true;
1292 if (parent.perViewNV)
1293 child.perViewNV = true;
1294 if (parent.perTaskNV)
1295 child.perTaskNV = true;
1296#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001297}
1298
John Kessenichf2b7f332016-09-01 17:05:23 -06001299bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001300{
John Kessenich7b9fa252016-01-21 18:56:57 -07001301 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001302 // - struct members might inherit from a struct declaration
1303 // (note that non-block structs don't explicitly inherit,
1304 // only implicitly, meaning no decoration involved)
1305 // - affect decorations on the struct members
1306 // (note smooth does not, and expecting something like volatile
1307 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001308 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001309 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001310}
1311
John Kessenich140f3df2015-06-26 16:58:36 -06001312//
1313// Implement the TGlslangToSpvTraverser class.
1314//
1315
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001316TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001317 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1318 : TIntermTraverser(true, false, true),
1319 options(options),
1320 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001321 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001322 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001323 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001324 glslangIntermediate(glslangIntermediate),
1325 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001326{
1327 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1328
1329 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001330 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1331 glslangIntermediate->getVersion());
1332
John Kessenich121853f2017-05-31 17:11:16 -06001333 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001334 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001335 builder.setSourceFile(glslangIntermediate->getSourceFile());
1336
1337 // Set the source shader's text. If for SPV version 1.0, include
1338 // a preamble in comments stating the OpModuleProcessed instructions.
1339 // Otherwise, emit those as actual instructions.
1340 std::string text;
1341 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1342 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001343 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001344 text.append("// OpModuleProcessed ");
1345 text.append(processes[p]);
1346 text.append("\n");
1347 } else
1348 builder.addModuleProcessed(processes[p]);
1349 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001350 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001351 text.append("#line 1\n");
1352 text.append(glslangIntermediate->getSourceText());
1353 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001354 // Pass name and text for all included files
1355 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1356 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1357 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001358 }
John Kessenich140f3df2015-06-26 16:58:36 -06001359 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001360
1361 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1362 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1363
1364 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1365 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1366 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1367 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1368 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001369 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001370 memoryModel = spv::MemoryModelVulkanKHR;
1371 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001372 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001373 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001374 builder.setMemoryModel(addressingModel, memoryModel);
1375
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001376 if (glslangIntermediate->usingVariablePointers()) {
1377 builder.addCapability(spv::CapabilityVariablePointers);
1378 }
1379
John Kessenicheee9d532016-09-19 18:09:30 -06001380 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1381 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001382
1383 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001384 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1385 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001386 builder.addSourceExtension(it->c_str());
1387
1388 // Add the top-level modes for this shader.
1389
John Kessenich92187592016-02-01 13:45:25 -07001390 if (glslangIntermediate->getXfbMode()) {
1391 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001392 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001393 }
John Kessenich140f3df2015-06-26 16:58:36 -06001394
1395 unsigned int mode;
1396 switch (glslangIntermediate->getStage()) {
1397 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001398 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001399 break;
1400
steve-lunarge7412492017-03-23 11:56:07 -06001401 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001402 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001403 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001404
steve-lunarge7412492017-03-23 11:56:07 -06001405 glslang::TLayoutGeometry primitive;
1406
1407 if (glslangIntermediate->getStage() == EShLangTessControl) {
1408 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1409 primitive = glslangIntermediate->getOutputPrimitive();
1410 } else {
1411 primitive = glslangIntermediate->getInputPrimitive();
1412 }
1413
1414 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001415 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1416 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1417 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001418 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001419 }
John Kessenich4016e382016-07-15 11:53:56 -06001420 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001421 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1422
John Kesseniche6903322015-10-13 16:29:02 -06001423 switch (glslangIntermediate->getVertexSpacing()) {
1424 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1425 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1426 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001427 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001428 }
John Kessenich4016e382016-07-15 11:53:56 -06001429 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001430 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1431
1432 switch (glslangIntermediate->getVertexOrder()) {
1433 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1434 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001435 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001436 }
John Kessenich4016e382016-07-15 11:53:56 -06001437 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001438 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1439
1440 if (glslangIntermediate->getPointMode())
1441 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001442 break;
1443
1444 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001445 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001446 switch (glslangIntermediate->getInputPrimitive()) {
1447 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1448 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1449 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001450 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001451 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001452 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001453 }
John Kessenich4016e382016-07-15 11:53:56 -06001454 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001455 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001456
John Kessenich140f3df2015-06-26 16:58:36 -06001457 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1458
1459 switch (glslangIntermediate->getOutputPrimitive()) {
1460 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1461 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1462 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001463 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001464 }
John Kessenich4016e382016-07-15 11:53:56 -06001465 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001466 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1468 break;
1469
1470 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001471 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001472 if (glslangIntermediate->getPixelCenterInteger())
1473 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001474
John Kessenich140f3df2015-06-26 16:58:36 -06001475 if (glslangIntermediate->getOriginUpperLeft())
1476 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001477 else
1478 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001479
1480 if (glslangIntermediate->getEarlyFragmentTests())
1481 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1482
chaocc1204522017-06-30 17:14:30 -07001483 if (glslangIntermediate->getPostDepthCoverage()) {
1484 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1485 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1486 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1487 }
1488
John Kesseniche6903322015-10-13 16:29:02 -06001489 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001490 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1491 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001492 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001493 }
John Kessenich4016e382016-07-15 11:53:56 -06001494 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001495 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1496
1497 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1498 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05001499
1500 switch (glslangIntermediate->getInterlockOrdering()) {
1501 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1502 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1503 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1504 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1505 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1506 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1507 default: mode = spv::ExecutionModeMax; break;
1508 }
1509 if (mode != spv::ExecutionModeMax) {
1510 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1511 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1512 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1513 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1514 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1515 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1516 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1517 } else {
1518 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1519 }
1520 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1521 }
1522
John Kessenich140f3df2015-06-26 16:58:36 -06001523 break;
1524
1525 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001526 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1528 glslangIntermediate->getLocalSize(1),
1529 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001530#ifdef NV_EXTENSIONS
1531 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1532 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1533 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1534 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1535 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1536 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1537 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1538 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1539 }
1540#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001541 break;
1542
Chao Chen3c366992018-09-19 11:41:59 -07001543#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001544 case EShLangRayGenNV:
1545 case EShLangIntersectNV:
1546 case EShLangAnyHitNV:
1547 case EShLangClosestHitNV:
1548 case EShLangMissNV:
1549 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001550 builder.addCapability(spv::CapabilityRayTracingNV);
1551 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001552 break;
Chao Chen3c366992018-09-19 11:41:59 -07001553 case EShLangTaskNV:
1554 case EShLangMeshNV:
1555 builder.addCapability(spv::CapabilityMeshShadingNV);
1556 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1557 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1558 glslangIntermediate->getLocalSize(1),
1559 glslangIntermediate->getLocalSize(2));
1560 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1561 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1562 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1563
1564 switch (glslangIntermediate->getOutputPrimitive()) {
1565 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1566 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1567 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1568 default: mode = spv::ExecutionModeMax; break;
1569 }
1570 if (mode != spv::ExecutionModeMax)
1571 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1572 }
1573 break;
1574#endif
1575
John Kessenich140f3df2015-06-26 16:58:36 -06001576 default:
1577 break;
1578 }
John Kessenich140f3df2015-06-26 16:58:36 -06001579}
1580
John Kessenichfca82622016-11-26 13:23:20 -07001581// Finish creating SPV, after the traversal is complete.
1582void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001583{
John Kessenichf04c51b2018-08-03 15:56:12 -06001584 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001585 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001586 builder.setBuildPoint(shaderEntry->getLastBlock());
1587 builder.leaveFunction();
1588 }
1589
John Kessenich7ba63412015-12-20 17:37:07 -07001590 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001591 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1592 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001593
John Kessenichf04c51b2018-08-03 15:56:12 -06001594 // Add capabilities, extensions, remove unneeded decorations, etc.,
1595 // based on the resulting SPIR-V.
1596 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001597}
1598
John Kessenichfca82622016-11-26 13:23:20 -07001599// Write the SPV into 'out'.
1600void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001601{
John Kessenichfca82622016-11-26 13:23:20 -07001602 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001603}
1604
1605//
1606// Implement the traversal functions.
1607//
1608// Return true from interior nodes to have the external traversal
1609// continue on to children. Return false if children were
1610// already processed.
1611//
1612
1613//
qining25262b32016-05-06 17:25:16 -04001614// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001615// - uniform/input reads
1616// - output writes
1617// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1618// - something simple that degenerates into the last bullet
1619//
1620void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1621{
qining75d1d802016-04-06 14:42:01 -04001622 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1623 if (symbol->getType().getQualifier().isSpecConstant())
1624 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1625
John Kessenich140f3df2015-06-26 16:58:36 -06001626 // getSymbolId() will set up all the IO decorations on the first call.
1627 // Formal function parameters were mapped during makeFunctions().
1628 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001629
John Kessenich7ba63412015-12-20 17:37:07 -07001630 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001631 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001632 // Consider adding to the OpEntryPoint interface list.
1633 // Only looking at structures if they have at least one member.
1634 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1635 spv::StorageClass sc = builder.getStorageClass(id);
1636 // Before SPIR-V 1.4, we only want to include Input and Output.
1637 // Starting with SPIR-V 1.4, we want all globals.
1638 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1639 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001640 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001641 }
John Kessenich5f77d862017-09-19 11:09:59 -06001642 }
John Kessenich9c14f772019-06-17 08:38:35 -06001643
1644 // If the SPIR-V type is required to be different than the AST type,
1645 // translate now from the SPIR-V type to the AST type, for the consuming
1646 // operation.
1647 // Note this turns it from an l-value to an r-value.
1648 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1649 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1650 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001651 }
1652
1653 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001654 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001655 // Prepare to generate code for the access
1656
1657 // L-value chains will be computed left to right. We're on the symbol now,
1658 // which is the left-most part of the access chain, so now is "clear" time,
1659 // followed by setting the base.
1660 builder.clearAccessChain();
1661
1662 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001663 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001664 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001665 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001666 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001667 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001668 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001669 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001670 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1671 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001672 builder.setAccessChainRValue(id);
1673 else
1674 builder.setAccessChainLValue(id);
1675 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001676
1677 // Process linkage-only nodes for any special additional interface work.
1678 if (linkageOnly) {
1679 if (glslangIntermediate->getHlslFunctionality1()) {
1680 // Map implicit counter buffers to their originating buffers, which should have been
1681 // seen by now, given earlier pruning of unused counters, and preservation of order
1682 // of declaration.
1683 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1684 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1685 // Save possible originating buffers for counter buffers, keyed by
1686 // making the potential counter-buffer name.
1687 std::string keyName = symbol->getName().c_str();
1688 keyName = glslangIntermediate->addCounterBufferName(keyName);
1689 counterOriginator[keyName] = symbol;
1690 } else {
1691 // Handle a counter buffer, by finding the saved originating buffer.
1692 std::string keyName = symbol->getName().c_str();
1693 auto it = counterOriginator.find(keyName);
1694 if (it != counterOriginator.end()) {
1695 id = getSymbolId(it->second);
1696 if (id != spv::NoResult) {
1697 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001698 if (counterId != spv::NoResult) {
1699 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001700 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001701 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001702 }
1703 }
1704 }
1705 }
1706 }
1707 }
John Kessenich140f3df2015-06-26 16:58:36 -06001708}
1709
1710bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1711{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001712 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001713
qining40887662016-04-03 22:20:42 -04001714 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1715 if (node->getType().getQualifier().isSpecConstant())
1716 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1717
John Kessenich140f3df2015-06-26 16:58:36 -06001718 // First, handle special cases
1719 switch (node->getOp()) {
1720 case glslang::EOpAssign:
1721 case glslang::EOpAddAssign:
1722 case glslang::EOpSubAssign:
1723 case glslang::EOpMulAssign:
1724 case glslang::EOpVectorTimesMatrixAssign:
1725 case glslang::EOpVectorTimesScalarAssign:
1726 case glslang::EOpMatrixTimesScalarAssign:
1727 case glslang::EOpMatrixTimesMatrixAssign:
1728 case glslang::EOpDivAssign:
1729 case glslang::EOpModAssign:
1730 case glslang::EOpAndAssign:
1731 case glslang::EOpInclusiveOrAssign:
1732 case glslang::EOpExclusiveOrAssign:
1733 case glslang::EOpLeftShiftAssign:
1734 case glslang::EOpRightShiftAssign:
1735 // A bin-op assign "a += b" means the same thing as "a = a + b"
1736 // where a is evaluated before b. For a simple assignment, GLSL
1737 // says to evaluate the left before the right. So, always, left
1738 // node then right node.
1739 {
1740 // get the left l-value, save it away
1741 builder.clearAccessChain();
1742 node->getLeft()->traverse(this);
1743 spv::Builder::AccessChain lValue = builder.getAccessChain();
1744
1745 // evaluate the right
1746 builder.clearAccessChain();
1747 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001748 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001749
1750 if (node->getOp() != glslang::EOpAssign) {
1751 // the left is also an r-value
1752 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001753 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001754
1755 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001756 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001757 TranslateNoContractionDecoration(node->getType().getQualifier()),
1758 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001759 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001760 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1761 node->getType().getBasicType());
1762
1763 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001764 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001765 }
1766
1767 // store the result
1768 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001769 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001770
1771 // assignments are expressions having an rValue after they are evaluated...
1772 builder.clearAccessChain();
1773 builder.setAccessChainRValue(rValue);
1774 }
1775 return false;
1776 case glslang::EOpIndexDirect:
1777 case glslang::EOpIndexDirectStruct:
1778 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001779 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001780 // Get the left part of the access chain.
1781 node->getLeft()->traverse(this);
1782
1783 // Add the next element in the chain
1784
David Netoa901ffe2016-06-08 14:11:40 +01001785 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001786 if (! node->getLeft()->getType().isArray() &&
1787 node->getLeft()->getType().isVector() &&
1788 node->getOp() == glslang::EOpIndexDirect) {
1789 // This is essentially a hard-coded vector swizzle of size 1,
1790 // so short circuit the access-chain stuff with a swizzle.
1791 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001792 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001793 int dummySize;
1794 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1795 TranslateCoherent(node->getLeft()->getType()),
1796 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001797 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001798
1799 // Load through a block reference is performed with a dot operator that
1800 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1801 // do a load and reset the access chain.
1802 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1803 !node->getLeft()->getType().isArray() &&
1804 node->getOp() == glslang::EOpIndexDirectStruct)
1805 {
1806 spv::Id left = accessChainLoad(node->getLeft()->getType());
1807 builder.clearAccessChain();
1808 builder.setAccessChainLValue(left);
1809 }
1810
David Netoa901ffe2016-06-08 14:11:40 +01001811 int spvIndex = glslangIndex;
1812 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1813 node->getOp() == glslang::EOpIndexDirectStruct)
1814 {
1815 // This may be, e.g., an anonymous block-member selection, which generally need
1816 // index remapping due to hidden members in anonymous blocks.
1817 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1818 assert(remapper.size() > 0);
1819 spvIndex = remapper[glslangIndex];
1820 }
John Kessenichebb50532016-05-16 19:22:05 -06001821
David Netoa901ffe2016-06-08 14:11:40 +01001822 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001823 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001824
1825 // Add capabilities here for accessing PointSize and clip/cull distance.
1826 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001827 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001828 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001829 }
1830 }
1831 return false;
1832 case glslang::EOpIndexIndirect:
1833 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001834 // Array, matrix, or vector indirection with variable index.
1835 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001836 // matrices are arrays of vectors, so will also work for a matrix.
1837 // Will use the access chain's 'component' for variable index into a vector.
1838
1839 // This adapter is building access chains left to right.
1840 // Set up the access chain to the left.
1841 node->getLeft()->traverse(this);
1842
1843 // save it so that computing the right side doesn't trash it
1844 spv::Builder::AccessChain partial = builder.getAccessChain();
1845
1846 // compute the next index in the chain
1847 builder.clearAccessChain();
1848 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001849 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001850
John Kessenich5611c6d2018-04-05 11:25:02 -06001851 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1852
John Kessenich140f3df2015-06-26 16:58:36 -06001853 // restore the saved access chain
1854 builder.setAccessChain(partial);
1855
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001856 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1857 int dummySize;
1858 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1859 TranslateCoherent(node->getLeft()->getType()),
1860 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1861 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001862 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001863 }
1864 return false;
1865 case glslang::EOpVectorSwizzle:
1866 {
1867 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001868 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001869 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001870 int dummySize;
1871 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1872 TranslateCoherent(node->getLeft()->getType()),
1873 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001874 }
1875 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001876 case glslang::EOpMatrixSwizzle:
1877 logger->missingFunctionality("matrix swizzle");
1878 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001879 case glslang::EOpLogicalOr:
1880 case glslang::EOpLogicalAnd:
1881 {
1882
1883 // These may require short circuiting, but can sometimes be done as straight
1884 // binary operations. The right operand must be short circuited if it has
1885 // side effects, and should probably be if it is complex.
1886 if (isTrivial(node->getRight()->getAsTyped()))
1887 break; // handle below as a normal binary operation
1888 // otherwise, we need to do dynamic short circuiting on the right operand
1889 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1890 builder.clearAccessChain();
1891 builder.setAccessChainRValue(result);
1892 }
1893 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001894 default:
1895 break;
1896 }
1897
1898 // Assume generic binary op...
1899
John Kessenich32cfd492016-02-02 12:37:46 -07001900 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001901 builder.clearAccessChain();
1902 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001903 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001904
John Kessenich32cfd492016-02-02 12:37:46 -07001905 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001906 builder.clearAccessChain();
1907 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001908 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001909
John Kessenich32cfd492016-02-02 12:37:46 -07001910 // get result
John Kessenichead86222018-03-28 18:01:20 -06001911 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001912 TranslateNoContractionDecoration(node->getType().getQualifier()),
1913 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001914 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001915 convertGlslangToSpvType(node->getType()), left, right,
1916 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001917
John Kessenich50e57562015-12-21 21:21:11 -07001918 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001919 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001920 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001921 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001922 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001923 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001924 return false;
1925 }
John Kessenich140f3df2015-06-26 16:58:36 -06001926}
1927
John Kessenich9c14f772019-06-17 08:38:35 -06001928// Figure out what, if any, type changes are needed when accessing a specific built-in.
1929// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1930// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1931std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1932 const glslang::TType& glslangType)
1933{
1934 switch(builtIn)
1935 {
1936 case spv::BuiltInSubgroupEqMask:
1937 case spv::BuiltInSubgroupGeMask:
1938 case spv::BuiltInSubgroupGtMask:
1939 case spv::BuiltInSubgroupLeMask:
1940 case spv::BuiltInSubgroupLtMask: {
1941 // these require changing a 64-bit scaler -> a vector of 32-bit components
1942 if (glslangType.isVector())
1943 break;
1944 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1945 builder.makeUintType(64));
1946 return ret;
1947 }
1948 default:
1949 break;
1950 }
1951
1952 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1953 return ret;
1954}
1955
1956// For an object previously identified (see getForcedType() and forceType)
1957// as needing type translations, do the translation needed for a load, turning
1958// an L-value into in R-value.
1959spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
1960{
1961 const auto forceIt = forceType.find(object);
1962 if (forceIt == forceType.end())
1963 return object;
1964
1965 spv::Id desiredTypeId = forceIt->second;
1966 spv::Id objectTypeId = builder.getTypeId(object);
1967 assert(builder.isPointerType(objectTypeId));
1968 objectTypeId = builder.getContainedTypeId(objectTypeId);
1969 if (builder.isVectorType(objectTypeId) &&
1970 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
1971 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
1972 // handle 32-bit v.xy* -> 64-bit
1973 builder.clearAccessChain();
1974 builder.setAccessChainLValue(object);
1975 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
1976 std::vector<spv::Id> components;
1977 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
1978 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
1979
1980 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
1981 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
1982 builder.createCompositeConstruct(vecType, components));
1983 } else {
1984 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
1985 }
1986 } else {
1987 logger->missingFunctionality("forcing non 32-bit vector type");
1988 }
1989
1990 return object;
1991}
1992
John Kessenich140f3df2015-06-26 16:58:36 -06001993bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1994{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001995 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001996
qining40887662016-04-03 22:20:42 -04001997 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1998 if (node->getType().getQualifier().isSpecConstant())
1999 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2000
John Kessenichfc51d282015-08-19 13:34:18 -06002001 spv::Id result = spv::NoResult;
2002
2003 // try texturing first
2004 result = createImageTextureFunctionCall(node);
2005 if (result != spv::NoResult) {
2006 builder.clearAccessChain();
2007 builder.setAccessChainRValue(result);
2008
2009 return false; // done with this node
2010 }
2011
2012 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002013
2014 if (node->getOp() == glslang::EOpArrayLength) {
2015 // Quite special; won't want to evaluate the operand.
2016
John Kessenich5611c6d2018-04-05 11:25:02 -06002017 // Currently, the front-end does not allow .length() on an array until it is sized,
2018 // except for the last block membeor of an SSBO.
2019 // TODO: If this changes, link-time sized arrays might show up here, and need their
2020 // size extracted.
2021
John Kessenichc9a80832015-09-12 12:17:44 -06002022 // Normal .length() would have been constant folded by the front-end.
2023 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002024 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002025
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002026 spv::Id length;
2027 if (node->getOperand()->getType().isCoopMat()) {
2028 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2029
2030 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2031 assert(builder.isCooperativeMatrixType(typeId));
2032
2033 length = builder.createCooperativeMatrixLength(typeId);
2034 } else {
2035 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2036 block->traverse(this);
2037 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2038 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2039 }
John Kessenichc9a80832015-09-12 12:17:44 -06002040
John Kessenich8c869672018-11-28 07:01:37 -07002041 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2042 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2043 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002044 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2045 if (builder.isInSpecConstCodeGenMode()) {
2046 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2047 } else {
2048 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2049 }
2050 }
John Kessenich8c869672018-11-28 07:01:37 -07002051
John Kessenichc9a80832015-09-12 12:17:44 -06002052 builder.clearAccessChain();
2053 builder.setAccessChainRValue(length);
2054
2055 return false;
2056 }
2057
John Kessenichfc51d282015-08-19 13:34:18 -06002058 // Start by evaluating the operand
2059
John Kessenich8c8505c2016-07-26 12:50:38 -06002060 // Does it need a swizzle inversion? If so, evaluation is inverted;
2061 // operate first on the swizzle base, then apply the swizzle.
2062 spv::Id invertedType = spv::NoType;
2063 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2064 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2065 invertedType = getInvertedSwizzleType(*node->getOperand());
2066
John Kessenich140f3df2015-06-26 16:58:36 -06002067 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002068 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002069 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002070 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002071 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002072 operandNode = node->getOperand();
2073
2074 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002075
Rex Xufc618912015-09-09 16:42:49 +08002076 spv::Id operand = spv::NoResult;
2077
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002078 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2079
Rex Xufc618912015-09-09 16:42:49 +08002080 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2081 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002082 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002083 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002084 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002085 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2086 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2087 } else
John Kessenich32cfd492016-02-02 12:37:46 -07002088 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002089
John Kessenichead86222018-03-28 18:01:20 -06002090 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002091 TranslateNoContractionDecoration(node->getType().getQualifier()),
2092 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002093
2094 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002095 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002096 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002097
2098 // if not, then possibly an operation
2099 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002100 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002101
2102 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002103 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002104 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002105 builder.addDecoration(result, decorations.nonUniform);
2106 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002107
John Kessenich140f3df2015-06-26 16:58:36 -06002108 builder.clearAccessChain();
2109 builder.setAccessChainRValue(result);
2110
2111 return false; // done with this node
2112 }
2113
2114 // it must be a special case, check...
2115 switch (node->getOp()) {
2116 case glslang::EOpPostIncrement:
2117 case glslang::EOpPostDecrement:
2118 case glslang::EOpPreIncrement:
2119 case glslang::EOpPreDecrement:
2120 {
2121 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002122 spv::Id one = 0;
2123 if (node->getBasicType() == glslang::EbtFloat)
2124 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08002125 else if (node->getBasicType() == glslang::EbtDouble)
2126 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002127 else if (node->getBasicType() == glslang::EbtFloat16)
2128 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002129 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2130 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002131 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2132 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002133 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2134 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002135 else
2136 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002137 glslang::TOperator op;
2138 if (node->getOp() == glslang::EOpPreIncrement ||
2139 node->getOp() == glslang::EOpPostIncrement)
2140 op = glslang::EOpAdd;
2141 else
2142 op = glslang::EOpSub;
2143
John Kessenichead86222018-03-28 18:01:20 -06002144 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002145 convertGlslangToSpvType(node->getType()), operand, one,
2146 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002147 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002148
2149 // The result of operation is always stored, but conditionally the
2150 // consumed result. The consumed result is always an r-value.
2151 builder.accessChainStore(result);
2152 builder.clearAccessChain();
2153 if (node->getOp() == glslang::EOpPreIncrement ||
2154 node->getOp() == glslang::EOpPreDecrement)
2155 builder.setAccessChainRValue(result);
2156 else
2157 builder.setAccessChainRValue(operand);
2158 }
2159
2160 return false;
2161
2162 case glslang::EOpEmitStreamVertex:
2163 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2164 return false;
2165 case glslang::EOpEndStreamPrimitive:
2166 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2167 return false;
2168
2169 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002170 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002171 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002172 }
John Kessenich140f3df2015-06-26 16:58:36 -06002173}
2174
2175bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2176{
qining27e04a02016-04-14 16:40:20 -04002177 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2178 if (node->getType().getQualifier().isSpecConstant())
2179 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2180
John Kessenichfc51d282015-08-19 13:34:18 -06002181 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002182 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2183 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002184
2185 // try texturing
2186 result = createImageTextureFunctionCall(node);
2187 if (result != spv::NoResult) {
2188 builder.clearAccessChain();
2189 builder.setAccessChainRValue(result);
2190
2191 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002192 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002193#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002194 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002195#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002196 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002197 // "imageStore" is a special case, which has no result
2198 return false;
2199 }
John Kessenichfc51d282015-08-19 13:34:18 -06002200
John Kessenich140f3df2015-06-26 16:58:36 -06002201 glslang::TOperator binOp = glslang::EOpNull;
2202 bool reduceComparison = true;
2203 bool isMatrix = false;
2204 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002205 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002206
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002207 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2208
John Kessenich140f3df2015-06-26 16:58:36 -06002209 assert(node->getOp());
2210
John Kessenichf6640762016-08-01 19:44:00 -06002211 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002212
2213 switch (node->getOp()) {
2214 case glslang::EOpSequence:
2215 {
2216 if (preVisit)
2217 ++sequenceDepth;
2218 else
2219 --sequenceDepth;
2220
2221 if (sequenceDepth == 1) {
2222 // If this is the parent node of all the functions, we want to see them
2223 // early, so all call points have actual SPIR-V functions to reference.
2224 // In all cases, still let the traverser visit the children for us.
2225 makeFunctions(node->getAsAggregate()->getSequence());
2226
John Kessenich6fccb3c2016-09-19 16:01:41 -06002227 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002228 // anything else gets there, so visit out of order, doing them all now.
2229 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2230
John Kessenich6a60c2f2016-12-08 21:01:59 -07002231 // 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 -06002232 // so do them manually.
2233 visitFunctions(node->getAsAggregate()->getSequence());
2234
2235 return false;
2236 }
2237
2238 return true;
2239 }
2240 case glslang::EOpLinkerObjects:
2241 {
2242 if (visit == glslang::EvPreVisit)
2243 linkageOnly = true;
2244 else
2245 linkageOnly = false;
2246
2247 return true;
2248 }
2249 case glslang::EOpComma:
2250 {
2251 // processing from left to right naturally leaves the right-most
2252 // lying around in the access chain
2253 glslang::TIntermSequence& glslangOperands = node->getSequence();
2254 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2255 glslangOperands[i]->traverse(this);
2256
2257 return false;
2258 }
2259 case glslang::EOpFunction:
2260 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002261 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002262 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002263 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002264 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002265 } else {
2266 handleFunctionEntry(node);
2267 }
2268 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002269 if (inEntryPoint)
2270 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002271 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002272 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002273 }
2274
2275 return true;
2276 case glslang::EOpParameters:
2277 // Parameters will have been consumed by EOpFunction processing, but not
2278 // the body, so we still visited the function node's children, making this
2279 // child redundant.
2280 return false;
2281 case glslang::EOpFunctionCall:
2282 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002283 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002284 if (node->isUserDefined())
2285 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002286 // 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 -07002287 if (result) {
2288 builder.clearAccessChain();
2289 builder.setAccessChainRValue(result);
2290 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002291 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002292
2293 return false;
2294 }
2295 case glslang::EOpConstructMat2x2:
2296 case glslang::EOpConstructMat2x3:
2297 case glslang::EOpConstructMat2x4:
2298 case glslang::EOpConstructMat3x2:
2299 case glslang::EOpConstructMat3x3:
2300 case glslang::EOpConstructMat3x4:
2301 case glslang::EOpConstructMat4x2:
2302 case glslang::EOpConstructMat4x3:
2303 case glslang::EOpConstructMat4x4:
2304 case glslang::EOpConstructDMat2x2:
2305 case glslang::EOpConstructDMat2x3:
2306 case glslang::EOpConstructDMat2x4:
2307 case glslang::EOpConstructDMat3x2:
2308 case glslang::EOpConstructDMat3x3:
2309 case glslang::EOpConstructDMat3x4:
2310 case glslang::EOpConstructDMat4x2:
2311 case glslang::EOpConstructDMat4x3:
2312 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002313 case glslang::EOpConstructIMat2x2:
2314 case glslang::EOpConstructIMat2x3:
2315 case glslang::EOpConstructIMat2x4:
2316 case glslang::EOpConstructIMat3x2:
2317 case glslang::EOpConstructIMat3x3:
2318 case glslang::EOpConstructIMat3x4:
2319 case glslang::EOpConstructIMat4x2:
2320 case glslang::EOpConstructIMat4x3:
2321 case glslang::EOpConstructIMat4x4:
2322 case glslang::EOpConstructUMat2x2:
2323 case glslang::EOpConstructUMat2x3:
2324 case glslang::EOpConstructUMat2x4:
2325 case glslang::EOpConstructUMat3x2:
2326 case glslang::EOpConstructUMat3x3:
2327 case glslang::EOpConstructUMat3x4:
2328 case glslang::EOpConstructUMat4x2:
2329 case glslang::EOpConstructUMat4x3:
2330 case glslang::EOpConstructUMat4x4:
2331 case glslang::EOpConstructBMat2x2:
2332 case glslang::EOpConstructBMat2x3:
2333 case glslang::EOpConstructBMat2x4:
2334 case glslang::EOpConstructBMat3x2:
2335 case glslang::EOpConstructBMat3x3:
2336 case glslang::EOpConstructBMat3x4:
2337 case glslang::EOpConstructBMat4x2:
2338 case glslang::EOpConstructBMat4x3:
2339 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002340 case glslang::EOpConstructF16Mat2x2:
2341 case glslang::EOpConstructF16Mat2x3:
2342 case glslang::EOpConstructF16Mat2x4:
2343 case glslang::EOpConstructF16Mat3x2:
2344 case glslang::EOpConstructF16Mat3x3:
2345 case glslang::EOpConstructF16Mat3x4:
2346 case glslang::EOpConstructF16Mat4x2:
2347 case glslang::EOpConstructF16Mat4x3:
2348 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002349 isMatrix = true;
2350 // fall through
2351 case glslang::EOpConstructFloat:
2352 case glslang::EOpConstructVec2:
2353 case glslang::EOpConstructVec3:
2354 case glslang::EOpConstructVec4:
2355 case glslang::EOpConstructDouble:
2356 case glslang::EOpConstructDVec2:
2357 case glslang::EOpConstructDVec3:
2358 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002359 case glslang::EOpConstructFloat16:
2360 case glslang::EOpConstructF16Vec2:
2361 case glslang::EOpConstructF16Vec3:
2362 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002363 case glslang::EOpConstructBool:
2364 case glslang::EOpConstructBVec2:
2365 case glslang::EOpConstructBVec3:
2366 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002367 case glslang::EOpConstructInt8:
2368 case glslang::EOpConstructI8Vec2:
2369 case glslang::EOpConstructI8Vec3:
2370 case glslang::EOpConstructI8Vec4:
2371 case glslang::EOpConstructUint8:
2372 case glslang::EOpConstructU8Vec2:
2373 case glslang::EOpConstructU8Vec3:
2374 case glslang::EOpConstructU8Vec4:
2375 case glslang::EOpConstructInt16:
2376 case glslang::EOpConstructI16Vec2:
2377 case glslang::EOpConstructI16Vec3:
2378 case glslang::EOpConstructI16Vec4:
2379 case glslang::EOpConstructUint16:
2380 case glslang::EOpConstructU16Vec2:
2381 case glslang::EOpConstructU16Vec3:
2382 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002383 case glslang::EOpConstructInt:
2384 case glslang::EOpConstructIVec2:
2385 case glslang::EOpConstructIVec3:
2386 case glslang::EOpConstructIVec4:
2387 case glslang::EOpConstructUint:
2388 case glslang::EOpConstructUVec2:
2389 case glslang::EOpConstructUVec3:
2390 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002391 case glslang::EOpConstructInt64:
2392 case glslang::EOpConstructI64Vec2:
2393 case glslang::EOpConstructI64Vec3:
2394 case glslang::EOpConstructI64Vec4:
2395 case glslang::EOpConstructUint64:
2396 case glslang::EOpConstructU64Vec2:
2397 case glslang::EOpConstructU64Vec3:
2398 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002399 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002400 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002401 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002402 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002403 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002404 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002405 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002406 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002407 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002408 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002409 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002410 else if (node->getOp() == glslang::EOpConstructStruct ||
2411 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2412 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002413 std::vector<spv::Id> constituents;
2414 for (int c = 0; c < (int)arguments.size(); ++c)
2415 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002416 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002417 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002418 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002419 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002420 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002421
2422 builder.clearAccessChain();
2423 builder.setAccessChainRValue(constructed);
2424
2425 return false;
2426 }
2427
2428 // These six are component-wise compares with component-wise results.
2429 // Forward on to createBinaryOperation(), requesting a vector result.
2430 case glslang::EOpLessThan:
2431 case glslang::EOpGreaterThan:
2432 case glslang::EOpLessThanEqual:
2433 case glslang::EOpGreaterThanEqual:
2434 case glslang::EOpVectorEqual:
2435 case glslang::EOpVectorNotEqual:
2436 {
2437 // Map the operation to a binary
2438 binOp = node->getOp();
2439 reduceComparison = false;
2440 switch (node->getOp()) {
2441 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2442 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2443 default: binOp = node->getOp(); break;
2444 }
2445
2446 break;
2447 }
2448 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002449 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002450 binOp = glslang::EOpMul;
2451 break;
2452 case glslang::EOpOuterProduct:
2453 // two vectors multiplied to make a matrix
2454 binOp = glslang::EOpOuterProduct;
2455 break;
2456 case glslang::EOpDot:
2457 {
qining25262b32016-05-06 17:25:16 -04002458 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002459 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002460 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002461 binOp = glslang::EOpMul;
2462 break;
2463 }
2464 case glslang::EOpMod:
2465 // when an aggregate, this is the floating-point mod built-in function,
2466 // which can be emitted by the one in createBinaryOperation()
2467 binOp = glslang::EOpMod;
2468 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002469 case glslang::EOpEmitVertex:
2470 case glslang::EOpEndPrimitive:
2471 case glslang::EOpBarrier:
2472 case glslang::EOpMemoryBarrier:
2473 case glslang::EOpMemoryBarrierAtomicCounter:
2474 case glslang::EOpMemoryBarrierBuffer:
2475 case glslang::EOpMemoryBarrierImage:
2476 case glslang::EOpMemoryBarrierShared:
2477 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002478 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002479 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002480 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002481 case glslang::EOpWorkgroupMemoryBarrier:
2482 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002483 case glslang::EOpSubgroupBarrier:
2484 case glslang::EOpSubgroupMemoryBarrier:
2485 case glslang::EOpSubgroupMemoryBarrierBuffer:
2486 case glslang::EOpSubgroupMemoryBarrierImage:
2487 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002488 noReturnValue = true;
2489 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2490 break;
2491
Jeff Bolz36831c92018-09-05 10:11:41 -05002492 case glslang::EOpAtomicStore:
2493 noReturnValue = true;
2494 // fallthrough
2495 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002496 case glslang::EOpAtomicAdd:
2497 case glslang::EOpAtomicMin:
2498 case glslang::EOpAtomicMax:
2499 case glslang::EOpAtomicAnd:
2500 case glslang::EOpAtomicOr:
2501 case glslang::EOpAtomicXor:
2502 case glslang::EOpAtomicExchange:
2503 case glslang::EOpAtomicCompSwap:
2504 atomic = true;
2505 break;
2506
John Kessenich0d0c6d32017-07-23 16:08:26 -06002507 case glslang::EOpAtomicCounterAdd:
2508 case glslang::EOpAtomicCounterSubtract:
2509 case glslang::EOpAtomicCounterMin:
2510 case glslang::EOpAtomicCounterMax:
2511 case glslang::EOpAtomicCounterAnd:
2512 case glslang::EOpAtomicCounterOr:
2513 case glslang::EOpAtomicCounterXor:
2514 case glslang::EOpAtomicCounterExchange:
2515 case glslang::EOpAtomicCounterCompSwap:
2516 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2517 builder.addCapability(spv::CapabilityAtomicStorageOps);
2518 atomic = true;
2519 break;
2520
Chao Chen3c366992018-09-19 11:41:59 -07002521#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002522 case glslang::EOpIgnoreIntersectionNV:
2523 case glslang::EOpTerminateRayNV:
2524 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002525 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002526 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2527 noReturnValue = true;
2528 break;
2529#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002530 case glslang::EOpCooperativeMatrixLoad:
2531 case glslang::EOpCooperativeMatrixStore:
2532 noReturnValue = true;
2533 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002534 case glslang::EOpBeginInvocationInterlock:
2535 case glslang::EOpEndInvocationInterlock:
2536 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2537 noReturnValue = true;
2538 break;
Chao Chen3c366992018-09-19 11:41:59 -07002539
John Kessenich140f3df2015-06-26 16:58:36 -06002540 default:
2541 break;
2542 }
2543
2544 //
2545 // See if it maps to a regular operation.
2546 //
John Kessenich140f3df2015-06-26 16:58:36 -06002547 if (binOp != glslang::EOpNull) {
2548 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2549 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2550 assert(left && right);
2551
2552 builder.clearAccessChain();
2553 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002554 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002555
2556 builder.clearAccessChain();
2557 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002558 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002559
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002560 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002561 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002562 TranslateNoContractionDecoration(node->getType().getQualifier()),
2563 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002564 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002565 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002566 left->getType().getBasicType(), reduceComparison);
2567
2568 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002569 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002570 builder.clearAccessChain();
2571 builder.setAccessChainRValue(result);
2572
2573 return false;
2574 }
2575
John Kessenich426394d2015-07-23 10:22:48 -06002576 //
2577 // Create the list of operands.
2578 //
John Kessenich140f3df2015-06-26 16:58:36 -06002579 glslang::TIntermSequence& glslangOperands = node->getSequence();
2580 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002581 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002582 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002583 // special case l-value operands; there are just a few
2584 bool lvalue = false;
2585 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002586 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002587 case glslang::EOpModf:
2588 if (arg == 1)
2589 lvalue = true;
2590 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002591 case glslang::EOpInterpolateAtSample:
2592 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002593#ifdef AMD_EXTENSIONS
2594 case glslang::EOpInterpolateAtVertex:
2595#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002596 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002597 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002598
2599 // Does it need a swizzle inversion? If so, evaluation is inverted;
2600 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002601 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002602 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2603 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2604 }
Rex Xu7a26c172015-12-08 17:12:09 +08002605 break;
Rex Xud4782c12015-09-06 16:30:11 +08002606 case glslang::EOpAtomicAdd:
2607 case glslang::EOpAtomicMin:
2608 case glslang::EOpAtomicMax:
2609 case glslang::EOpAtomicAnd:
2610 case glslang::EOpAtomicOr:
2611 case glslang::EOpAtomicXor:
2612 case glslang::EOpAtomicExchange:
2613 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002614 case glslang::EOpAtomicLoad:
2615 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002616 case glslang::EOpAtomicCounterAdd:
2617 case glslang::EOpAtomicCounterSubtract:
2618 case glslang::EOpAtomicCounterMin:
2619 case glslang::EOpAtomicCounterMax:
2620 case glslang::EOpAtomicCounterAnd:
2621 case glslang::EOpAtomicCounterOr:
2622 case glslang::EOpAtomicCounterXor:
2623 case glslang::EOpAtomicCounterExchange:
2624 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002625 if (arg == 0)
2626 lvalue = true;
2627 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002628 case glslang::EOpAddCarry:
2629 case glslang::EOpSubBorrow:
2630 if (arg == 2)
2631 lvalue = true;
2632 break;
2633 case glslang::EOpUMulExtended:
2634 case glslang::EOpIMulExtended:
2635 if (arg >= 2)
2636 lvalue = true;
2637 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002638 case glslang::EOpCooperativeMatrixLoad:
2639 if (arg == 0 || arg == 1)
2640 lvalue = true;
2641 break;
2642 case glslang::EOpCooperativeMatrixStore:
2643 if (arg == 1)
2644 lvalue = true;
2645 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002646 default:
2647 break;
2648 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002649 builder.clearAccessChain();
2650 if (invertedType != spv::NoType && arg == 0)
2651 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2652 else
2653 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002654
2655 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2656 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2657
2658 if (arg == 1) {
2659 // fold "element" parameter into the access chain
2660 spv::Builder::AccessChain save = builder.getAccessChain();
2661 builder.clearAccessChain();
2662 glslangOperands[2]->traverse(this);
2663
2664 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2665
2666 builder.setAccessChain(save);
2667
2668 // Point to the first element of the array.
2669 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002670 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002671
2672 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2673 unsigned int alignment = builder.getAccessChain().alignment;
2674
2675 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2676 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2677 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2678 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2679 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2680 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2681 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2682 }
2683
2684 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2685
2686 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2687 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2688 }
2689
2690 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2691 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2692 }
2693 } else if (arg == 2) {
2694 continue;
2695 }
2696 }
2697
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002698 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002699 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002700 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2701 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2702 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002703 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002704 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002705 }
John Kessenich140f3df2015-06-26 16:58:36 -06002706 }
John Kessenich426394d2015-07-23 10:22:48 -06002707
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002708 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002709 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2710 std::vector<spv::IdImmediate> idImmOps;
2711
2712 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2713 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2714 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2715 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2716 // get the pointee type
2717 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2718 assert(builder.isCooperativeMatrixType(typeId));
2719 // do the op
2720 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2721 // store the result to the pointer (out param 'm')
2722 builder.createStore(result, operands[0]);
2723 result = 0;
2724 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2725 std::vector<spv::IdImmediate> idImmOps;
2726
2727 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2728 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2729 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2730 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2731 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2732
2733 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2734 result = 0;
2735 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002736 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002737 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002738 } else {
2739 // Pass through to generic operations.
2740 switch (glslangOperands.size()) {
2741 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002742 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002743 break;
2744 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002745 {
2746 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002747 TranslateNoContractionDecoration(node->getType().getQualifier()),
2748 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002749 result = createUnaryOperation(
2750 node->getOp(), decorations,
2751 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002752 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002753 }
John Kessenich426394d2015-07-23 10:22:48 -06002754 break;
2755 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002756 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002757 break;
2758 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002759 if (invertedType)
2760 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002761 }
2762
2763 if (noReturnValue)
2764 return false;
2765
2766 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002767 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002768 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002769 } else {
2770 builder.clearAccessChain();
2771 builder.setAccessChainRValue(result);
2772 return false;
2773 }
2774}
2775
John Kessenich433e9ff2017-01-26 20:31:11 -07002776// This path handles both if-then-else and ?:
2777// The if-then-else has a node type of void, while
2778// ?: has either a void or a non-void node type
2779//
2780// Leaving the result, when not void:
2781// GLSL only has r-values as the result of a :?, but
2782// if we have an l-value, that can be more efficient if it will
2783// become the base of a complex r-value expression, because the
2784// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002785bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2786{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002787 // see if OpSelect can handle it
2788 const auto isOpSelectable = [&]() {
2789 if (node->getBasicType() == glslang::EbtVoid)
2790 return false;
2791 // OpSelect can do all other types starting with SPV 1.4
2792 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2793 // pre-1.4, only scalars and vectors can be handled
2794 if ((!node->getType().isScalar() && !node->getType().isVector()))
2795 return false;
2796 }
2797 return true;
2798 };
2799
John Kessenich4bee5312018-02-20 21:29:05 -07002800 // See if it simple and safe, or required, to execute both sides.
2801 // Crucially, side effects must be either semantically required or avoided,
2802 // and there are performance trade-offs.
2803 // Return true if required or a good idea (and safe) to execute both sides,
2804 // false otherwise.
2805 const auto bothSidesPolicy = [&]() -> bool {
2806 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002807 if (node->getTrueBlock() == nullptr ||
2808 node->getFalseBlock() == nullptr)
2809 return false;
2810
John Kessenich4bee5312018-02-20 21:29:05 -07002811 // required? (unless we write additional code to look for side effects
2812 // and make performance trade-offs if none are present)
2813 if (!node->getShortCircuit())
2814 return true;
2815
2816 // if not required to execute both, decide based on performance/practicality...
2817
John Kessenich0c1e71a2019-01-10 18:23:06 +07002818 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002819 return false;
2820
John Kessenich433e9ff2017-01-26 20:31:11 -07002821 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2822 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2823
2824 // return true if a single operand to ? : is okay for OpSelect
2825 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002826 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002827 };
2828
2829 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2830 operandOkay(node->getFalseBlock()->getAsTyped());
2831 };
2832
John Kessenich4bee5312018-02-20 21:29:05 -07002833 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2834 // emit the condition before doing anything with selection
2835 node->getCondition()->traverse(this);
2836 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2837
2838 // Find a way of executing both sides and selecting the right result.
2839 const auto executeBothSides = [&]() -> void {
2840 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002841 node->getTrueBlock()->traverse(this);
2842 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2843 node->getFalseBlock()->traverse(this);
2844 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2845
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002846 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002847
John Kessenich4bee5312018-02-20 21:29:05 -07002848 // done if void
2849 if (node->getBasicType() == glslang::EbtVoid)
2850 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002851
John Kessenich4bee5312018-02-20 21:29:05 -07002852 // emit code to select between trueValue and falseValue
2853
2854 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002855 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002856 // Emit OpSelect for this selection.
2857
2858 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002859 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2860 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002861 condition = builder.smearScalar(spv::NoPrecision, condition,
2862 builder.makeVectorType(builder.makeBoolType(),
2863 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002864 }
John Kessenich4bee5312018-02-20 21:29:05 -07002865
2866 // OpSelect
2867 result = builder.createTriOp(spv::OpSelect,
2868 convertGlslangToSpvType(node->getType()), condition,
2869 trueValue, falseValue);
2870
2871 builder.clearAccessChain();
2872 builder.setAccessChainRValue(result);
2873 } else {
2874 // We need control flow to select the result.
2875 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2876 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2877
2878 // Selection control:
2879 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2880
2881 // make an "if" based on the value created by the condition
2882 spv::Builder::If ifBuilder(condition, control, builder);
2883
2884 // emit the "then" statement
2885 builder.createStore(trueValue, result);
2886 ifBuilder.makeBeginElse();
2887 // emit the "else" statement
2888 builder.createStore(falseValue, result);
2889
2890 // finish off the control flow
2891 ifBuilder.makeEndIf();
2892
2893 builder.clearAccessChain();
2894 builder.setAccessChainLValue(result);
2895 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002896 };
2897
John Kessenich4bee5312018-02-20 21:29:05 -07002898 // Execute the one side needed, as per the condition
2899 const auto executeOneSide = [&]() {
2900 // Always emit control flow.
2901 if (node->getBasicType() != glslang::EbtVoid)
2902 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002903
John Kessenich4bee5312018-02-20 21:29:05 -07002904 // Selection control:
2905 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2906
2907 // make an "if" based on the value created by the condition
2908 spv::Builder::If ifBuilder(condition, control, builder);
2909
2910 // emit the "then" statement
2911 if (node->getTrueBlock() != nullptr) {
2912 node->getTrueBlock()->traverse(this);
2913 if (result != spv::NoResult)
2914 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2915 }
2916
2917 if (node->getFalseBlock() != nullptr) {
2918 ifBuilder.makeBeginElse();
2919 // emit the "else" statement
2920 node->getFalseBlock()->traverse(this);
2921 if (result != spv::NoResult)
2922 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2923 }
2924
2925 // finish off the control flow
2926 ifBuilder.makeEndIf();
2927
2928 if (result != spv::NoResult) {
2929 builder.clearAccessChain();
2930 builder.setAccessChainLValue(result);
2931 }
2932 };
2933
2934 // Try for OpSelect (or a requirement to execute both sides)
2935 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002936 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2937 if (node->getType().getQualifier().isSpecConstant())
2938 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002939 executeBothSides();
2940 } else
2941 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002942
2943 return false;
2944}
2945
2946bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2947{
2948 // emit and get the condition before doing anything with switch
2949 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002950 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002951
Rex Xu57e65922017-07-04 23:23:40 +08002952 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002953 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002954
John Kessenich140f3df2015-06-26 16:58:36 -06002955 // browse the children to sort out code segments
2956 int defaultSegment = -1;
2957 std::vector<TIntermNode*> codeSegments;
2958 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2959 std::vector<int> caseValues;
2960 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2961 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2962 TIntermNode* child = *c;
2963 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002964 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002965 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002966 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002967 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2968 } else
2969 codeSegments.push_back(child);
2970 }
2971
qining25262b32016-05-06 17:25:16 -04002972 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002973 // statements between the last case and the end of the switch statement
2974 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2975 (int)codeSegments.size() == defaultSegment)
2976 codeSegments.push_back(nullptr);
2977
2978 // make the switch statement
2979 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002980 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002981
2982 // emit all the code in the segments
2983 breakForLoop.push(false);
2984 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2985 builder.nextSwitchSegment(segmentBlocks, s);
2986 if (codeSegments[s])
2987 codeSegments[s]->traverse(this);
2988 else
2989 builder.addSwitchBreak();
2990 }
2991 breakForLoop.pop();
2992
2993 builder.endSwitch(segmentBlocks);
2994
2995 return false;
2996}
2997
2998void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2999{
3000 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003001 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003002
3003 builder.clearAccessChain();
3004 builder.setAccessChainRValue(constant);
3005}
3006
3007bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3008{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003009 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003010 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003011
3012 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003013 std::vector<unsigned int> operands;
3014 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003015
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003016 // Spec requires back edges to target header blocks, and every header block
3017 // must dominate its merge block. Make a header block first to ensure these
3018 // conditions are met. By definition, it will contain OpLoopMerge, followed
3019 // by a block-ending branch. But we don't want to put any other body/test
3020 // instructions in it, since the body/test may have arbitrary instructions,
3021 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003022 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003023 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003024 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003025 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003026 spv::Block& test = builder.makeNewBlock();
3027 builder.createBranch(&test);
3028
3029 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003030 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003031 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003032 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3033
3034 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003035 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003036 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003037 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003038 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003039 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003040
3041 builder.setBuildPoint(&blocks.continue_target);
3042 if (node->getTerminal())
3043 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003044 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003045 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003046 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003047 builder.createBranch(&blocks.body);
3048
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003049 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003050 builder.setBuildPoint(&blocks.body);
3051 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003052 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003053 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003054 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003055
3056 builder.setBuildPoint(&blocks.continue_target);
3057 if (node->getTerminal())
3058 node->getTerminal()->traverse(this);
3059 if (node->getTest()) {
3060 node->getTest()->traverse(this);
3061 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003062 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003063 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003064 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003065 // TODO: unless there was a break/return/discard instruction
3066 // somewhere in the body, this is an infinite loop, so we should
3067 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003068 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003069 }
John Kessenich140f3df2015-06-26 16:58:36 -06003070 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003071 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003072 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003073 return false;
3074}
3075
3076bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3077{
3078 if (node->getExpression())
3079 node->getExpression()->traverse(this);
3080
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003081 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003082
John Kessenich140f3df2015-06-26 16:58:36 -06003083 switch (node->getFlowOp()) {
3084 case glslang::EOpKill:
3085 builder.makeDiscard();
3086 break;
3087 case glslang::EOpBreak:
3088 if (breakForLoop.top())
3089 builder.createLoopExit();
3090 else
3091 builder.addSwitchBreak();
3092 break;
3093 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003094 builder.createLoopContinue();
3095 break;
3096 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003097 if (node->getExpression()) {
3098 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3099 spv::Id returnId = accessChainLoad(glslangReturnType);
3100 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3101 builder.clearAccessChain();
3102 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3103 builder.setAccessChainLValue(copyId);
3104 multiTypeStore(glslangReturnType, returnId);
3105 returnId = builder.createLoad(copyId);
3106 }
3107 builder.makeReturn(false, returnId);
3108 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003109 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003110
3111 builder.clearAccessChain();
3112 break;
3113
Jeff Bolzba6170b2019-07-01 09:23:23 -05003114 case glslang::EOpDemote:
3115 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3116 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3117 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3118 break;
3119
John Kessenich140f3df2015-06-26 16:58:36 -06003120 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003121 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003122 break;
3123 }
3124
3125 return false;
3126}
3127
John Kessenich9c14f772019-06-17 08:38:35 -06003128spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003129{
qining25262b32016-05-06 17:25:16 -04003130 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003131 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003132 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003133 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003134 spv::Id result = createSpvConstant(*node);
3135 if (result != spv::NoResult)
3136 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003137 }
3138
3139 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003140 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003141 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3142 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003143
Rex Xucabbb782017-03-24 13:41:14 +08003144 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3145 node->getType().containsBasicType(glslang::EbtInt16) ||
3146 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003147 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003148 switch (storageClass) {
3149 case spv::StorageClassInput:
3150 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003151 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003152 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003153 break;
3154 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003155 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003156 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003157 break;
3158 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003159 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003160 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3161 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003162 else
3163 builder.addCapability(spv::CapabilityStorageUniform16);
3164 break;
3165 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003166 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003167 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3168 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3169 break;
3170 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003171 if (node->getType().containsBasicType(glslang::EbtFloat16))
3172 builder.addCapability(spv::CapabilityFloat16);
3173 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3174 node->getType().containsBasicType(glslang::EbtUint16))
3175 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003176 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003177 }
3178 }
Rex Xuf89ad982017-04-07 23:22:33 +08003179
John Kessenich312dcfb2018-07-03 13:19:51 -06003180 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3181 node->getType().containsBasicType(glslang::EbtUint8);
3182 if (contains8BitType) {
3183 if (storageClass == spv::StorageClassPushConstant) {
3184 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3185 builder.addCapability(spv::CapabilityStoragePushConstant8);
3186 } else if (storageClass == spv::StorageClassUniform) {
3187 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3188 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003189 } else if (storageClass == spv::StorageClassStorageBuffer) {
3190 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3191 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003192 } else {
3193 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003194 }
3195 }
3196
John Kessenich140f3df2015-06-26 16:58:36 -06003197 const char* name = node->getName().c_str();
3198 if (glslang::IsAnonymous(name))
3199 name = "";
3200
3201 return builder.createVariable(storageClass, spvType, name);
3202}
3203
3204// Return type Id of the sampled type.
3205spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3206{
3207 switch (sampler.type) {
3208 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003209#ifdef AMD_EXTENSIONS
3210 case glslang::EbtFloat16:
3211 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3212 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3213 return builder.makeFloatType(16);
3214#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003215 case glslang::EbtInt: return builder.makeIntType(32);
3216 case glslang::EbtUint: return builder.makeUintType(32);
3217 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003219 return builder.makeFloatType(32);
3220 }
3221}
3222
John Kessenich8c8505c2016-07-26 12:50:38 -06003223// If node is a swizzle operation, return the type that should be used if
3224// the swizzle base is first consumed by another operation, before the swizzle
3225// is applied.
3226spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3227{
John Kessenichecba76f2017-01-06 00:34:48 -07003228 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003229 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3230 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3231 else
3232 return spv::NoType;
3233}
3234
3235// When inverting a swizzle with a parent op, this function
3236// will apply the swizzle operation to a completed parent operation.
3237spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3238{
3239 std::vector<unsigned> swizzle;
3240 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3241 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3242}
3243
John Kessenich8c8505c2016-07-26 12:50:38 -06003244// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3245void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3246{
3247 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3248 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3249 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3250}
3251
John Kessenich3ac051e2015-12-20 11:29:16 -07003252// Convert from a glslang type to an SPV type, by calling into a
3253// recursive version of this function. This establishes the inherited
3254// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003255spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003256{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003257 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003258}
3259
3260// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003261// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003262// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003263spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003264 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3265 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003266{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003267 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003268
3269 switch (type.getBasicType()) {
3270 case glslang::EbtVoid:
3271 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003272 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003273 break;
3274 case glslang::EbtFloat:
3275 spvType = builder.makeFloatType(32);
3276 break;
3277 case glslang::EbtDouble:
3278 spvType = builder.makeFloatType(64);
3279 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003280 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003281 spvType = builder.makeFloatType(16);
3282 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003283 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003284 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3285 // a 32-bit int where non-0 means true.
3286 if (explicitLayout != glslang::ElpNone)
3287 spvType = builder.makeUintType(32);
3288 else
3289 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003290 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003291 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003292 spvType = builder.makeIntType(8);
3293 break;
3294 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003295 spvType = builder.makeUintType(8);
3296 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003297 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003298 spvType = builder.makeIntType(16);
3299 break;
3300 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003301 spvType = builder.makeUintType(16);
3302 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003303 case glslang::EbtInt:
3304 spvType = builder.makeIntType(32);
3305 break;
3306 case glslang::EbtUint:
3307 spvType = builder.makeUintType(32);
3308 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003309 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003310 spvType = builder.makeIntType(64);
3311 break;
3312 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003313 spvType = builder.makeUintType(64);
3314 break;
John Kessenich426394d2015-07-23 10:22:48 -06003315 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003316 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003317 spvType = builder.makeUintType(32);
3318 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003319#ifdef NV_EXTENSIONS
3320 case glslang::EbtAccStructNV:
3321 spvType = builder.makeAccelerationStructureNVType();
3322 break;
3323#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003324 case glslang::EbtSampler:
3325 {
3326 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003327 if (sampler.sampler) {
3328 // pure sampler
3329 spvType = builder.makeSamplerType();
3330 } else {
3331 // an image is present, make its type
3332 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3333 sampler.image ? 2 : 1, TranslateImageFormat(type));
3334 if (sampler.combined) {
3335 // already has both image and sampler, make the combined type
3336 spvType = builder.makeSampledImageType(spvType);
3337 }
John Kessenich55e7d112015-11-15 21:33:39 -07003338 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003339 }
John Kessenich140f3df2015-06-26 16:58:36 -06003340 break;
3341 case glslang::EbtStruct:
3342 case glslang::EbtBlock:
3343 {
3344 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003345 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003346
3347 // Try to share structs for different layouts, but not yet for other
3348 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003349 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003350 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003351 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003352 break;
3353
3354 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003355 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003356 memberRemapper[glslangMembers].resize(glslangMembers->size());
3357 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003358 }
3359 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003360 case glslang::EbtReference:
3361 {
3362 // Make the forward pointer, then recurse to convert the structure type, then
3363 // patch up the forward pointer with a real pointer type.
3364 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3365 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3366 forwardPointers[type.getReferentType()] = forwardId;
3367 }
3368 spvType = forwardPointers[type.getReferentType()];
3369 if (!forwardReferenceOnly) {
3370 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3371 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3372 forwardPointers[type.getReferentType()],
3373 referentType);
3374 }
3375 }
3376 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003377 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003378 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003379 break;
3380 }
3381
3382 if (type.isMatrix())
3383 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3384 else {
3385 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3386 if (type.getVectorSize() > 1)
3387 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3388 }
3389
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003390 if (type.isCoopMat()) {
3391 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3392 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3393 if (type.getBasicType() == glslang::EbtFloat16)
3394 builder.addCapability(spv::CapabilityFloat16);
3395
3396 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3397 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3398 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3399
3400 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3401 }
3402
John Kessenich140f3df2015-06-26 16:58:36 -06003403 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003404 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3405
John Kessenichc9a80832015-09-12 12:17:44 -06003406 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003407 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003408 // We need to decorate array strides for types needing explicit layout, except blocks.
3409 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003410 // Use a dummy glslang type for querying internal strides of
3411 // arrays of arrays, but using just a one-dimensional array.
3412 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003413 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3414 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003415
3416 // Will compute the higher-order strides here, rather than making a whole
3417 // pile of types and doing repetitive recursion on their contents.
3418 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3419 }
John Kessenichf8842e52016-01-04 19:22:56 -07003420
3421 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003422 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003423 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003424 if (stride > 0)
3425 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003426 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003427 }
3428 } else {
3429 // single-dimensional array, and don't yet have stride
3430
John Kessenichf8842e52016-01-04 19:22:56 -07003431 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003432 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3433 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003434 }
John Kessenich31ed4832015-09-09 17:51:38 -06003435
John Kessenichead86222018-03-28 18:01:20 -06003436 // Do the outer dimension, which might not be known for a runtime-sized array.
3437 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3438 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003439 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003440 else {
3441 if (!lastBufferBlockMember) {
3442 builder.addExtension("SPV_EXT_descriptor_indexing");
3443 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3444 }
John Kessenichead86222018-03-28 18:01:20 -06003445 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003446 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003447 if (stride > 0)
3448 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003449 }
3450
3451 return spvType;
3452}
3453
John Kessenich0e737842017-03-24 18:38:16 -06003454// TODO: this functionality should exist at a higher level, in creating the AST
3455//
3456// Identify interface members that don't have their required extension turned on.
3457//
3458bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3459{
Chao Chen3c366992018-09-19 11:41:59 -07003460#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003461 auto& extensions = glslangIntermediate->getRequestedExtensions();
3462
Rex Xubcf291a2017-03-29 23:01:36 +08003463 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3464 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3465 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003466 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3467 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3468 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003469
3470 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3471 if (member.getFieldName() == "gl_ViewportMask" &&
3472 extensions.find("GL_NV_viewport_array2") == extensions.end())
3473 return true;
3474 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3475 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3476 return true;
3477 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3478 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3479 return true;
3480 }
3481#endif
John Kessenich0e737842017-03-24 18:38:16 -06003482
3483 return false;
3484};
3485
John Kessenich6090df02016-06-30 21:18:02 -06003486// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3487// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3488// Mutually recursive with convertGlslangToSpvType().
3489spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3490 const glslang::TTypeList* glslangMembers,
3491 glslang::TLayoutPacking explicitLayout,
3492 const glslang::TQualifier& qualifier)
3493{
3494 // Create a vector of struct types for SPIR-V to consume
3495 std::vector<spv::Id> spvMembers;
3496 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 -06003497 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003498 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3499 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3500 if (glslangMember.hiddenMember()) {
3501 ++memberDelta;
3502 if (type.getBasicType() == glslang::EbtBlock)
3503 memberRemapper[glslangMembers][i] = -1;
3504 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003505 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003506 if (filterMember(glslangMember)) {
3507 memberDelta++;
3508 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003509 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003510 }
3511 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003512 }
John Kessenich6090df02016-06-30 21:18:02 -06003513 // modify just this child's view of the qualifier
3514 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3515 InheritQualifiers(memberQualifier, qualifier);
3516
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003517 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003518 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003519 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003520
3521 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003522 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3523 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003524
3525 // Make forward pointers for any pointer members, and create a list of members to
3526 // convert to spirv types after creating the struct.
3527 if (glslangMember.getBasicType() == glslang::EbtReference) {
3528 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3529 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3530 }
3531 spvMembers.push_back(
3532 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3533 } else {
3534 spvMembers.push_back(
3535 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3536 }
John Kessenich6090df02016-06-30 21:18:02 -06003537 }
3538 }
3539
3540 // Make the SPIR-V type
3541 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003542 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003543 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3544
3545 // Decorate it
3546 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3547
John Kessenichd72f4882019-01-16 14:55:37 +07003548 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003549 auto it = deferredForwardPointers[i];
3550 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3551 }
3552
John Kessenich6090df02016-06-30 21:18:02 -06003553 return spvType;
3554}
3555
3556void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3557 const glslang::TTypeList* glslangMembers,
3558 glslang::TLayoutPacking explicitLayout,
3559 const glslang::TQualifier& qualifier,
3560 spv::Id spvType)
3561{
3562 // Name and decorate the non-hidden members
3563 int offset = -1;
3564 int locationOffset = 0; // for use within the members of this struct
3565 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3566 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3567 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003568 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003569 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003570 if (filterMember(glslangMember))
3571 continue;
3572 }
John Kessenich6090df02016-06-30 21:18:02 -06003573
3574 // modify just this child's view of the qualifier
3575 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3576 InheritQualifiers(memberQualifier, qualifier);
3577
3578 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003579 if (member < 0)
3580 continue;
3581
3582 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3583 builder.addMemberDecoration(spvType, member,
3584 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3585 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3586 // Add interpolation and auxiliary storage decorations only to
3587 // top-level members of Input and Output storage classes
3588 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3589 type.getQualifier().storage == glslang::EvqVaryingOut) {
3590 if (type.getBasicType() == glslang::EbtBlock ||
3591 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3592 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3593 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003594#ifdef NV_EXTENSIONS
3595 addMeshNVDecoration(spvType, member, memberQualifier);
3596#endif
John Kessenich6090df02016-06-30 21:18:02 -06003597 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003598 }
3599 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003600
John Kessenich5d610ee2018-03-07 18:05:55 -07003601 if (type.getBasicType() == glslang::EbtBlock &&
3602 qualifier.storage == glslang::EvqBuffer) {
3603 // Add memory decorations only to top-level members of shader storage block
3604 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003605 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003606 for (unsigned int i = 0; i < memory.size(); ++i)
3607 builder.addMemberDecoration(spvType, member, memory[i]);
3608 }
John Kessenich6090df02016-06-30 21:18:02 -06003609
John Kessenich5d610ee2018-03-07 18:05:55 -07003610 // Location assignment was already completed correctly by the front end,
3611 // just track whether a member needs to be decorated.
3612 // Ignore member locations if the container is an array, as that's
3613 // ill-specified and decisions have been made to not allow this.
3614 if (! type.isArray() && memberQualifier.hasLocation())
3615 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003616
John Kessenich5d610ee2018-03-07 18:05:55 -07003617 if (qualifier.hasLocation()) // track for upcoming inheritance
3618 locationOffset += glslangIntermediate->computeTypeLocationSize(
3619 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003620
John Kessenich5d610ee2018-03-07 18:05:55 -07003621 // component, XFB, others
3622 if (glslangMember.getQualifier().hasComponent())
3623 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3624 glslangMember.getQualifier().layoutComponent);
3625 if (glslangMember.getQualifier().hasXfbOffset())
3626 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3627 glslangMember.getQualifier().layoutXfbOffset);
3628 else if (explicitLayout != glslang::ElpNone) {
3629 // figure out what to do with offset, which is accumulating
3630 int nextOffset;
3631 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3632 if (offset >= 0)
3633 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3634 offset = nextOffset;
3635 }
John Kessenich6090df02016-06-30 21:18:02 -06003636
John Kessenich5d610ee2018-03-07 18:05:55 -07003637 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3638 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3639 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003640
John Kessenich5d610ee2018-03-07 18:05:55 -07003641 // built-in variable decorations
3642 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3643 if (builtIn != spv::BuiltInMax)
3644 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003645
John Kessenich5611c6d2018-04-05 11:25:02 -06003646 // nonuniform
3647 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3648
John Kessenichead86222018-03-28 18:01:20 -06003649 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3650 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3651 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3652 memberQualifier.semanticName);
3653 }
3654
chaoc771d89f2017-01-13 01:10:53 -08003655#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003656 if (builtIn == spv::BuiltInLayer) {
3657 // SPV_NV_viewport_array2 extension
3658 if (glslangMember.getQualifier().layoutViewportRelative){
3659 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3660 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3661 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003662 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003663 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3664 builder.addMemberDecoration(spvType, member,
3665 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3666 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3667 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3668 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003669 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003670 }
3671 if (glslangMember.getQualifier().layoutPassthrough) {
3672 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3673 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3674 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3675 }
chaoc771d89f2017-01-13 01:10:53 -08003676#endif
John Kessenich6090df02016-06-30 21:18:02 -06003677 }
3678
3679 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003680 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3681 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003682}
3683
John Kessenich6c292d32016-02-15 20:58:50 -07003684// Turn the expression forming the array size into an id.
3685// This is not quite trivial, because of specialization constants.
3686// Sometimes, a raw constant is turned into an Id, and sometimes
3687// a specialization constant expression is.
3688spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3689{
3690 // First, see if this is sized with a node, meaning a specialization constant:
3691 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3692 if (specNode != nullptr) {
3693 builder.clearAccessChain();
3694 specNode->traverse(this);
3695 return accessChainLoad(specNode->getAsTyped()->getType());
3696 }
qining25262b32016-05-06 17:25:16 -04003697
John Kessenich6c292d32016-02-15 20:58:50 -07003698 // Otherwise, need a compile-time (front end) size, get it:
3699 int size = arraySizes.getDimSize(dim);
3700 assert(size > 0);
3701 return builder.makeUintConstant(size);
3702}
3703
John Kessenich103bef92016-02-08 21:38:15 -07003704// Wrap the builder's accessChainLoad to:
3705// - localize handling of RelaxedPrecision
3706// - use the SPIR-V inferred type instead of another conversion of the glslang type
3707// (avoids unnecessary work and possible type punning for structures)
3708// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003709spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3710{
John Kessenich103bef92016-02-08 21:38:15 -07003711 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003712
3713 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3714 coherentFlags |= TranslateCoherent(type);
3715
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003716 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003717 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003718
John Kessenich5611c6d2018-04-05 11:25:02 -06003719 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003720 TranslateNonUniformDecoration(type.getQualifier()),
3721 nominalTypeId,
3722 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003723 TranslateMemoryScope(coherentFlags),
3724 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003725
3726 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003727 if (type.getBasicType() == glslang::EbtBool) {
3728 if (builder.isScalarType(nominalTypeId)) {
3729 // Conversion for bool
3730 spv::Id boolType = builder.makeBoolType();
3731 if (nominalTypeId != boolType)
3732 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3733 } else if (builder.isVectorType(nominalTypeId)) {
3734 // Conversion for bvec
3735 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3736 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3737 if (nominalTypeId != bvecType)
3738 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3739 }
3740 }
John Kessenich103bef92016-02-08 21:38:15 -07003741
3742 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003743}
3744
Rex Xu27253232016-02-23 17:51:09 +08003745// Wrap the builder's accessChainStore to:
3746// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003747//
3748// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003749void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3750{
3751 // Need to convert to abstract types when necessary
3752 if (type.getBasicType() == glslang::EbtBool) {
3753 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3754
3755 if (builder.isScalarType(nominalTypeId)) {
3756 // Conversion for bool
3757 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003758 if (nominalTypeId != boolType) {
3759 // keep these outside arguments, for determinant order-of-evaluation
3760 spv::Id one = builder.makeUintConstant(1);
3761 spv::Id zero = builder.makeUintConstant(0);
3762 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3763 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003764 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003765 } else if (builder.isVectorType(nominalTypeId)) {
3766 // Conversion for bvec
3767 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3768 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003769 if (nominalTypeId != bvecType) {
3770 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003771 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3772 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3773 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003774 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003775 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3776 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003777 }
3778 }
3779
Jeff Bolz36831c92018-09-05 10:11:41 -05003780 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3781 coherentFlags |= TranslateCoherent(type);
3782
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003783 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003784 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003785
Jeff Bolz36831c92018-09-05 10:11:41 -05003786 builder.accessChainStore(rvalue,
3787 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003788 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003789}
3790
John Kessenich4bf71552016-09-02 11:20:21 -06003791// For storing when types match at the glslang level, but not might match at the
3792// SPIR-V level.
3793//
3794// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003795// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003796// as in a member-decorated way.
3797//
3798// NOTE: This function can handle any store request; if it's not special it
3799// simplifies to a simple OpStore.
3800//
3801// Implicitly uses the existing builder.accessChain as the storage target.
3802void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3803{
John Kessenichb3e24e42016-09-11 12:33:43 -06003804 // we only do the complex path here if it's an aggregate
3805 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003806 accessChainStore(type, rValue);
3807 return;
3808 }
3809
John Kessenichb3e24e42016-09-11 12:33:43 -06003810 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003811 spv::Id rType = builder.getTypeId(rValue);
3812 spv::Id lValue = builder.accessChainGetLValue();
3813 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3814 if (lType == rType) {
3815 accessChainStore(type, rValue);
3816 return;
3817 }
3818
John Kessenichb3e24e42016-09-11 12:33:43 -06003819 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003820 // where the two types were the same type in GLSL. This requires member
3821 // by member copy, recursively.
3822
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003823 // SPIR-V 1.4 added an instruction to do help do this.
3824 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3825 // However, bool in uniform space is changed to int, so
3826 // OpCopyLogical does not work for that.
3827 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3828 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3829 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3830 if (lBool == rBool) {
3831 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3832 accessChainStore(type, logicalCopy);
3833 return;
3834 }
3835 }
3836
John Kessenichb3e24e42016-09-11 12:33:43 -06003837 // If an array, copy element by element.
3838 if (type.isArray()) {
3839 glslang::TType glslangElementType(type, 0);
3840 spv::Id elementRType = builder.getContainedTypeId(rType);
3841 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3842 // get the source member
3843 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003844
John Kessenichb3e24e42016-09-11 12:33:43 -06003845 // set up the target storage
3846 builder.clearAccessChain();
3847 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003848 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003849
John Kessenichb3e24e42016-09-11 12:33:43 -06003850 // store the member
3851 multiTypeStore(glslangElementType, elementRValue);
3852 }
3853 } else {
3854 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003855
John Kessenichb3e24e42016-09-11 12:33:43 -06003856 // loop over structure members
3857 const glslang::TTypeList& members = *type.getStruct();
3858 for (int m = 0; m < (int)members.size(); ++m) {
3859 const glslang::TType& glslangMemberType = *members[m].type;
3860
3861 // get the source member
3862 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3863 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3864
3865 // set up the target storage
3866 builder.clearAccessChain();
3867 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003868 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003869
3870 // store the member
3871 multiTypeStore(glslangMemberType, memberRValue);
3872 }
John Kessenich4bf71552016-09-02 11:20:21 -06003873 }
3874}
3875
John Kessenichf85e8062015-12-19 13:57:10 -07003876// Decide whether or not this type should be
3877// decorated with offsets and strides, and if so
3878// whether std140 or std430 rules should be applied.
3879glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003880{
John Kessenichf85e8062015-12-19 13:57:10 -07003881 // has to be a block
3882 if (type.getBasicType() != glslang::EbtBlock)
3883 return glslang::ElpNone;
3884
Chao Chen3c366992018-09-19 11:41:59 -07003885 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003886 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003887 type.getQualifier().storage != glslang::EvqBuffer &&
3888 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003889 return glslang::ElpNone;
3890
3891 // return the layout to use
3892 switch (type.getQualifier().layoutPacking) {
3893 case glslang::ElpStd140:
3894 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003895 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003896 return type.getQualifier().layoutPacking;
3897 default:
3898 return glslang::ElpNone;
3899 }
John Kessenich31ed4832015-09-09 17:51:38 -06003900}
3901
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003902// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003903int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003904{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003905 int size;
John Kessenich49987892015-12-29 17:11:44 -07003906 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003907 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003908
3909 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003910}
3911
John Kessenich49987892015-12-29 17:11:44 -07003912// 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 -07003913// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003914int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003915{
John Kessenich49987892015-12-29 17:11:44 -07003916 glslang::TType elementType;
3917 elementType.shallowCopy(matrixType);
3918 elementType.clearArraySizes();
3919
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003920 int size;
John Kessenich49987892015-12-29 17:11:44 -07003921 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003922 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003923
3924 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003925}
3926
John Kessenich5e4b1242015-08-06 22:53:06 -06003927// Given a member type of a struct, realign the current offset for it, and compute
3928// the next (not yet aligned) offset for the next member, which will get aligned
3929// on the next call.
3930// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3931// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3932// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003933void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003934 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003935{
3936 // this will get a positive value when deemed necessary
3937 nextOffset = -1;
3938
John Kessenich5e4b1242015-08-06 22:53:06 -06003939 // override anything in currentOffset with user-set offset
3940 if (memberType.getQualifier().hasOffset())
3941 currentOffset = memberType.getQualifier().layoutOffset;
3942
3943 // It could be that current linker usage in glslang updated all the layoutOffset,
3944 // in which case the following code does not matter. But, that's not quite right
3945 // once cross-compilation unit GLSL validation is done, as the original user
3946 // settings are needed in layoutOffset, and then the following will come into play.
3947
John Kessenichf85e8062015-12-19 13:57:10 -07003948 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003949 if (! memberType.getQualifier().hasOffset())
3950 currentOffset = -1;
3951
3952 return;
3953 }
3954
John Kessenichf85e8062015-12-19 13:57:10 -07003955 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003956 if (currentOffset < 0)
3957 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003958
John Kessenich5e4b1242015-08-06 22:53:06 -06003959 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3960 // but possibly not yet correctly aligned.
3961
3962 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003963 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003964 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003965
3966 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003967 // TODO: make this consistent in early phases of code:
3968 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3969 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3970 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003971 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003972 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003973 int dummySize;
3974 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3975 if (componentAlignment <= 4)
3976 memberAlignment = componentAlignment;
3977 }
3978
3979 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003980 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003981
3982 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003983 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003984 glslang::RoundToPow2(currentOffset, 16);
3985
John Kessenich5e4b1242015-08-06 22:53:06 -06003986 nextOffset = currentOffset + memberSize;
3987}
3988
David Netoa901ffe2016-06-08 14:11:40 +01003989void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003990{
David Netoa901ffe2016-06-08 14:11:40 +01003991 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3992 switch (glslangBuiltIn)
3993 {
3994 case glslang::EbvClipDistance:
3995 case glslang::EbvCullDistance:
3996 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003997#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003998 case glslang::EbvViewportMaskNV:
3999 case glslang::EbvSecondaryPositionNV:
4000 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004001 case glslang::EbvPositionPerViewNV:
4002 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004003 case glslang::EbvTaskCountNV:
4004 case glslang::EbvPrimitiveCountNV:
4005 case glslang::EbvPrimitiveIndicesNV:
4006 case glslang::EbvClipDistancePerViewNV:
4007 case glslang::EbvCullDistancePerViewNV:
4008 case glslang::EbvLayerPerViewNV:
4009 case glslang::EbvMeshViewCountNV:
4010 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004011#endif
David Netoa901ffe2016-06-08 14:11:40 +01004012 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4013 // Alternately, we could just call this for any glslang built-in, since the
4014 // capability already guards against duplicates.
4015 TranslateBuiltInDecoration(glslangBuiltIn, false);
4016 break;
4017 default:
4018 // Capabilities were already generated when the struct was declared.
4019 break;
4020 }
John Kessenichebb50532016-05-16 19:22:05 -06004021}
4022
John Kessenich6fccb3c2016-09-19 16:01:41 -06004023bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004024{
John Kessenicheee9d532016-09-19 18:09:30 -06004025 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004026}
4027
John Kessenichd41993d2017-09-10 15:21:05 -06004028// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004029// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4030// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004031bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004032{
John Kessenich6a14f782017-12-04 02:48:10 -07004033 assert(qualifier == glslang::EvqIn ||
4034 qualifier == glslang::EvqOut ||
4035 qualifier == glslang::EvqInOut ||
4036 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004037 return qualifier != glslang::EvqConstReadOnly;
4038}
4039
4040// Is parameter pass-by-original?
4041bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4042 bool implicitThisParam)
4043{
4044 if (implicitThisParam) // implicit this
4045 return true;
4046 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004047 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004048 return paramType.containsOpaque() || // sampler, etc.
4049 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4050}
4051
John Kessenich140f3df2015-06-26 16:58:36 -06004052// Make all the functions, skeletally, without actually visiting their bodies.
4053void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4054{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004055 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004056 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4057 if (paramPrecision != spv::NoPrecision)
4058 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004059 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004060 if (type.getBasicType() == glslang::EbtReference) {
4061 // Original and non-writable params pass the pointer directly and
4062 // use restrict/aliased, others are stored to a pointer in Function
4063 // memory and use RestrictPointer/AliasedPointer.
4064 if (originalParam(type.getQualifier().storage, type, false) ||
4065 !writableParam(type.getQualifier().storage)) {
4066 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4067 } else {
4068 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4069 }
4070 }
John Kessenichfad62972017-07-18 02:35:46 -06004071 };
4072
John Kessenich140f3df2015-06-26 16:58:36 -06004073 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4074 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004075 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004076 continue;
4077
4078 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004079 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004080 //
qining25262b32016-05-06 17:25:16 -04004081 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004082 // function. What it is an address of varies:
4083 //
John Kessenich4bf71552016-09-02 11:20:21 -06004084 // - "in" parameters not marked as "const" can be written to without modifying the calling
4085 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004086 //
4087 // - "const in" parameters can just be the r-value, as no writes need occur.
4088 //
John Kessenich4bf71552016-09-02 11:20:21 -06004089 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4090 // 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 -06004091
4092 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004093 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004094 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4095
John Kessenichfad62972017-07-18 02:35:46 -06004096 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4097 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06004098
John Kessenichfad62972017-07-18 02:35:46 -06004099 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004100 for (int p = 0; p < (int)parameters.size(); ++p) {
4101 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4102 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004103 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004104 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004105 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004106 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4107 else
John Kessenich4bf71552016-09-02 11:20:21 -06004108 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004109 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004110 paramTypes.push_back(typeId);
4111 }
4112
4113 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004114 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4115 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004116 glslFunction->getName().c_str(), paramTypes,
4117 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004118 if (implicitThis)
4119 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004120
4121 // Track function to emit/call later
4122 functionMap[glslFunction->getName().c_str()] = function;
4123
4124 // Set the parameter id's
4125 for (int p = 0; p < (int)parameters.size(); ++p) {
4126 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4127 // give a name too
4128 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004129
4130 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4131 if (paramType.containsBasicType(glslang::EbtInt8) ||
4132 paramType.containsBasicType(glslang::EbtUint8))
4133 builder.addCapability(spv::CapabilityInt8);
4134 if (paramType.containsBasicType(glslang::EbtInt16) ||
4135 paramType.containsBasicType(glslang::EbtUint16))
4136 builder.addCapability(spv::CapabilityInt16);
4137 if (paramType.containsBasicType(glslang::EbtFloat16))
4138 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004139 }
4140 }
4141}
4142
4143// Process all the initializers, while skipping the functions and link objects
4144void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4145{
4146 builder.setBuildPoint(shaderEntry->getLastBlock());
4147 for (int i = 0; i < (int)initializers.size(); ++i) {
4148 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4149 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4150
4151 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004152 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004153 initializer->traverse(this);
4154 }
4155 }
4156}
4157
4158// Process all the functions, while skipping initializers.
4159void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4160{
4161 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4162 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004163 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004164 node->traverse(this);
4165 }
4166}
4167
4168void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4169{
qining25262b32016-05-06 17:25:16 -04004170 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004171 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004172 currentFunction = functionMap[node->getName().c_str()];
4173 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004174 builder.setBuildPoint(functionBlock);
4175}
4176
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004177void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004178{
Rex Xufc618912015-09-09 16:42:49 +08004179 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004180
4181 glslang::TSampler sampler = {};
4182 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004183#ifdef AMD_EXTENSIONS
4184 bool f16ShadowCompare = false;
4185#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004186 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004187 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4188 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004189#ifdef AMD_EXTENSIONS
4190 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4191#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004192 }
4193
John Kessenich140f3df2015-06-26 16:58:36 -06004194 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4195 builder.clearAccessChain();
4196 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004197
4198 // Special case l-value operands
4199 bool lvalue = false;
4200 switch (node.getOp()) {
4201 case glslang::EOpImageAtomicAdd:
4202 case glslang::EOpImageAtomicMin:
4203 case glslang::EOpImageAtomicMax:
4204 case glslang::EOpImageAtomicAnd:
4205 case glslang::EOpImageAtomicOr:
4206 case glslang::EOpImageAtomicXor:
4207 case glslang::EOpImageAtomicExchange:
4208 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004209 case glslang::EOpImageAtomicLoad:
4210 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004211 if (i == 0)
4212 lvalue = true;
4213 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004214 case glslang::EOpSparseImageLoad:
4215 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4216 lvalue = true;
4217 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004218#ifdef AMD_EXTENSIONS
4219 case glslang::EOpSparseTexture:
4220 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4221 lvalue = true;
4222 break;
4223 case glslang::EOpSparseTextureClamp:
4224 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4225 lvalue = true;
4226 break;
4227 case glslang::EOpSparseTextureLod:
4228 case glslang::EOpSparseTextureOffset:
4229 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4230 lvalue = true;
4231 break;
4232#else
Rex Xu48edadf2015-12-31 16:11:41 +08004233 case glslang::EOpSparseTexture:
4234 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4235 lvalue = true;
4236 break;
4237 case glslang::EOpSparseTextureClamp:
4238 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4239 lvalue = true;
4240 break;
4241 case glslang::EOpSparseTextureLod:
4242 case glslang::EOpSparseTextureOffset:
4243 if (i == 3)
4244 lvalue = true;
4245 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004246#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004247 case glslang::EOpSparseTextureFetch:
4248 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4249 lvalue = true;
4250 break;
4251 case glslang::EOpSparseTextureFetchOffset:
4252 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4253 lvalue = true;
4254 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004255#ifdef AMD_EXTENSIONS
4256 case glslang::EOpSparseTextureLodOffset:
4257 case glslang::EOpSparseTextureGrad:
4258 case glslang::EOpSparseTextureOffsetClamp:
4259 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4260 lvalue = true;
4261 break;
4262 case glslang::EOpSparseTextureGradOffset:
4263 case glslang::EOpSparseTextureGradClamp:
4264 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4265 lvalue = true;
4266 break;
4267 case glslang::EOpSparseTextureGradOffsetClamp:
4268 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4269 lvalue = true;
4270 break;
4271#else
Rex Xu48edadf2015-12-31 16:11:41 +08004272 case glslang::EOpSparseTextureLodOffset:
4273 case glslang::EOpSparseTextureGrad:
4274 case glslang::EOpSparseTextureOffsetClamp:
4275 if (i == 4)
4276 lvalue = true;
4277 break;
4278 case glslang::EOpSparseTextureGradOffset:
4279 case glslang::EOpSparseTextureGradClamp:
4280 if (i == 5)
4281 lvalue = true;
4282 break;
4283 case glslang::EOpSparseTextureGradOffsetClamp:
4284 if (i == 6)
4285 lvalue = true;
4286 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004287#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004288 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004289 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4290 lvalue = true;
4291 break;
4292 case glslang::EOpSparseTextureGatherOffset:
4293 case glslang::EOpSparseTextureGatherOffsets:
4294 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4295 lvalue = true;
4296 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004297#ifdef AMD_EXTENSIONS
4298 case glslang::EOpSparseTextureGatherLod:
4299 if (i == 3)
4300 lvalue = true;
4301 break;
4302 case glslang::EOpSparseTextureGatherLodOffset:
4303 case glslang::EOpSparseTextureGatherLodOffsets:
4304 if (i == 4)
4305 lvalue = true;
4306 break;
Rex Xu129799a2017-07-05 17:23:28 +08004307 case glslang::EOpSparseImageLoadLod:
4308 if (i == 3)
4309 lvalue = true;
4310 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004311#endif
Chao Chen3a137962018-09-19 11:41:27 -07004312#ifdef NV_EXTENSIONS
4313 case glslang::EOpImageSampleFootprintNV:
4314 if (i == 4)
4315 lvalue = true;
4316 break;
4317 case glslang::EOpImageSampleFootprintClampNV:
4318 case glslang::EOpImageSampleFootprintLodNV:
4319 if (i == 5)
4320 lvalue = true;
4321 break;
4322 case glslang::EOpImageSampleFootprintGradNV:
4323 if (i == 6)
4324 lvalue = true;
4325 break;
4326 case glslang::EOpImageSampleFootprintGradClampNV:
4327 if (i == 7)
4328 lvalue = true;
4329 break;
4330#endif
Rex Xufc618912015-09-09 16:42:49 +08004331 default:
4332 break;
4333 }
4334
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004335 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004336 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004337 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4338 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4339 } else
John Kessenich32cfd492016-02-02 12:37:46 -07004340 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004341 }
4342}
4343
John Kessenichfc51d282015-08-19 13:34:18 -06004344void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004345{
John Kessenichfc51d282015-08-19 13:34:18 -06004346 builder.clearAccessChain();
4347 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004348 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004349}
John Kessenich140f3df2015-06-26 16:58:36 -06004350
John Kessenichfc51d282015-08-19 13:34:18 -06004351spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4352{
John Kesseniche485c7a2017-05-31 18:50:53 -06004353 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004354 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004355
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004356 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004357
John Kessenichfc51d282015-08-19 13:34:18 -06004358 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004359
John Kessenichf43c7392019-03-31 10:51:57 -06004360 const glslang::TType &imageType = node->getAsAggregate()
4361 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4362 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004363 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004364#ifdef AMD_EXTENSIONS
4365 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004366 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4367 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004368#endif
4369
John Kessenichf43c7392019-03-31 10:51:57 -06004370 const auto signExtensionMask = [&]() {
4371 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4372 if (sampler.type == glslang::EbtUint)
4373 return spv::ImageOperandsZeroExtendMask;
4374 else if (sampler.type == glslang::EbtInt)
4375 return spv::ImageOperandsSignExtendMask;
4376 }
4377 return spv::ImageOperandsMaskNone;
4378 };
4379
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004380 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4381
John Kessenichfc51d282015-08-19 13:34:18 -06004382 std::vector<spv::Id> arguments;
4383 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004384 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004385 else
4386 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004387 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004388
4389 spv::Builder::TextureParameters params = { };
4390 params.sampler = arguments[0];
4391
Rex Xu04db3f52015-09-16 11:44:02 +08004392 glslang::TCrackedTextureOp cracked;
4393 node->crackTexture(sampler, cracked);
4394
amhagan05506bb2017-06-13 16:53:02 -04004395 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004396
John Kessenichfc51d282015-08-19 13:34:18 -06004397 // Check for queries
4398 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004399 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4400 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004401 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004402
John Kessenichfc51d282015-08-19 13:34:18 -06004403 switch (node->getOp()) {
4404 case glslang::EOpImageQuerySize:
4405 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004406 if (arguments.size() > 1) {
4407 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004408 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004409 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004410 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004411 case glslang::EOpImageQuerySamples:
4412 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004413 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004414 case glslang::EOpTextureQueryLod:
4415 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004416 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004417 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004418 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004419 case glslang::EOpSparseTexelsResident:
4420 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004421 default:
4422 assert(0);
4423 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004424 }
John Kessenich140f3df2015-06-26 16:58:36 -06004425 }
4426
LoopDawg4425f242018-02-18 11:40:01 -07004427 int components = node->getType().getVectorSize();
4428
4429 if (node->getOp() == glslang::EOpTextureFetch) {
4430 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4431 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4432 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4433 // here around e.g. which ones return scalars or other types.
4434 components = 4;
4435 }
4436
4437 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4438
4439 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4440
Rex Xufc618912015-09-09 16:42:49 +08004441 // Check for image functions other than queries
4442 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004443 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004444 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004445 spv::IdImmediate image = { true, *(opIt++) };
4446 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004447
4448 // Handle subpass operations
4449 // TODO: GLSL should change to have the "MS" only on the type rather than the
4450 // built-in function.
4451 if (cracked.subpass) {
4452 // add on the (0,0) coordinate
4453 spv::Id zero = builder.makeIntConstant(0);
4454 std::vector<spv::Id> comps;
4455 comps.push_back(zero);
4456 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004457 spv::IdImmediate coord = { true,
4458 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4459 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004460 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4461 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004462 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004463 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4464 }
4465 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004466 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004467 if (sampler.ms) {
4468 spv::IdImmediate imageOperand = { true, *(opIt++) };
4469 operands.push_back(imageOperand);
4470 }
John Kessenich6c292d32016-02-15 20:58:50 -07004471 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004472 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4473 builder.setPrecision(result, precision);
4474 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004475 }
4476
John Kessenich149afc32018-08-14 13:31:43 -06004477 spv::IdImmediate coord = { true, *(opIt++) };
4478 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004479#ifdef AMD_EXTENSIONS
4480 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4481#else
John Kessenich56bab042015-09-16 10:54:31 -06004482 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004483#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004484 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004485 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004486 mask = mask | spv::ImageOperandsSampleMask;
4487 }
Rex Xu129799a2017-07-05 17:23:28 +08004488#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004489 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004490 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4491 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004492 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004493 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004494#endif
4495 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4496 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004497 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004498 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004499 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4500 operands.push_back(imageOperands);
4501 }
4502 if (mask & spv::ImageOperandsSampleMask) {
4503 spv::IdImmediate imageOperand = { true, *opIt++ };
4504 operands.push_back(imageOperand);
4505 }
4506#ifdef AMD_EXTENSIONS
4507 if (mask & spv::ImageOperandsLodMask) {
4508 spv::IdImmediate imageOperand = { true, *opIt++ };
4509 operands.push_back(imageOperand);
4510 }
4511#endif
4512 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004513 spv::IdImmediate imageOperand = { true,
4514 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004515 operands.push_back(imageOperand);
4516 }
4517
John Kessenich149afc32018-08-14 13:31:43 -06004518 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004519 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004520
John Kessenich149afc32018-08-14 13:31:43 -06004521 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004522 builder.setPrecision(result[0], precision);
4523
4524 // If needed, add a conversion constructor to the proper size.
4525 if (components != node->getType().getVectorSize())
4526 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4527
4528 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004529#ifdef AMD_EXTENSIONS
4530 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4531#else
John Kessenich56bab042015-09-16 10:54:31 -06004532 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004533#endif
Rex Xu129799a2017-07-05 17:23:28 +08004534
Jeff Bolz36831c92018-09-05 10:11:41 -05004535 // Push the texel value before the operands
4536#ifdef AMD_EXTENSIONS
4537 if (sampler.ms || cracked.lod) {
4538#else
4539 if (sampler.ms) {
4540#endif
John Kessenich149afc32018-08-14 13:31:43 -06004541 spv::IdImmediate texel = { true, *(opIt + 1) };
4542 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004543 } else {
4544 spv::IdImmediate texel = { true, *opIt };
4545 operands.push_back(texel);
4546 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004547
4548 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4549 if (sampler.ms) {
4550 mask = mask | spv::ImageOperandsSampleMask;
4551 }
4552#ifdef AMD_EXTENSIONS
4553 if (cracked.lod) {
4554 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4555 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4556 mask = mask | spv::ImageOperandsLodMask;
4557 }
4558#endif
4559 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4560 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004561 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004562 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004563 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4564 operands.push_back(imageOperands);
4565 }
4566 if (mask & spv::ImageOperandsSampleMask) {
4567 spv::IdImmediate imageOperand = { true, *opIt++ };
4568 operands.push_back(imageOperand);
4569 }
4570#ifdef AMD_EXTENSIONS
4571 if (mask & spv::ImageOperandsLodMask) {
4572 spv::IdImmediate imageOperand = { true, *opIt++ };
4573 operands.push_back(imageOperand);
4574 }
4575#endif
4576 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004577 spv::IdImmediate imageOperand = { true,
4578 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004579 operands.push_back(imageOperand);
4580 }
4581
John Kessenich56bab042015-09-16 10:54:31 -06004582 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004583 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004584 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004585 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004586#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004587 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4588 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004589#else
Rex Xu5eafa472016-02-19 22:24:03 +08004590 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004591#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004592 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004593 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004594 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4595
Jeff Bolz36831c92018-09-05 10:11:41 -05004596 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004597 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004598 mask = mask | spv::ImageOperandsSampleMask;
4599 }
Rex Xu129799a2017-07-05 17:23:28 +08004600#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004601 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004602 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4603 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4604
Jeff Bolz36831c92018-09-05 10:11:41 -05004605 mask = mask | spv::ImageOperandsLodMask;
4606 }
4607#endif
4608 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4609 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004610 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004611 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004612 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004613 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004614 }
4615 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004616 spv::IdImmediate imageOperand = { true, *opIt++ };
4617 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004618 }
4619#ifdef AMD_EXTENSIONS
4620 if (mask & spv::ImageOperandsLodMask) {
4621 spv::IdImmediate imageOperand = { true, *opIt++ };
4622 operands.push_back(imageOperand);
4623 }
Rex Xu129799a2017-07-05 17:23:28 +08004624#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004625 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4626 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4627 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004628 }
4629
4630 // Create the return type that was a special structure
4631 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004632 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004633 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4634 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4635
4636 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4637
4638 // Decode the return type
4639 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4640 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004641 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004642 // Process image atomic operations
4643
4644 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4645 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004646 // For non-MS, the sample value should be 0
4647 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4648 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004649
Jeff Bolz36831c92018-09-05 10:11:41 -05004650 spv::Id resultTypeId;
4651 // imageAtomicStore has a void return type so base the pointer type on
4652 // the type of the value operand.
4653 if (node->getOp() == glslang::EOpImageAtomicStore) {
4654 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4655 } else {
4656 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4657 }
John Kessenich56bab042015-09-16 10:54:31 -06004658 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004659
4660 std::vector<spv::Id> operands;
4661 operands.push_back(pointer);
4662 for (; opIt != arguments.end(); ++opIt)
4663 operands.push_back(*opIt);
4664
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004665 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004666 }
4667 }
4668
amhagan05506bb2017-06-13 16:53:02 -04004669#ifdef AMD_EXTENSIONS
4670 // Check for fragment mask functions other than queries
4671 if (cracked.fragMask) {
4672 assert(sampler.ms);
4673
4674 auto opIt = arguments.begin();
4675 std::vector<spv::Id> operands;
4676
4677 // Extract the image if necessary
4678 if (builder.isSampledImage(params.sampler))
4679 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4680
4681 operands.push_back(params.sampler);
4682 ++opIt;
4683
4684 if (sampler.isSubpass()) {
4685 // add on the (0,0) coordinate
4686 spv::Id zero = builder.makeIntConstant(0);
4687 std::vector<spv::Id> comps;
4688 comps.push_back(zero);
4689 comps.push_back(zero);
4690 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4691 }
4692
4693 for (; opIt != arguments.end(); ++opIt)
4694 operands.push_back(*opIt);
4695
4696 spv::Op fragMaskOp = spv::OpNop;
4697 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4698 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4699 else if (node->getOp() == glslang::EOpFragmentFetch)
4700 fragMaskOp = spv::OpFragmentFetchAMD;
4701
4702 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4703 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4704 return builder.createOp(fragMaskOp, resultType(), operands);
4705 }
4706#endif
4707
Rex Xufc618912015-09-09 16:42:49 +08004708 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004709 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004710#ifdef NV_EXTENSIONS
4711 bool imageFootprint = node->isImageFootprint();
4712#endif
4713
Rex Xu71519fe2015-11-11 15:35:47 +08004714 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4715
John Kessenichfc51d282015-08-19 13:34:18 -06004716 // check for bias argument
4717 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004718#ifdef AMD_EXTENSIONS
4719 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4720#else
Rex Xu71519fe2015-11-11 15:35:47 +08004721 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004722#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004723 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004724#ifdef AMD_EXTENSIONS
4725 if (cracked.gather)
4726 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004727
4728 if (f16ShadowCompare)
4729 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004730#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004731 if (cracked.offset)
4732 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004733#ifdef AMD_EXTENSIONS
4734 else if (cracked.offsets)
4735 ++nonBiasArgCount;
4736#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004737 if (cracked.grad)
4738 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004739 if (cracked.lodClamp)
4740 ++nonBiasArgCount;
4741 if (sparse)
4742 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004743#ifdef NV_EXTENSIONS
4744 if (imageFootprint)
4745 //Following three extra arguments
4746 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4747 nonBiasArgCount += 3;
4748#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004749 if ((int)arguments.size() > nonBiasArgCount)
4750 bias = true;
4751 }
4752
John Kessenicha5c33d62016-06-02 23:45:21 -06004753 // See if the sampler param should really be just the SPV image part
4754 if (cracked.fetch) {
4755 // a fetch needs to have the image extracted first
4756 if (builder.isSampledImage(params.sampler))
4757 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4758 }
4759
Rex Xu225e0fc2016-11-17 17:47:59 +08004760#ifdef AMD_EXTENSIONS
4761 if (cracked.gather) {
4762 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4763 if (bias || cracked.lod ||
4764 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4765 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004766 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004767 }
4768 }
4769#endif
4770
John Kessenichfc51d282015-08-19 13:34:18 -06004771 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004772
John Kessenichfc51d282015-08-19 13:34:18 -06004773 params.coords = arguments[1];
4774 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004775 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004776
4777 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004778#ifdef AMD_EXTENSIONS
4779 if (cubeCompare || f16ShadowCompare) {
4780#else
Rex Xu48edadf2015-12-31 16:11:41 +08004781 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004782#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004783 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004784 ++extraArgs;
4785 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004786 params.Dref = arguments[2];
4787 ++extraArgs;
4788 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004789 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004790 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004791 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004792 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004793 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004794 dRefComp = builder.getNumComponents(params.coords) - 1;
4795 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004796 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4797 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004798
4799 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004800 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004801 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004802 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004803 } else if (glslangIntermediate->getStage() != EShLangFragment
4804#ifdef NV_EXTENSIONS
4805 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4806 && !(glslangIntermediate->getStage() == EShLangCompute &&
4807 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4808#endif
4809 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004810 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4811 noImplicitLod = true;
4812 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004813
4814 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004815 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004816 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004817 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004818 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004819
4820 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004821 if (cracked.grad) {
4822 params.gradX = arguments[2 + extraArgs];
4823 params.gradY = arguments[3 + extraArgs];
4824 extraArgs += 2;
4825 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004826
4827 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004828 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004829 params.offset = arguments[2 + extraArgs];
4830 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004831 } else if (cracked.offsets) {
4832 params.offsets = arguments[2 + extraArgs];
4833 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004834 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004835
4836 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004837 if (cracked.lodClamp) {
4838 params.lodClamp = arguments[2 + extraArgs];
4839 ++extraArgs;
4840 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004841 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004842 if (sparse) {
4843 params.texelOut = arguments[2 + extraArgs];
4844 ++extraArgs;
4845 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004846
John Kessenich76d4dfc2016-06-16 12:43:23 -06004847 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004848 if (cracked.gather && ! sampler.shadow) {
4849 // default component is 0, if missing, otherwise an argument
4850 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004851 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004852 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004853 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004854 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004855 }
Chao Chen3a137962018-09-19 11:41:27 -07004856#ifdef NV_EXTENSIONS
4857 spv::Id resultStruct = spv::NoResult;
4858 if (imageFootprint) {
4859 //Following three extra arguments
4860 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4861 params.granularity = arguments[2 + extraArgs];
4862 params.coarse = arguments[3 + extraArgs];
4863 resultStruct = arguments[4 + extraArgs];
4864 extraArgs += 3;
4865 }
4866#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004867 // bias
4868 if (bias) {
4869 params.bias = arguments[2 + extraArgs];
4870 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004871 }
John Kessenichfc51d282015-08-19 13:34:18 -06004872
Chao Chen3a137962018-09-19 11:41:27 -07004873#ifdef NV_EXTENSIONS
4874 if (imageFootprint) {
4875 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4876 builder.addCapability(spv::CapabilityImageFootprintNV);
4877
4878
4879 //resultStructType(OpenGL type) contains 5 elements:
4880 //struct gl_TextureFootprint2DNV {
4881 // uvec2 anchor;
4882 // uvec2 offset;
4883 // uvec2 mask;
4884 // uint lod;
4885 // uint granularity;
4886 //};
4887 //or
4888 //struct gl_TextureFootprint3DNV {
4889 // uvec3 anchor;
4890 // uvec3 offset;
4891 // uvec2 mask;
4892 // uint lod;
4893 // uint granularity;
4894 //};
4895 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4896 assert(builder.isStructType(resultStructType));
4897
4898 //resType (SPIR-V type) contains 6 elements:
4899 //Member 0 must be a Boolean type scalar(LOD),
4900 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4901 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4902 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4903 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4904 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4905 std::vector<spv::Id> members;
4906 members.push_back(resultType());
4907 for (int i = 0; i < 5; i++) {
4908 members.push_back(builder.getContainedTypeId(resultStructType, i));
4909 }
4910 spv::Id resType = builder.makeStructType(members, "ResType");
4911
4912 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004913 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4914 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004915
4916 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4917 for (int i = 0; i < 5; i++) {
4918 builder.clearAccessChain();
4919 builder.setAccessChainLValue(resultStruct);
4920
4921 //Accessing to a struct we created, no coherent flag is set
4922 spv::Builder::AccessChain::CoherentFlags flags;
4923 flags.clear();
4924
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004925 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004926 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4927 }
4928 return builder.createCompositeExtract(res, resultType(), 0);
4929 }
4930#endif
4931
John Kessenich65336482016-06-16 14:06:26 -06004932 // projective component (might not to move)
4933 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4934 // are divided by the last component of P."
4935 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4936 // unused components will appear after all used components."
4937 if (cracked.proj) {
4938 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4939 int projTargetComp;
4940 switch (sampler.dim) {
4941 case glslang::Esd1D: projTargetComp = 1; break;
4942 case glslang::Esd2D: projTargetComp = 2; break;
4943 case glslang::EsdRect: projTargetComp = 2; break;
4944 default: projTargetComp = projSourceComp; break;
4945 }
4946 // copy the projective coordinate if we have to
4947 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004948 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004949 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4950 projSourceComp);
4951 params.coords = builder.createCompositeInsert(projComp, params.coords,
4952 builder.getTypeId(params.coords), projTargetComp);
4953 }
4954 }
4955
Jeff Bolz36831c92018-09-05 10:11:41 -05004956 // nonprivate
4957 if (imageType.getQualifier().nonprivate) {
4958 params.nonprivate = true;
4959 }
4960
4961 // volatile
4962 if (imageType.getQualifier().volatil) {
4963 params.volatil = true;
4964 }
4965
St0fFa1184dd2018-04-09 21:08:14 +02004966 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004967 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4968 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004969 );
LoopDawg4425f242018-02-18 11:40:01 -07004970
4971 if (components != node->getType().getVectorSize())
4972 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4973
4974 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004975}
4976
4977spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4978{
4979 // Grab the function's pointer from the previously created function
4980 spv::Function* function = functionMap[node->getName().c_str()];
4981 if (! function)
4982 return 0;
4983
4984 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4985 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4986
4987 // See comments in makeFunctions() for details about the semantics for parameter passing.
4988 //
4989 // These imply we need a four step process:
4990 // 1. Evaluate the arguments
4991 // 2. Allocate and make copies of in, out, and inout arguments
4992 // 3. Make the call
4993 // 4. Copy back the results
4994
John Kessenichd3ed90b2018-05-04 11:43:03 -06004995 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004996 std::vector<spv::Builder::AccessChain> lValues;
4997 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004998 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004999 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005000 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005001 // build l-value
5002 builder.clearAccessChain();
5003 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005004 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005005 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005006 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005007 // save l-value
5008 lValues.push_back(builder.getAccessChain());
5009 } else {
5010 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005011 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005012 }
5013 }
5014
5015 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5016 // copy the original into that space.
5017 //
5018 // Also, build up the list of actual arguments to pass in for the call
5019 int lValueCount = 0;
5020 int rValueCount = 0;
5021 std::vector<spv::Id> spvArgs;
5022 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5023 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005024 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005025 builder.setAccessChain(lValues[lValueCount]);
5026 arg = builder.accessChainGetLValue();
5027 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005028 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005029 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005030 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005031 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5032 // need to copy the input into output space
5033 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005034 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005035 builder.clearAccessChain();
5036 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005037 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005038 }
5039 ++lValueCount;
5040 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005041 // process r-value, which involves a copy for a type mismatch
5042 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5043 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5044 builder.clearAccessChain();
5045 builder.setAccessChainLValue(argCopy);
5046 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5047 arg = builder.createLoad(argCopy);
5048 } else
5049 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005050 ++rValueCount;
5051 }
5052 spvArgs.push_back(arg);
5053 }
5054
5055 // 3. Make the call.
5056 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005057 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005058
5059 // 4. Copy back out an "out" arguments.
5060 lValueCount = 0;
5061 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005062 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005063 ++lValueCount;
5064 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005065 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5066 spv::Id copy = builder.createLoad(spvArgs[a]);
5067 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005068 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005069 }
5070 ++lValueCount;
5071 }
5072 }
5073
5074 return result;
5075}
5076
5077// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005078spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005079 spv::Id typeId, spv::Id left, spv::Id right,
5080 glslang::TBasicType typeProxy, bool reduceComparison)
5081{
John Kessenich66011cb2018-03-06 16:12:04 -07005082 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5083 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005084 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005085
5086 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005087 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005088 bool comparison = false;
5089
5090 switch (op) {
5091 case glslang::EOpAdd:
5092 case glslang::EOpAddAssign:
5093 if (isFloat)
5094 binOp = spv::OpFAdd;
5095 else
5096 binOp = spv::OpIAdd;
5097 break;
5098 case glslang::EOpSub:
5099 case glslang::EOpSubAssign:
5100 if (isFloat)
5101 binOp = spv::OpFSub;
5102 else
5103 binOp = spv::OpISub;
5104 break;
5105 case glslang::EOpMul:
5106 case glslang::EOpMulAssign:
5107 if (isFloat)
5108 binOp = spv::OpFMul;
5109 else
5110 binOp = spv::OpIMul;
5111 break;
5112 case glslang::EOpVectorTimesScalar:
5113 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005114 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005115 if (builder.isVector(right))
5116 std::swap(left, right);
5117 assert(builder.isScalar(right));
5118 needMatchingVectors = false;
5119 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005120 } else if (isFloat)
5121 binOp = spv::OpFMul;
5122 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005123 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005124 break;
5125 case glslang::EOpVectorTimesMatrix:
5126 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005127 binOp = spv::OpVectorTimesMatrix;
5128 break;
5129 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005130 binOp = spv::OpMatrixTimesVector;
5131 break;
5132 case glslang::EOpMatrixTimesScalar:
5133 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005134 binOp = spv::OpMatrixTimesScalar;
5135 break;
5136 case glslang::EOpMatrixTimesMatrix:
5137 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005138 binOp = spv::OpMatrixTimesMatrix;
5139 break;
5140 case glslang::EOpOuterProduct:
5141 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005142 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005143 break;
5144
5145 case glslang::EOpDiv:
5146 case glslang::EOpDivAssign:
5147 if (isFloat)
5148 binOp = spv::OpFDiv;
5149 else if (isUnsigned)
5150 binOp = spv::OpUDiv;
5151 else
5152 binOp = spv::OpSDiv;
5153 break;
5154 case glslang::EOpMod:
5155 case glslang::EOpModAssign:
5156 if (isFloat)
5157 binOp = spv::OpFMod;
5158 else if (isUnsigned)
5159 binOp = spv::OpUMod;
5160 else
5161 binOp = spv::OpSMod;
5162 break;
5163 case glslang::EOpRightShift:
5164 case glslang::EOpRightShiftAssign:
5165 if (isUnsigned)
5166 binOp = spv::OpShiftRightLogical;
5167 else
5168 binOp = spv::OpShiftRightArithmetic;
5169 break;
5170 case glslang::EOpLeftShift:
5171 case glslang::EOpLeftShiftAssign:
5172 binOp = spv::OpShiftLeftLogical;
5173 break;
5174 case glslang::EOpAnd:
5175 case glslang::EOpAndAssign:
5176 binOp = spv::OpBitwiseAnd;
5177 break;
5178 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005179 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005180 binOp = spv::OpLogicalAnd;
5181 break;
5182 case glslang::EOpInclusiveOr:
5183 case glslang::EOpInclusiveOrAssign:
5184 binOp = spv::OpBitwiseOr;
5185 break;
5186 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005187 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005188 binOp = spv::OpLogicalOr;
5189 break;
5190 case glslang::EOpExclusiveOr:
5191 case glslang::EOpExclusiveOrAssign:
5192 binOp = spv::OpBitwiseXor;
5193 break;
5194 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005195 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005196 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005197 break;
5198
5199 case glslang::EOpLessThan:
5200 case glslang::EOpGreaterThan:
5201 case glslang::EOpLessThanEqual:
5202 case glslang::EOpGreaterThanEqual:
5203 case glslang::EOpEqual:
5204 case glslang::EOpNotEqual:
5205 case glslang::EOpVectorEqual:
5206 case glslang::EOpVectorNotEqual:
5207 comparison = true;
5208 break;
5209 default:
5210 break;
5211 }
5212
John Kessenich7c1aa102015-10-15 13:29:11 -06005213 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005214 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005215 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005216 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5217 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005218 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005219
5220 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005221 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005222 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005223
qining25262b32016-05-06 17:25:16 -04005224 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005225 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005226 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005227 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005228 }
5229
5230 if (! comparison)
5231 return 0;
5232
John Kessenich7c1aa102015-10-15 13:29:11 -06005233 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005234
John Kessenich4583b612016-08-07 19:14:22 -06005235 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005236 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5237 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005238 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005239 return result;
5240 }
John Kessenich140f3df2015-06-26 16:58:36 -06005241
5242 switch (op) {
5243 case glslang::EOpLessThan:
5244 if (isFloat)
5245 binOp = spv::OpFOrdLessThan;
5246 else if (isUnsigned)
5247 binOp = spv::OpULessThan;
5248 else
5249 binOp = spv::OpSLessThan;
5250 break;
5251 case glslang::EOpGreaterThan:
5252 if (isFloat)
5253 binOp = spv::OpFOrdGreaterThan;
5254 else if (isUnsigned)
5255 binOp = spv::OpUGreaterThan;
5256 else
5257 binOp = spv::OpSGreaterThan;
5258 break;
5259 case glslang::EOpLessThanEqual:
5260 if (isFloat)
5261 binOp = spv::OpFOrdLessThanEqual;
5262 else if (isUnsigned)
5263 binOp = spv::OpULessThanEqual;
5264 else
5265 binOp = spv::OpSLessThanEqual;
5266 break;
5267 case glslang::EOpGreaterThanEqual:
5268 if (isFloat)
5269 binOp = spv::OpFOrdGreaterThanEqual;
5270 else if (isUnsigned)
5271 binOp = spv::OpUGreaterThanEqual;
5272 else
5273 binOp = spv::OpSGreaterThanEqual;
5274 break;
5275 case glslang::EOpEqual:
5276 case glslang::EOpVectorEqual:
5277 if (isFloat)
5278 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005279 else if (isBool)
5280 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005281 else
5282 binOp = spv::OpIEqual;
5283 break;
5284 case glslang::EOpNotEqual:
5285 case glslang::EOpVectorNotEqual:
5286 if (isFloat)
5287 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005288 else if (isBool)
5289 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005290 else
5291 binOp = spv::OpINotEqual;
5292 break;
5293 default:
5294 break;
5295 }
5296
qining25262b32016-05-06 17:25:16 -04005297 if (binOp != spv::OpNop) {
5298 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005299 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005300 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005301 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005302 }
John Kessenich140f3df2015-06-26 16:58:36 -06005303
5304 return 0;
5305}
5306
John Kessenich04bb8a02015-12-12 12:28:14 -07005307//
5308// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5309// These can be any of:
5310//
5311// matrix * scalar
5312// scalar * matrix
5313// matrix * matrix linear algebraic
5314// matrix * vector
5315// vector * matrix
5316// matrix * matrix componentwise
5317// matrix op matrix op in {+, -, /}
5318// matrix op scalar op in {+, -, /}
5319// scalar op matrix op in {+, -, /}
5320//
John Kessenichead86222018-03-28 18:01:20 -06005321spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5322 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005323{
5324 bool firstClass = true;
5325
5326 // First, handle first-class matrix operations (* and matrix/scalar)
5327 switch (op) {
5328 case spv::OpFDiv:
5329 if (builder.isMatrix(left) && builder.isScalar(right)) {
5330 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005331 spv::Id resultType = builder.getTypeId(right);
5332 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005333 op = spv::OpMatrixTimesScalar;
5334 } else
5335 firstClass = false;
5336 break;
5337 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005338 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005339 std::swap(left, right);
5340 assert(builder.isScalar(right));
5341 break;
5342 case spv::OpVectorTimesMatrix:
5343 assert(builder.isVector(left));
5344 assert(builder.isMatrix(right));
5345 break;
5346 case spv::OpMatrixTimesVector:
5347 assert(builder.isMatrix(left));
5348 assert(builder.isVector(right));
5349 break;
5350 case spv::OpMatrixTimesMatrix:
5351 assert(builder.isMatrix(left));
5352 assert(builder.isMatrix(right));
5353 break;
5354 default:
5355 firstClass = false;
5356 break;
5357 }
5358
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005359 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5360 firstClass = true;
5361
qining25262b32016-05-06 17:25:16 -04005362 if (firstClass) {
5363 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005364 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005365 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005366 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005367 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005368
LoopDawg592860c2016-06-09 08:57:35 -06005369 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005370 // The result type of all of them is the same type as the (a) matrix operand.
5371 // The algorithm is to:
5372 // - break the matrix(es) into vectors
5373 // - smear any scalar to a vector
5374 // - do vector operations
5375 // - make a matrix out the vector results
5376 switch (op) {
5377 case spv::OpFAdd:
5378 case spv::OpFSub:
5379 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005380 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005381 case spv::OpFMul:
5382 {
5383 // one time set up...
5384 bool leftMat = builder.isMatrix(left);
5385 bool rightMat = builder.isMatrix(right);
5386 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5387 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5388 spv::Id scalarType = builder.getScalarTypeId(typeId);
5389 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5390 std::vector<spv::Id> results;
5391 spv::Id smearVec = spv::NoResult;
5392 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005393 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005394 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005395 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005396
5397 // do each vector op
5398 for (unsigned int c = 0; c < numCols; ++c) {
5399 std::vector<unsigned int> indexes;
5400 indexes.push_back(c);
5401 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5402 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005403 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005404 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005405 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005406 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005407 }
5408
5409 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005410 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005411 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005412 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005413 }
5414 default:
5415 assert(0);
5416 return spv::NoResult;
5417 }
5418}
5419
John Kessenichead86222018-03-28 18:01:20 -06005420spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005421 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005422{
5423 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005424 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005425 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005426 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5427 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005428
5429 switch (op) {
5430 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005431 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005432 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005433 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005434 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005435 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005436 unaryOp = spv::OpSNegate;
5437 break;
5438
5439 case glslang::EOpLogicalNot:
5440 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005441 unaryOp = spv::OpLogicalNot;
5442 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005443 case glslang::EOpBitwiseNot:
5444 unaryOp = spv::OpNot;
5445 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005446
John Kessenich140f3df2015-06-26 16:58:36 -06005447 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005448 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005449 break;
5450 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005451 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005452 break;
5453 case glslang::EOpTranspose:
5454 unaryOp = spv::OpTranspose;
5455 break;
5456
5457 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005458 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005459 break;
5460 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005461 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 break;
5463 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005464 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005465 break;
5466 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005467 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005468 break;
5469 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005470 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005471 break;
5472 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005473 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005474 break;
5475 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005476 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005477 break;
5478 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005479 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005480 break;
5481
5482 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005483 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005484 break;
5485 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005486 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005487 break;
5488 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005489 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005490 break;
5491 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005492 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005493 break;
5494 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005495 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005496 break;
5497 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005498 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005499 break;
5500
5501 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005502 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005503 break;
5504 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005505 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005506 break;
5507
5508 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005509 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005510 break;
5511 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005512 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005513 break;
5514 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005515 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005516 break;
5517 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005518 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005519 break;
5520 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005521 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005522 break;
5523 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005524 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005525 break;
5526
5527 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005528 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005529 break;
5530 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005531 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005532 break;
5533 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005534 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005535 break;
5536 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005537 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005538 break;
5539 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005540 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005541 break;
5542 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005543 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005544 break;
5545
5546 case glslang::EOpIsNan:
5547 unaryOp = spv::OpIsNan;
5548 break;
5549 case glslang::EOpIsInf:
5550 unaryOp = spv::OpIsInf;
5551 break;
LoopDawg592860c2016-06-09 08:57:35 -06005552 case glslang::EOpIsFinite:
5553 unaryOp = spv::OpIsFinite;
5554 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005555
Rex Xucbc426e2015-12-15 16:03:10 +08005556 case glslang::EOpFloatBitsToInt:
5557 case glslang::EOpFloatBitsToUint:
5558 case glslang::EOpIntBitsToFloat:
5559 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005560 case glslang::EOpDoubleBitsToInt64:
5561 case glslang::EOpDoubleBitsToUint64:
5562 case glslang::EOpInt64BitsToDouble:
5563 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005564 case glslang::EOpFloat16BitsToInt16:
5565 case glslang::EOpFloat16BitsToUint16:
5566 case glslang::EOpInt16BitsToFloat16:
5567 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005568 unaryOp = spv::OpBitcast;
5569 break;
5570
John Kessenich140f3df2015-06-26 16:58:36 -06005571 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005572 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005573 break;
5574 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005575 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005576 break;
5577 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005578 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005579 break;
5580 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005581 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005582 break;
5583 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005584 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005585 break;
5586 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005587 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005588 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005589 case glslang::EOpPackSnorm4x8:
5590 libCall = spv::GLSLstd450PackSnorm4x8;
5591 break;
5592 case glslang::EOpUnpackSnorm4x8:
5593 libCall = spv::GLSLstd450UnpackSnorm4x8;
5594 break;
5595 case glslang::EOpPackUnorm4x8:
5596 libCall = spv::GLSLstd450PackUnorm4x8;
5597 break;
5598 case glslang::EOpUnpackUnorm4x8:
5599 libCall = spv::GLSLstd450UnpackUnorm4x8;
5600 break;
5601 case glslang::EOpPackDouble2x32:
5602 libCall = spv::GLSLstd450PackDouble2x32;
5603 break;
5604 case glslang::EOpUnpackDouble2x32:
5605 libCall = spv::GLSLstd450UnpackDouble2x32;
5606 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005607
Rex Xu8ff43de2016-04-22 16:51:45 +08005608 case glslang::EOpPackInt2x32:
5609 case glslang::EOpUnpackInt2x32:
5610 case glslang::EOpPackUint2x32:
5611 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005612 case glslang::EOpPack16:
5613 case glslang::EOpPack32:
5614 case glslang::EOpPack64:
5615 case glslang::EOpUnpack32:
5616 case glslang::EOpUnpack16:
5617 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005618 case glslang::EOpPackInt2x16:
5619 case glslang::EOpUnpackInt2x16:
5620 case glslang::EOpPackUint2x16:
5621 case glslang::EOpUnpackUint2x16:
5622 case glslang::EOpPackInt4x16:
5623 case glslang::EOpUnpackInt4x16:
5624 case glslang::EOpPackUint4x16:
5625 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005626 case glslang::EOpPackFloat2x16:
5627 case glslang::EOpUnpackFloat2x16:
5628 unaryOp = spv::OpBitcast;
5629 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005630
John Kessenich140f3df2015-06-26 16:58:36 -06005631 case glslang::EOpDPdx:
5632 unaryOp = spv::OpDPdx;
5633 break;
5634 case glslang::EOpDPdy:
5635 unaryOp = spv::OpDPdy;
5636 break;
5637 case glslang::EOpFwidth:
5638 unaryOp = spv::OpFwidth;
5639 break;
5640 case glslang::EOpDPdxFine:
5641 unaryOp = spv::OpDPdxFine;
5642 break;
5643 case glslang::EOpDPdyFine:
5644 unaryOp = spv::OpDPdyFine;
5645 break;
5646 case glslang::EOpFwidthFine:
5647 unaryOp = spv::OpFwidthFine;
5648 break;
5649 case glslang::EOpDPdxCoarse:
5650 unaryOp = spv::OpDPdxCoarse;
5651 break;
5652 case glslang::EOpDPdyCoarse:
5653 unaryOp = spv::OpDPdyCoarse;
5654 break;
5655 case glslang::EOpFwidthCoarse:
5656 unaryOp = spv::OpFwidthCoarse;
5657 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005658 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005659#ifdef AMD_EXTENSIONS
5660 if (typeProxy == glslang::EbtFloat16)
5661 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5662#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005663 libCall = spv::GLSLstd450InterpolateAtCentroid;
5664 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005665 case glslang::EOpAny:
5666 unaryOp = spv::OpAny;
5667 break;
5668 case glslang::EOpAll:
5669 unaryOp = spv::OpAll;
5670 break;
5671
5672 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005673 if (isFloat)
5674 libCall = spv::GLSLstd450FAbs;
5675 else
5676 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005677 break;
5678 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005679 if (isFloat)
5680 libCall = spv::GLSLstd450FSign;
5681 else
5682 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005683 break;
5684
John Kessenichfc51d282015-08-19 13:34:18 -06005685 case glslang::EOpAtomicCounterIncrement:
5686 case glslang::EOpAtomicCounterDecrement:
5687 case glslang::EOpAtomicCounter:
5688 {
5689 // Handle all of the atomics in one place, in createAtomicOperation()
5690 std::vector<spv::Id> operands;
5691 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005692 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005693 }
5694
John Kessenichfc51d282015-08-19 13:34:18 -06005695 case glslang::EOpBitFieldReverse:
5696 unaryOp = spv::OpBitReverse;
5697 break;
5698 case glslang::EOpBitCount:
5699 unaryOp = spv::OpBitCount;
5700 break;
5701 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005702 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005703 break;
5704 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005705 if (isUnsigned)
5706 libCall = spv::GLSLstd450FindUMsb;
5707 else
5708 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005709 break;
5710
Rex Xu574ab042016-04-14 16:53:07 +08005711 case glslang::EOpBallot:
5712 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005713 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005714 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005715 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005716#ifdef AMD_EXTENSIONS
5717 case glslang::EOpMinInvocations:
5718 case glslang::EOpMaxInvocations:
5719 case glslang::EOpAddInvocations:
5720 case glslang::EOpMinInvocationsNonUniform:
5721 case glslang::EOpMaxInvocationsNonUniform:
5722 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005723 case glslang::EOpMinInvocationsInclusiveScan:
5724 case glslang::EOpMaxInvocationsInclusiveScan:
5725 case glslang::EOpAddInvocationsInclusiveScan:
5726 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5727 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5728 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5729 case glslang::EOpMinInvocationsExclusiveScan:
5730 case glslang::EOpMaxInvocationsExclusiveScan:
5731 case glslang::EOpAddInvocationsExclusiveScan:
5732 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5733 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5734 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005735#endif
Rex Xu51596642016-09-21 18:56:12 +08005736 {
5737 std::vector<spv::Id> operands;
5738 operands.push_back(operand);
5739 return createInvocationsOperation(op, typeId, operands, typeProxy);
5740 }
John Kessenich66011cb2018-03-06 16:12:04 -07005741 case glslang::EOpSubgroupAll:
5742 case glslang::EOpSubgroupAny:
5743 case glslang::EOpSubgroupAllEqual:
5744 case glslang::EOpSubgroupBroadcastFirst:
5745 case glslang::EOpSubgroupBallot:
5746 case glslang::EOpSubgroupInverseBallot:
5747 case glslang::EOpSubgroupBallotBitCount:
5748 case glslang::EOpSubgroupBallotInclusiveBitCount:
5749 case glslang::EOpSubgroupBallotExclusiveBitCount:
5750 case glslang::EOpSubgroupBallotFindLSB:
5751 case glslang::EOpSubgroupBallotFindMSB:
5752 case glslang::EOpSubgroupAdd:
5753 case glslang::EOpSubgroupMul:
5754 case glslang::EOpSubgroupMin:
5755 case glslang::EOpSubgroupMax:
5756 case glslang::EOpSubgroupAnd:
5757 case glslang::EOpSubgroupOr:
5758 case glslang::EOpSubgroupXor:
5759 case glslang::EOpSubgroupInclusiveAdd:
5760 case glslang::EOpSubgroupInclusiveMul:
5761 case glslang::EOpSubgroupInclusiveMin:
5762 case glslang::EOpSubgroupInclusiveMax:
5763 case glslang::EOpSubgroupInclusiveAnd:
5764 case glslang::EOpSubgroupInclusiveOr:
5765 case glslang::EOpSubgroupInclusiveXor:
5766 case glslang::EOpSubgroupExclusiveAdd:
5767 case glslang::EOpSubgroupExclusiveMul:
5768 case glslang::EOpSubgroupExclusiveMin:
5769 case glslang::EOpSubgroupExclusiveMax:
5770 case glslang::EOpSubgroupExclusiveAnd:
5771 case glslang::EOpSubgroupExclusiveOr:
5772 case glslang::EOpSubgroupExclusiveXor:
5773 case glslang::EOpSubgroupQuadSwapHorizontal:
5774 case glslang::EOpSubgroupQuadSwapVertical:
5775 case glslang::EOpSubgroupQuadSwapDiagonal: {
5776 std::vector<spv::Id> operands;
5777 operands.push_back(operand);
5778 return createSubgroupOperation(op, typeId, operands, typeProxy);
5779 }
Rex Xu9d93a232016-05-05 12:30:44 +08005780#ifdef AMD_EXTENSIONS
5781 case glslang::EOpMbcnt:
5782 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5783 libCall = spv::MbcntAMD;
5784 break;
5785
5786 case glslang::EOpCubeFaceIndex:
5787 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5788 libCall = spv::CubeFaceIndexAMD;
5789 break;
5790
5791 case glslang::EOpCubeFaceCoord:
5792 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5793 libCall = spv::CubeFaceCoordAMD;
5794 break;
5795#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005796#ifdef NV_EXTENSIONS
5797 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005798 unaryOp = spv::OpGroupNonUniformPartitionNV;
5799 break;
5800#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005801 case glslang::EOpConstructReference:
5802 unaryOp = spv::OpBitcast;
5803 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005804
5805 case glslang::EOpCopyObject:
5806 unaryOp = spv::OpCopyObject;
5807 break;
5808
John Kessenich140f3df2015-06-26 16:58:36 -06005809 default:
5810 return 0;
5811 }
5812
5813 spv::Id id;
5814 if (libCall >= 0) {
5815 std::vector<spv::Id> args;
5816 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005817 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005818 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005819 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005820 }
John Kessenich140f3df2015-06-26 16:58:36 -06005821
John Kessenichead86222018-03-28 18:01:20 -06005822 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005823 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005824 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005825}
5826
John Kessenich7a53f762016-01-20 11:19:27 -07005827// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005828spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5829 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005830{
5831 // Handle unary operations vector by vector.
5832 // The result type is the same type as the original type.
5833 // The algorithm is to:
5834 // - break the matrix into vectors
5835 // - apply the operation to each vector
5836 // - make a matrix out the vector results
5837
5838 // get the types sorted out
5839 int numCols = builder.getNumColumns(operand);
5840 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005841 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5842 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005843 std::vector<spv::Id> results;
5844
5845 // do each vector op
5846 for (int c = 0; c < numCols; ++c) {
5847 std::vector<unsigned int> indexes;
5848 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005849 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5850 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005851 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005852 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005853 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005854 }
5855
5856 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005857 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005858 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005859 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005860}
5861
John Kessenichad7645f2018-06-04 19:11:25 -06005862// For converting integers where both the bitwidth and the signedness could
5863// change, but only do the width change here. The caller is still responsible
5864// for the signedness conversion.
5865spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005866{
John Kessenichad7645f2018-06-04 19:11:25 -06005867 // Get the result type width, based on the type to convert to.
5868 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005869 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005870 case glslang::EOpConvInt16ToUint8:
5871 case glslang::EOpConvIntToUint8:
5872 case glslang::EOpConvInt64ToUint8:
5873 case glslang::EOpConvUint16ToInt8:
5874 case glslang::EOpConvUintToInt8:
5875 case glslang::EOpConvUint64ToInt8:
5876 width = 8;
5877 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005878 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005879 case glslang::EOpConvIntToUint16:
5880 case glslang::EOpConvInt64ToUint16:
5881 case glslang::EOpConvUint8ToInt16:
5882 case glslang::EOpConvUintToInt16:
5883 case glslang::EOpConvUint64ToInt16:
5884 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005885 break;
5886 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005887 case glslang::EOpConvInt16ToUint:
5888 case glslang::EOpConvInt64ToUint:
5889 case glslang::EOpConvUint8ToInt:
5890 case glslang::EOpConvUint16ToInt:
5891 case glslang::EOpConvUint64ToInt:
5892 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005893 break;
5894 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005895 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005896 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005897 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005898 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005899 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005900 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005901 break;
5902
5903 default:
5904 assert(false && "Default missing");
5905 break;
5906 }
5907
John Kessenichad7645f2018-06-04 19:11:25 -06005908 // Get the conversion operation and result type,
5909 // based on the target width, but the source type.
5910 spv::Id type = spv::NoType;
5911 spv::Op convOp = spv::OpNop;
5912 switch(op) {
5913 case glslang::EOpConvInt8ToUint16:
5914 case glslang::EOpConvInt8ToUint:
5915 case glslang::EOpConvInt8ToUint64:
5916 case glslang::EOpConvInt16ToUint8:
5917 case glslang::EOpConvInt16ToUint:
5918 case glslang::EOpConvInt16ToUint64:
5919 case glslang::EOpConvIntToUint8:
5920 case glslang::EOpConvIntToUint16:
5921 case glslang::EOpConvIntToUint64:
5922 case glslang::EOpConvInt64ToUint8:
5923 case glslang::EOpConvInt64ToUint16:
5924 case glslang::EOpConvInt64ToUint:
5925 convOp = spv::OpSConvert;
5926 type = builder.makeIntType(width);
5927 break;
5928 default:
5929 convOp = spv::OpUConvert;
5930 type = builder.makeUintType(width);
5931 break;
5932 }
5933
John Kessenich66011cb2018-03-06 16:12:04 -07005934 if (vectorSize > 0)
5935 type = builder.makeVectorType(type, vectorSize);
5936
John Kessenichad7645f2018-06-04 19:11:25 -06005937 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005938}
5939
John Kessenichead86222018-03-28 18:01:20 -06005940spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5941 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005942{
5943 spv::Op convOp = spv::OpNop;
5944 spv::Id zero = 0;
5945 spv::Id one = 0;
5946
5947 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5948
5949 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005950 case glslang::EOpConvInt8ToBool:
5951 case glslang::EOpConvUint8ToBool:
5952 zero = builder.makeUint8Constant(0);
5953 zero = makeSmearedConstant(zero, vectorSize);
5954 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005955 case glslang::EOpConvInt16ToBool:
5956 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005957 zero = builder.makeUint16Constant(0);
5958 zero = makeSmearedConstant(zero, vectorSize);
5959 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5960 case glslang::EOpConvIntToBool:
5961 case glslang::EOpConvUintToBool:
5962 zero = builder.makeUintConstant(0);
5963 zero = makeSmearedConstant(zero, vectorSize);
5964 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5965 case glslang::EOpConvInt64ToBool:
5966 case glslang::EOpConvUint64ToBool:
5967 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005968 zero = makeSmearedConstant(zero, vectorSize);
5969 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5970
5971 case glslang::EOpConvFloatToBool:
5972 zero = builder.makeFloatConstant(0.0F);
5973 zero = makeSmearedConstant(zero, vectorSize);
5974 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5975
5976 case glslang::EOpConvDoubleToBool:
5977 zero = builder.makeDoubleConstant(0.0);
5978 zero = makeSmearedConstant(zero, vectorSize);
5979 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5980
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005981 case glslang::EOpConvFloat16ToBool:
5982 zero = builder.makeFloat16Constant(0.0F);
5983 zero = makeSmearedConstant(zero, vectorSize);
5984 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005985
John Kessenich140f3df2015-06-26 16:58:36 -06005986 case glslang::EOpConvBoolToFloat:
5987 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005988 zero = builder.makeFloatConstant(0.0F);
5989 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005990 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005991
John Kessenich140f3df2015-06-26 16:58:36 -06005992 case glslang::EOpConvBoolToDouble:
5993 convOp = spv::OpSelect;
5994 zero = builder.makeDoubleConstant(0.0);
5995 one = builder.makeDoubleConstant(1.0);
5996 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005997
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005998 case glslang::EOpConvBoolToFloat16:
5999 convOp = spv::OpSelect;
6000 zero = builder.makeFloat16Constant(0.0F);
6001 one = builder.makeFloat16Constant(1.0F);
6002 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006003
6004 case glslang::EOpConvBoolToInt8:
6005 zero = builder.makeInt8Constant(0);
6006 one = builder.makeInt8Constant(1);
6007 convOp = spv::OpSelect;
6008 break;
6009
6010 case glslang::EOpConvBoolToUint8:
6011 zero = builder.makeUint8Constant(0);
6012 one = builder.makeUint8Constant(1);
6013 convOp = spv::OpSelect;
6014 break;
6015
6016 case glslang::EOpConvBoolToInt16:
6017 zero = builder.makeInt16Constant(0);
6018 one = builder.makeInt16Constant(1);
6019 convOp = spv::OpSelect;
6020 break;
6021
6022 case glslang::EOpConvBoolToUint16:
6023 zero = builder.makeUint16Constant(0);
6024 one = builder.makeUint16Constant(1);
6025 convOp = spv::OpSelect;
6026 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006027
John Kessenich140f3df2015-06-26 16:58:36 -06006028 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006029 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006030 if (op == glslang::EOpConvBoolToInt64)
6031 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006032 else
6033 zero = builder.makeIntConstant(0);
6034
6035 if (op == glslang::EOpConvBoolToInt64)
6036 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006037 else
6038 one = builder.makeIntConstant(1);
6039
John Kessenich140f3df2015-06-26 16:58:36 -06006040 convOp = spv::OpSelect;
6041 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006042
John Kessenich140f3df2015-06-26 16:58:36 -06006043 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006044 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08006045 if (op == glslang::EOpConvBoolToUint64)
6046 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006047 else
6048 zero = builder.makeUintConstant(0);
6049
6050 if (op == glslang::EOpConvBoolToUint64)
6051 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006052 else
6053 one = builder.makeUintConstant(1);
6054
John Kessenich140f3df2015-06-26 16:58:36 -06006055 convOp = spv::OpSelect;
6056 break;
6057
John Kessenich66011cb2018-03-06 16:12:04 -07006058 case glslang::EOpConvInt8ToFloat16:
6059 case glslang::EOpConvInt8ToFloat:
6060 case glslang::EOpConvInt8ToDouble:
6061 case glslang::EOpConvInt16ToFloat16:
6062 case glslang::EOpConvInt16ToFloat:
6063 case glslang::EOpConvInt16ToDouble:
6064 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006065 case glslang::EOpConvIntToFloat:
6066 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006067 case glslang::EOpConvInt64ToFloat:
6068 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006069 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006070 convOp = spv::OpConvertSToF;
6071 break;
6072
John Kessenich66011cb2018-03-06 16:12:04 -07006073 case glslang::EOpConvUint8ToFloat16:
6074 case glslang::EOpConvUint8ToFloat:
6075 case glslang::EOpConvUint8ToDouble:
6076 case glslang::EOpConvUint16ToFloat16:
6077 case glslang::EOpConvUint16ToFloat:
6078 case glslang::EOpConvUint16ToDouble:
6079 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006080 case glslang::EOpConvUintToFloat:
6081 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006082 case glslang::EOpConvUint64ToFloat:
6083 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006084 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006085 convOp = spv::OpConvertUToF;
6086 break;
6087
6088 case glslang::EOpConvDoubleToFloat:
6089 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006090 case glslang::EOpConvDoubleToFloat16:
6091 case glslang::EOpConvFloat16ToDouble:
6092 case glslang::EOpConvFloatToFloat16:
6093 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06006094 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08006095 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06006096 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06006097 break;
6098
John Kessenich66011cb2018-03-06 16:12:04 -07006099 case glslang::EOpConvFloat16ToInt8:
6100 case glslang::EOpConvFloatToInt8:
6101 case glslang::EOpConvDoubleToInt8:
6102 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006103 case glslang::EOpConvFloatToInt16:
6104 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006105 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006106 case glslang::EOpConvFloatToInt:
6107 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006108 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006109 case glslang::EOpConvFloatToInt64:
6110 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006111 convOp = spv::OpConvertFToS;
6112 break;
6113
John Kessenich66011cb2018-03-06 16:12:04 -07006114 case glslang::EOpConvUint8ToInt8:
6115 case glslang::EOpConvInt8ToUint8:
6116 case glslang::EOpConvUint16ToInt16:
6117 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006118 case glslang::EOpConvUintToInt:
6119 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006120 case glslang::EOpConvUint64ToInt64:
6121 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006122 if (builder.isInSpecConstCodeGenMode()) {
6123 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006124 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6125 zero = builder.makeUint8Constant(0);
6126 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006127 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006128 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6129 zero = builder.makeUint64Constant(0);
6130 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006131 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006132 }
qining189b2032016-04-12 23:16:20 -04006133 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006134 // Use OpIAdd, instead of OpBitcast to do the conversion when
6135 // generating for OpSpecConstantOp instruction.
6136 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6137 }
6138 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006139 convOp = spv::OpBitcast;
6140 break;
6141
John Kessenich66011cb2018-03-06 16:12:04 -07006142 case glslang::EOpConvFloat16ToUint8:
6143 case glslang::EOpConvFloatToUint8:
6144 case glslang::EOpConvDoubleToUint8:
6145 case glslang::EOpConvFloat16ToUint16:
6146 case glslang::EOpConvFloatToUint16:
6147 case glslang::EOpConvDoubleToUint16:
6148 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006149 case glslang::EOpConvFloatToUint:
6150 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006151 case glslang::EOpConvFloatToUint64:
6152 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006153 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006154 convOp = spv::OpConvertFToU;
6155 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006156
John Kessenich66011cb2018-03-06 16:12:04 -07006157 case glslang::EOpConvInt8ToInt16:
6158 case glslang::EOpConvInt8ToInt:
6159 case glslang::EOpConvInt8ToInt64:
6160 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006161 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006162 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006163 case glslang::EOpConvIntToInt8:
6164 case glslang::EOpConvIntToInt16:
6165 case glslang::EOpConvIntToInt64:
6166 case glslang::EOpConvInt64ToInt8:
6167 case glslang::EOpConvInt64ToInt16:
6168 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006169 convOp = spv::OpSConvert;
6170 break;
6171
John Kessenich66011cb2018-03-06 16:12:04 -07006172 case glslang::EOpConvUint8ToUint16:
6173 case glslang::EOpConvUint8ToUint:
6174 case glslang::EOpConvUint8ToUint64:
6175 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006176 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006177 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006178 case glslang::EOpConvUintToUint8:
6179 case glslang::EOpConvUintToUint16:
6180 case glslang::EOpConvUintToUint64:
6181 case glslang::EOpConvUint64ToUint8:
6182 case glslang::EOpConvUint64ToUint16:
6183 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006184 convOp = spv::OpUConvert;
6185 break;
6186
John Kessenich66011cb2018-03-06 16:12:04 -07006187 case glslang::EOpConvInt8ToUint16:
6188 case glslang::EOpConvInt8ToUint:
6189 case glslang::EOpConvInt8ToUint64:
6190 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006191 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006192 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006193 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006194 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006195 case glslang::EOpConvIntToUint64:
6196 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006197 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006198 case glslang::EOpConvInt64ToUint:
6199 case glslang::EOpConvUint8ToInt16:
6200 case glslang::EOpConvUint8ToInt:
6201 case glslang::EOpConvUint8ToInt64:
6202 case glslang::EOpConvUint16ToInt8:
6203 case glslang::EOpConvUint16ToInt:
6204 case glslang::EOpConvUint16ToInt64:
6205 case glslang::EOpConvUintToInt8:
6206 case glslang::EOpConvUintToInt16:
6207 case glslang::EOpConvUintToInt64:
6208 case glslang::EOpConvUint64ToInt8:
6209 case glslang::EOpConvUint64ToInt16:
6210 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006211 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006212 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006213
6214 if (builder.isInSpecConstCodeGenMode()) {
6215 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006216 switch(op) {
6217 case glslang::EOpConvInt16ToUint8:
6218 case glslang::EOpConvIntToUint8:
6219 case glslang::EOpConvInt64ToUint8:
6220 case glslang::EOpConvUint16ToInt8:
6221 case glslang::EOpConvUintToInt8:
6222 case glslang::EOpConvUint64ToInt8:
6223 zero = builder.makeUint8Constant(0);
6224 break;
6225 case glslang::EOpConvInt8ToUint16:
6226 case glslang::EOpConvIntToUint16:
6227 case glslang::EOpConvInt64ToUint16:
6228 case glslang::EOpConvUint8ToInt16:
6229 case glslang::EOpConvUintToInt16:
6230 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006231 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006232 break;
6233 case glslang::EOpConvInt8ToUint:
6234 case glslang::EOpConvInt16ToUint:
6235 case glslang::EOpConvInt64ToUint:
6236 case glslang::EOpConvUint8ToInt:
6237 case glslang::EOpConvUint16ToInt:
6238 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006239 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006240 break;
6241 case glslang::EOpConvInt8ToUint64:
6242 case glslang::EOpConvInt16ToUint64:
6243 case glslang::EOpConvIntToUint64:
6244 case glslang::EOpConvUint8ToInt64:
6245 case glslang::EOpConvUint16ToInt64:
6246 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006247 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006248 break;
6249 default:
6250 assert(false && "Default missing");
6251 break;
6252 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006253 zero = makeSmearedConstant(zero, vectorSize);
6254 // Use OpIAdd, instead of OpBitcast to do the conversion when
6255 // generating for OpSpecConstantOp instruction.
6256 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6257 }
6258 // For normal run-time conversion instruction, use OpBitcast.
6259 convOp = spv::OpBitcast;
6260 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006261 case glslang::EOpConvUint64ToPtr:
6262 convOp = spv::OpConvertUToPtr;
6263 break;
6264 case glslang::EOpConvPtrToUint64:
6265 convOp = spv::OpConvertPtrToU;
6266 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006267 default:
6268 break;
6269 }
6270
6271 spv::Id result = 0;
6272 if (convOp == spv::OpNop)
6273 return result;
6274
6275 if (convOp == spv::OpSelect) {
6276 zero = makeSmearedConstant(zero, vectorSize);
6277 one = makeSmearedConstant(one, vectorSize);
6278 result = builder.createTriOp(convOp, destType, operand, one, zero);
6279 } else
6280 result = builder.createUnaryOp(convOp, destType, operand);
6281
John Kessenichead86222018-03-28 18:01:20 -06006282 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006283 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006284 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006285}
6286
6287spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6288{
6289 if (vectorSize == 0)
6290 return constant;
6291
6292 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6293 std::vector<spv::Id> components;
6294 for (int c = 0; c < vectorSize; ++c)
6295 components.push_back(constant);
6296 return builder.makeCompositeConstant(vectorTypeId, components);
6297}
6298
John Kessenich426394d2015-07-23 10:22:48 -06006299// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006300spv::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 -06006301{
6302 spv::Op opCode = spv::OpNop;
6303
6304 switch (op) {
6305 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006306 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006307 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006308 opCode = spv::OpAtomicIAdd;
6309 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006310 case glslang::EOpAtomicCounterSubtract:
6311 opCode = spv::OpAtomicISub;
6312 break;
John Kessenich426394d2015-07-23 10:22:48 -06006313 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006314 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006315 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006316 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006317 break;
6318 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006319 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006320 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006321 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006322 break;
6323 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006324 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006325 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006326 opCode = spv::OpAtomicAnd;
6327 break;
6328 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006329 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006330 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006331 opCode = spv::OpAtomicOr;
6332 break;
6333 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006334 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006335 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006336 opCode = spv::OpAtomicXor;
6337 break;
6338 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006339 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006340 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006341 opCode = spv::OpAtomicExchange;
6342 break;
6343 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006344 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006345 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006346 opCode = spv::OpAtomicCompareExchange;
6347 break;
6348 case glslang::EOpAtomicCounterIncrement:
6349 opCode = spv::OpAtomicIIncrement;
6350 break;
6351 case glslang::EOpAtomicCounterDecrement:
6352 opCode = spv::OpAtomicIDecrement;
6353 break;
6354 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006355 case glslang::EOpImageAtomicLoad:
6356 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006357 opCode = spv::OpAtomicLoad;
6358 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006359 case glslang::EOpAtomicStore:
6360 case glslang::EOpImageAtomicStore:
6361 opCode = spv::OpAtomicStore;
6362 break;
John Kessenich426394d2015-07-23 10:22:48 -06006363 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006364 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006365 break;
6366 }
6367
Rex Xue8fe8b02017-09-26 15:42:56 +08006368 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6369 builder.addCapability(spv::CapabilityInt64Atomics);
6370
John Kessenich426394d2015-07-23 10:22:48 -06006371 // Sort out the operands
6372 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006373 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006374 // - compare-exchange swaps the value and comparator
6375 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006376 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006377 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6378 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6379 spv::Id scopeId;
6380 if (glslangIntermediate->usingVulkanMemoryModel()) {
6381 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6382 } else {
6383 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6384 }
6385 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006386 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006387 spv::Id semanticsId2 = semanticsId;
6388
6389 pointerId = operands[0];
6390 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6391 // no additional operands
6392 } else if (opCode == spv::OpAtomicCompareExchange) {
6393 compareId = operands[1];
6394 valueId = operands[2];
6395 if (operands.size() > 3) {
6396 scopeId = operands[3];
6397 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6398 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6399 }
6400 } else if (opCode == spv::OpAtomicLoad) {
6401 if (operands.size() > 1) {
6402 scopeId = operands[1];
6403 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6404 }
6405 } else {
6406 // atomic store or RMW
6407 valueId = operands[1];
6408 if (operands.size() > 2) {
6409 scopeId = operands[2];
6410 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6411 }
Rex Xu04db3f52015-09-16 11:44:02 +08006412 }
John Kessenich426394d2015-07-23 10:22:48 -06006413
Jeff Bolz36831c92018-09-05 10:11:41 -05006414 // Check for capabilities
6415 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006416 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6417 spv::MemorySemanticsMakeVisibleKHRMask |
6418 spv::MemorySemanticsOutputMemoryKHRMask |
6419 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006420 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6421 }
John Kessenich426394d2015-07-23 10:22:48 -06006422
Jeff Bolz36831c92018-09-05 10:11:41 -05006423 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6424 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6425 }
John Kessenich48d6e792017-10-06 21:21:48 -06006426
Jeff Bolz36831c92018-09-05 10:11:41 -05006427 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6428 spvAtomicOperands.push_back(pointerId);
6429 spvAtomicOperands.push_back(scopeId);
6430 spvAtomicOperands.push_back(semanticsId);
6431 if (opCode == spv::OpAtomicCompareExchange) {
6432 spvAtomicOperands.push_back(semanticsId2);
6433 spvAtomicOperands.push_back(valueId);
6434 spvAtomicOperands.push_back(compareId);
6435 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6436 spvAtomicOperands.push_back(valueId);
6437 }
John Kessenich48d6e792017-10-06 21:21:48 -06006438
Jeff Bolz36831c92018-09-05 10:11:41 -05006439 if (opCode == spv::OpAtomicStore) {
6440 builder.createNoResultOp(opCode, spvAtomicOperands);
6441 return 0;
6442 } else {
6443 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6444
6445 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6446 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6447 if (op == glslang::EOpAtomicCounterDecrement)
6448 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6449
6450 return resultId;
6451 }
John Kessenich426394d2015-07-23 10:22:48 -06006452}
6453
John Kessenich91cef522016-05-05 16:45:40 -06006454// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006455spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006456{
Corentin Walleze7061422018-08-08 15:20:15 +02006457#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006458 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6459 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006460#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006461
Rex Xu51596642016-09-21 18:56:12 +08006462 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006463 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006464 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6465
chaocf200da82016-12-20 12:44:35 -08006466 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6467 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006468 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6469 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006470 } else if (op == glslang::EOpAnyInvocation ||
6471 op == glslang::EOpAllInvocations ||
6472 op == glslang::EOpAllInvocationsEqual) {
6473 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6474 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006475 } else {
6476 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006477#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006478 if (op == glslang::EOpMinInvocationsNonUniform ||
6479 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006480 op == glslang::EOpAddInvocationsNonUniform ||
6481 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6482 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6483 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6484 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6485 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6486 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006487 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006488#endif
Rex Xu51596642016-09-21 18:56:12 +08006489
Rex Xu9d93a232016-05-05 12:30:44 +08006490#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006491 switch (op) {
6492 case glslang::EOpMinInvocations:
6493 case glslang::EOpMaxInvocations:
6494 case glslang::EOpAddInvocations:
6495 case glslang::EOpMinInvocationsNonUniform:
6496 case glslang::EOpMaxInvocationsNonUniform:
6497 case glslang::EOpAddInvocationsNonUniform:
6498 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006499 break;
6500 case glslang::EOpMinInvocationsInclusiveScan:
6501 case glslang::EOpMaxInvocationsInclusiveScan:
6502 case glslang::EOpAddInvocationsInclusiveScan:
6503 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6504 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6505 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6506 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006507 break;
6508 case glslang::EOpMinInvocationsExclusiveScan:
6509 case glslang::EOpMaxInvocationsExclusiveScan:
6510 case glslang::EOpAddInvocationsExclusiveScan:
6511 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6512 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6513 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6514 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006515 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006516 default:
6517 break;
Rex Xu430ef402016-10-14 17:22:23 +08006518 }
John Kessenich149afc32018-08-14 13:31:43 -06006519 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6520 spvGroupOperands.push_back(scope);
6521 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006522 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006523 spvGroupOperands.push_back(groupOp);
6524 }
Rex Xu9d93a232016-05-05 12:30:44 +08006525#endif
Rex Xu51596642016-09-21 18:56:12 +08006526 }
6527
John Kessenich149afc32018-08-14 13:31:43 -06006528 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6529 spv::IdImmediate op = { true, *opIt };
6530 spvGroupOperands.push_back(op);
6531 }
John Kessenich91cef522016-05-05 16:45:40 -06006532
6533 switch (op) {
6534 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006535 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006536 break;
John Kessenich91cef522016-05-05 16:45:40 -06006537 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006538 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006539 break;
John Kessenich91cef522016-05-05 16:45:40 -06006540 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006541 opCode = spv::OpSubgroupAllEqualKHR;
6542 break;
Rex Xu51596642016-09-21 18:56:12 +08006543 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006544 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006545 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006546 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006547 break;
6548 case glslang::EOpReadFirstInvocation:
6549 opCode = spv::OpSubgroupFirstInvocationKHR;
6550 break;
6551 case glslang::EOpBallot:
6552 {
6553 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6554 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6555 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6556 //
6557 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6558 //
6559 spv::Id uintType = builder.makeUintType(32);
6560 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6561 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6562
6563 std::vector<spv::Id> components;
6564 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6565 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6566
6567 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6568 return builder.createUnaryOp(spv::OpBitcast, typeId,
6569 builder.createCompositeConstruct(uvec2Type, components));
6570 }
6571
Rex Xu9d93a232016-05-05 12:30:44 +08006572#ifdef AMD_EXTENSIONS
6573 case glslang::EOpMinInvocations:
6574 case glslang::EOpMaxInvocations:
6575 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006576 case glslang::EOpMinInvocationsInclusiveScan:
6577 case glslang::EOpMaxInvocationsInclusiveScan:
6578 case glslang::EOpAddInvocationsInclusiveScan:
6579 case glslang::EOpMinInvocationsExclusiveScan:
6580 case glslang::EOpMaxInvocationsExclusiveScan:
6581 case glslang::EOpAddInvocationsExclusiveScan:
6582 if (op == glslang::EOpMinInvocations ||
6583 op == glslang::EOpMinInvocationsInclusiveScan ||
6584 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006585 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006586 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006587 else {
6588 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006589 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006590 else
Rex Xu51596642016-09-21 18:56:12 +08006591 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006592 }
Rex Xu430ef402016-10-14 17:22:23 +08006593 } else if (op == glslang::EOpMaxInvocations ||
6594 op == glslang::EOpMaxInvocationsInclusiveScan ||
6595 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006596 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006597 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006598 else {
6599 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006600 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006601 else
Rex Xu51596642016-09-21 18:56:12 +08006602 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006603 }
6604 } else {
6605 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006606 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006607 else
Rex Xu51596642016-09-21 18:56:12 +08006608 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006609 }
6610
Rex Xu2bbbe062016-08-23 15:41:05 +08006611 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006612 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006613
6614 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006615 case glslang::EOpMinInvocationsNonUniform:
6616 case glslang::EOpMaxInvocationsNonUniform:
6617 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006618 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6619 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6620 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6621 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6622 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6623 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6624 if (op == glslang::EOpMinInvocationsNonUniform ||
6625 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6626 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006627 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006628 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006629 else {
6630 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006631 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006632 else
Rex Xu51596642016-09-21 18:56:12 +08006633 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006634 }
6635 }
Rex Xu430ef402016-10-14 17:22:23 +08006636 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6637 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6638 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006639 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006640 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006641 else {
6642 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006643 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006644 else
Rex Xu51596642016-09-21 18:56:12 +08006645 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006646 }
6647 }
6648 else {
6649 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006650 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006651 else
Rex Xu51596642016-09-21 18:56:12 +08006652 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006653 }
6654
Rex Xu2bbbe062016-08-23 15:41:05 +08006655 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006656 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006657
6658 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006659#endif
John Kessenich91cef522016-05-05 16:45:40 -06006660 default:
6661 logger->missingFunctionality("invocation operation");
6662 return spv::NoResult;
6663 }
Rex Xu51596642016-09-21 18:56:12 +08006664
6665 assert(opCode != spv::OpNop);
6666 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006667}
6668
Rex Xu2bbbe062016-08-23 15:41:05 +08006669// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006670spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6671 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006672{
Rex Xub7072052016-09-26 15:53:40 +08006673#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006674 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6675 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006676 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006677 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006678 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6679 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6680 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006681#else
6682 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6683 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006684 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6685 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006686#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006687
6688 // Handle group invocation operations scalar by scalar.
6689 // The result type is the same type as the original type.
6690 // The algorithm is to:
6691 // - break the vector into scalars
6692 // - apply the operation to each scalar
6693 // - make a vector out the scalar results
6694
6695 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006696 int numComponents = builder.getNumComponents(operands[0]);
6697 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006698 std::vector<spv::Id> results;
6699
6700 // do each scalar op
6701 for (int comp = 0; comp < numComponents; ++comp) {
6702 std::vector<unsigned int> indexes;
6703 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006704 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6705 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006706 if (op == spv::OpSubgroupReadInvocationKHR) {
6707 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006708 spv::IdImmediate operand = { true, operands[1] };
6709 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006710 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006711 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6712 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006713 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006714 spv::IdImmediate operand = { true, operands[1] };
6715 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006716 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006717 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6718 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006719 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006720 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006721 spvGroupOperands.push_back(scalar);
6722 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006723
Rex Xub7072052016-09-26 15:53:40 +08006724 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006725 }
6726
6727 // put the pieces together
6728 return builder.createCompositeConstruct(typeId, results);
6729}
Rex Xu2bbbe062016-08-23 15:41:05 +08006730
John Kessenich66011cb2018-03-06 16:12:04 -07006731// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006732spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6733 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006734{
6735 // Add the required capabilities.
6736 switch (op) {
6737 case glslang::EOpSubgroupElect:
6738 builder.addCapability(spv::CapabilityGroupNonUniform);
6739 break;
6740 case glslang::EOpSubgroupAll:
6741 case glslang::EOpSubgroupAny:
6742 case glslang::EOpSubgroupAllEqual:
6743 builder.addCapability(spv::CapabilityGroupNonUniform);
6744 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6745 break;
6746 case glslang::EOpSubgroupBroadcast:
6747 case glslang::EOpSubgroupBroadcastFirst:
6748 case glslang::EOpSubgroupBallot:
6749 case glslang::EOpSubgroupInverseBallot:
6750 case glslang::EOpSubgroupBallotBitExtract:
6751 case glslang::EOpSubgroupBallotBitCount:
6752 case glslang::EOpSubgroupBallotInclusiveBitCount:
6753 case glslang::EOpSubgroupBallotExclusiveBitCount:
6754 case glslang::EOpSubgroupBallotFindLSB:
6755 case glslang::EOpSubgroupBallotFindMSB:
6756 builder.addCapability(spv::CapabilityGroupNonUniform);
6757 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6758 break;
6759 case glslang::EOpSubgroupShuffle:
6760 case glslang::EOpSubgroupShuffleXor:
6761 builder.addCapability(spv::CapabilityGroupNonUniform);
6762 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6763 break;
6764 case glslang::EOpSubgroupShuffleUp:
6765 case glslang::EOpSubgroupShuffleDown:
6766 builder.addCapability(spv::CapabilityGroupNonUniform);
6767 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6768 break;
6769 case glslang::EOpSubgroupAdd:
6770 case glslang::EOpSubgroupMul:
6771 case glslang::EOpSubgroupMin:
6772 case glslang::EOpSubgroupMax:
6773 case glslang::EOpSubgroupAnd:
6774 case glslang::EOpSubgroupOr:
6775 case glslang::EOpSubgroupXor:
6776 case glslang::EOpSubgroupInclusiveAdd:
6777 case glslang::EOpSubgroupInclusiveMul:
6778 case glslang::EOpSubgroupInclusiveMin:
6779 case glslang::EOpSubgroupInclusiveMax:
6780 case glslang::EOpSubgroupInclusiveAnd:
6781 case glslang::EOpSubgroupInclusiveOr:
6782 case glslang::EOpSubgroupInclusiveXor:
6783 case glslang::EOpSubgroupExclusiveAdd:
6784 case glslang::EOpSubgroupExclusiveMul:
6785 case glslang::EOpSubgroupExclusiveMin:
6786 case glslang::EOpSubgroupExclusiveMax:
6787 case glslang::EOpSubgroupExclusiveAnd:
6788 case glslang::EOpSubgroupExclusiveOr:
6789 case glslang::EOpSubgroupExclusiveXor:
6790 builder.addCapability(spv::CapabilityGroupNonUniform);
6791 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6792 break;
6793 case glslang::EOpSubgroupClusteredAdd:
6794 case glslang::EOpSubgroupClusteredMul:
6795 case glslang::EOpSubgroupClusteredMin:
6796 case glslang::EOpSubgroupClusteredMax:
6797 case glslang::EOpSubgroupClusteredAnd:
6798 case glslang::EOpSubgroupClusteredOr:
6799 case glslang::EOpSubgroupClusteredXor:
6800 builder.addCapability(spv::CapabilityGroupNonUniform);
6801 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6802 break;
6803 case glslang::EOpSubgroupQuadBroadcast:
6804 case glslang::EOpSubgroupQuadSwapHorizontal:
6805 case glslang::EOpSubgroupQuadSwapVertical:
6806 case glslang::EOpSubgroupQuadSwapDiagonal:
6807 builder.addCapability(spv::CapabilityGroupNonUniform);
6808 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6809 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006810#ifdef NV_EXTENSIONS
6811 case glslang::EOpSubgroupPartitionedAdd:
6812 case glslang::EOpSubgroupPartitionedMul:
6813 case glslang::EOpSubgroupPartitionedMin:
6814 case glslang::EOpSubgroupPartitionedMax:
6815 case glslang::EOpSubgroupPartitionedAnd:
6816 case glslang::EOpSubgroupPartitionedOr:
6817 case glslang::EOpSubgroupPartitionedXor:
6818 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6819 case glslang::EOpSubgroupPartitionedInclusiveMul:
6820 case glslang::EOpSubgroupPartitionedInclusiveMin:
6821 case glslang::EOpSubgroupPartitionedInclusiveMax:
6822 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6823 case glslang::EOpSubgroupPartitionedInclusiveOr:
6824 case glslang::EOpSubgroupPartitionedInclusiveXor:
6825 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6826 case glslang::EOpSubgroupPartitionedExclusiveMul:
6827 case glslang::EOpSubgroupPartitionedExclusiveMin:
6828 case glslang::EOpSubgroupPartitionedExclusiveMax:
6829 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6830 case glslang::EOpSubgroupPartitionedExclusiveOr:
6831 case glslang::EOpSubgroupPartitionedExclusiveXor:
6832 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6833 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6834 break;
6835#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006836 default: assert(0 && "Unhandled subgroup operation!");
6837 }
6838
6839 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6840 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6841 const bool isBool = typeProxy == glslang::EbtBool;
6842
6843 spv::Op opCode = spv::OpNop;
6844
6845 // Figure out which opcode to use.
6846 switch (op) {
6847 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6848 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6849 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6850 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6851 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6852 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6853 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6854 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6855 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6856 case glslang::EOpSubgroupBallotBitCount:
6857 case glslang::EOpSubgroupBallotInclusiveBitCount:
6858 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6859 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6860 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6861 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6862 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6863 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6864 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6865 case glslang::EOpSubgroupAdd:
6866 case glslang::EOpSubgroupInclusiveAdd:
6867 case glslang::EOpSubgroupExclusiveAdd:
6868 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006869#ifdef NV_EXTENSIONS
6870 case glslang::EOpSubgroupPartitionedAdd:
6871 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6872 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6873#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006874 if (isFloat) {
6875 opCode = spv::OpGroupNonUniformFAdd;
6876 } else {
6877 opCode = spv::OpGroupNonUniformIAdd;
6878 }
6879 break;
6880 case glslang::EOpSubgroupMul:
6881 case glslang::EOpSubgroupInclusiveMul:
6882 case glslang::EOpSubgroupExclusiveMul:
6883 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006884#ifdef NV_EXTENSIONS
6885 case glslang::EOpSubgroupPartitionedMul:
6886 case glslang::EOpSubgroupPartitionedInclusiveMul:
6887 case glslang::EOpSubgroupPartitionedExclusiveMul:
6888#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006889 if (isFloat) {
6890 opCode = spv::OpGroupNonUniformFMul;
6891 } else {
6892 opCode = spv::OpGroupNonUniformIMul;
6893 }
6894 break;
6895 case glslang::EOpSubgroupMin:
6896 case glslang::EOpSubgroupInclusiveMin:
6897 case glslang::EOpSubgroupExclusiveMin:
6898 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006899#ifdef NV_EXTENSIONS
6900 case glslang::EOpSubgroupPartitionedMin:
6901 case glslang::EOpSubgroupPartitionedInclusiveMin:
6902 case glslang::EOpSubgroupPartitionedExclusiveMin:
6903#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006904 if (isFloat) {
6905 opCode = spv::OpGroupNonUniformFMin;
6906 } else if (isUnsigned) {
6907 opCode = spv::OpGroupNonUniformUMin;
6908 } else {
6909 opCode = spv::OpGroupNonUniformSMin;
6910 }
6911 break;
6912 case glslang::EOpSubgroupMax:
6913 case glslang::EOpSubgroupInclusiveMax:
6914 case glslang::EOpSubgroupExclusiveMax:
6915 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006916#ifdef NV_EXTENSIONS
6917 case glslang::EOpSubgroupPartitionedMax:
6918 case glslang::EOpSubgroupPartitionedInclusiveMax:
6919 case glslang::EOpSubgroupPartitionedExclusiveMax:
6920#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006921 if (isFloat) {
6922 opCode = spv::OpGroupNonUniformFMax;
6923 } else if (isUnsigned) {
6924 opCode = spv::OpGroupNonUniformUMax;
6925 } else {
6926 opCode = spv::OpGroupNonUniformSMax;
6927 }
6928 break;
6929 case glslang::EOpSubgroupAnd:
6930 case glslang::EOpSubgroupInclusiveAnd:
6931 case glslang::EOpSubgroupExclusiveAnd:
6932 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006933#ifdef NV_EXTENSIONS
6934 case glslang::EOpSubgroupPartitionedAnd:
6935 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6936 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6937#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006938 if (isBool) {
6939 opCode = spv::OpGroupNonUniformLogicalAnd;
6940 } else {
6941 opCode = spv::OpGroupNonUniformBitwiseAnd;
6942 }
6943 break;
6944 case glslang::EOpSubgroupOr:
6945 case glslang::EOpSubgroupInclusiveOr:
6946 case glslang::EOpSubgroupExclusiveOr:
6947 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006948#ifdef NV_EXTENSIONS
6949 case glslang::EOpSubgroupPartitionedOr:
6950 case glslang::EOpSubgroupPartitionedInclusiveOr:
6951 case glslang::EOpSubgroupPartitionedExclusiveOr:
6952#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006953 if (isBool) {
6954 opCode = spv::OpGroupNonUniformLogicalOr;
6955 } else {
6956 opCode = spv::OpGroupNonUniformBitwiseOr;
6957 }
6958 break;
6959 case glslang::EOpSubgroupXor:
6960 case glslang::EOpSubgroupInclusiveXor:
6961 case glslang::EOpSubgroupExclusiveXor:
6962 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006963#ifdef NV_EXTENSIONS
6964 case glslang::EOpSubgroupPartitionedXor:
6965 case glslang::EOpSubgroupPartitionedInclusiveXor:
6966 case glslang::EOpSubgroupPartitionedExclusiveXor:
6967#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006968 if (isBool) {
6969 opCode = spv::OpGroupNonUniformLogicalXor;
6970 } else {
6971 opCode = spv::OpGroupNonUniformBitwiseXor;
6972 }
6973 break;
6974 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6975 case glslang::EOpSubgroupQuadSwapHorizontal:
6976 case glslang::EOpSubgroupQuadSwapVertical:
6977 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6978 default: assert(0 && "Unhandled subgroup operation!");
6979 }
6980
John Kessenich149afc32018-08-14 13:31:43 -06006981 // get the right Group Operation
6982 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006983 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006984 default:
6985 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006986 case glslang::EOpSubgroupBallotBitCount:
6987 case glslang::EOpSubgroupAdd:
6988 case glslang::EOpSubgroupMul:
6989 case glslang::EOpSubgroupMin:
6990 case glslang::EOpSubgroupMax:
6991 case glslang::EOpSubgroupAnd:
6992 case glslang::EOpSubgroupOr:
6993 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006994 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006995 break;
6996 case glslang::EOpSubgroupBallotInclusiveBitCount:
6997 case glslang::EOpSubgroupInclusiveAdd:
6998 case glslang::EOpSubgroupInclusiveMul:
6999 case glslang::EOpSubgroupInclusiveMin:
7000 case glslang::EOpSubgroupInclusiveMax:
7001 case glslang::EOpSubgroupInclusiveAnd:
7002 case glslang::EOpSubgroupInclusiveOr:
7003 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007004 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007005 break;
7006 case glslang::EOpSubgroupBallotExclusiveBitCount:
7007 case glslang::EOpSubgroupExclusiveAdd:
7008 case glslang::EOpSubgroupExclusiveMul:
7009 case glslang::EOpSubgroupExclusiveMin:
7010 case glslang::EOpSubgroupExclusiveMax:
7011 case glslang::EOpSubgroupExclusiveAnd:
7012 case glslang::EOpSubgroupExclusiveOr:
7013 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007014 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007015 break;
7016 case glslang::EOpSubgroupClusteredAdd:
7017 case glslang::EOpSubgroupClusteredMul:
7018 case glslang::EOpSubgroupClusteredMin:
7019 case glslang::EOpSubgroupClusteredMax:
7020 case glslang::EOpSubgroupClusteredAnd:
7021 case glslang::EOpSubgroupClusteredOr:
7022 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007023 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007024 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007025#ifdef NV_EXTENSIONS
7026 case glslang::EOpSubgroupPartitionedAdd:
7027 case glslang::EOpSubgroupPartitionedMul:
7028 case glslang::EOpSubgroupPartitionedMin:
7029 case glslang::EOpSubgroupPartitionedMax:
7030 case glslang::EOpSubgroupPartitionedAnd:
7031 case glslang::EOpSubgroupPartitionedOr:
7032 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007033 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007034 break;
7035 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7036 case glslang::EOpSubgroupPartitionedInclusiveMul:
7037 case glslang::EOpSubgroupPartitionedInclusiveMin:
7038 case glslang::EOpSubgroupPartitionedInclusiveMax:
7039 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7040 case glslang::EOpSubgroupPartitionedInclusiveOr:
7041 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007042 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007043 break;
7044 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7045 case glslang::EOpSubgroupPartitionedExclusiveMul:
7046 case glslang::EOpSubgroupPartitionedExclusiveMin:
7047 case glslang::EOpSubgroupPartitionedExclusiveMax:
7048 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7049 case glslang::EOpSubgroupPartitionedExclusiveOr:
7050 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007051 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007052 break;
7053#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007054 }
7055
John Kessenich149afc32018-08-14 13:31:43 -06007056 // build the instruction
7057 std::vector<spv::IdImmediate> spvGroupOperands;
7058
7059 // Every operation begins with the Execution Scope operand.
7060 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7061 spvGroupOperands.push_back(executionScope);
7062
7063 // Next, for all operations that use a Group Operation, push that as an operand.
7064 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007065 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007066 spvGroupOperands.push_back(groupOperand);
7067 }
7068
John Kessenich66011cb2018-03-06 16:12:04 -07007069 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007070 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7071 spv::IdImmediate operand = { true, *opIt };
7072 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007073 }
7074
7075 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007076 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007077 switch (op) {
7078 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007079 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7080 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7081 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7082 }
7083 if (directionId != spv::NoResult) {
7084 spv::IdImmediate direction = { true, directionId };
7085 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007086 }
7087
7088 return builder.createOp(opCode, typeId, spvGroupOperands);
7089}
7090
John Kessenich5e4b1242015-08-06 22:53:06 -06007091spv::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 -06007092{
John Kessenich66011cb2018-03-06 16:12:04 -07007093 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7094 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007095
John Kessenich140f3df2015-06-26 16:58:36 -06007096 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007097 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007098 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007099 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007100 spv::Id typeId0 = 0;
7101 if (consumedOperands > 0)
7102 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007103 spv::Id typeId1 = 0;
7104 if (consumedOperands > 1)
7105 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007106 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007107
7108 switch (op) {
7109 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007110 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007111 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007112 else if (isUnsigned)
7113 libCall = spv::GLSLstd450UMin;
7114 else
7115 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007116 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007117 break;
7118 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007119 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007120 break;
7121 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007122 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007123 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007124 else if (isUnsigned)
7125 libCall = spv::GLSLstd450UMax;
7126 else
7127 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007128 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007129 break;
7130 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007131 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007132 break;
7133 case glslang::EOpDot:
7134 opCode = spv::OpDot;
7135 break;
7136 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007137 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007138 break;
7139
7140 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007141 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007142 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007143 else if (isUnsigned)
7144 libCall = spv::GLSLstd450UClamp;
7145 else
7146 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007147 builder.promoteScalar(precision, operands.front(), operands[1]);
7148 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007149 break;
7150 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007151 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7152 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007153 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007154 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007155 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007156 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007157 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007158 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007159 break;
7160 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007161 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007162 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007163 break;
7164 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007165 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007166 builder.promoteScalar(precision, operands[0], operands[2]);
7167 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007168 break;
7169
7170 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007171 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007172 break;
7173 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007174 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007175 break;
7176 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007177 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007178 break;
7179 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007180 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007181 break;
7182 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007183 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007184 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007185 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007186#ifdef AMD_EXTENSIONS
7187 if (typeProxy == glslang::EbtFloat16)
7188 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7189#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007190 libCall = spv::GLSLstd450InterpolateAtSample;
7191 break;
7192 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007193#ifdef AMD_EXTENSIONS
7194 if (typeProxy == glslang::EbtFloat16)
7195 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7196#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007197 libCall = spv::GLSLstd450InterpolateAtOffset;
7198 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007199 case glslang::EOpAddCarry:
7200 opCode = spv::OpIAddCarry;
7201 typeId = builder.makeStructResultType(typeId0, typeId0);
7202 consumedOperands = 2;
7203 break;
7204 case glslang::EOpSubBorrow:
7205 opCode = spv::OpISubBorrow;
7206 typeId = builder.makeStructResultType(typeId0, typeId0);
7207 consumedOperands = 2;
7208 break;
7209 case glslang::EOpUMulExtended:
7210 opCode = spv::OpUMulExtended;
7211 typeId = builder.makeStructResultType(typeId0, typeId0);
7212 consumedOperands = 2;
7213 break;
7214 case glslang::EOpIMulExtended:
7215 opCode = spv::OpSMulExtended;
7216 typeId = builder.makeStructResultType(typeId0, typeId0);
7217 consumedOperands = 2;
7218 break;
7219 case glslang::EOpBitfieldExtract:
7220 if (isUnsigned)
7221 opCode = spv::OpBitFieldUExtract;
7222 else
7223 opCode = spv::OpBitFieldSExtract;
7224 break;
7225 case glslang::EOpBitfieldInsert:
7226 opCode = spv::OpBitFieldInsert;
7227 break;
7228
7229 case glslang::EOpFma:
7230 libCall = spv::GLSLstd450Fma;
7231 break;
7232 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007233 {
7234 libCall = spv::GLSLstd450FrexpStruct;
7235 assert(builder.isPointerType(typeId1));
7236 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007237 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007238#ifdef AMD_EXTENSIONS
7239 if (width == 16)
7240 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7241 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7242#endif
Rex Xu470026f2017-03-29 17:12:40 +08007243 if (builder.getNumComponents(operands[0]) == 1)
7244 frexpIntType = builder.makeIntegerType(width, true);
7245 else
7246 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7247 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7248 consumedOperands = 1;
7249 }
John Kessenich55e7d112015-11-15 21:33:39 -07007250 break;
7251 case glslang::EOpLdexp:
7252 libCall = spv::GLSLstd450Ldexp;
7253 break;
7254
Rex Xu574ab042016-04-14 16:53:07 +08007255 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007256 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007257
John Kessenich66011cb2018-03-06 16:12:04 -07007258 case glslang::EOpSubgroupBroadcast:
7259 case glslang::EOpSubgroupBallotBitExtract:
7260 case glslang::EOpSubgroupShuffle:
7261 case glslang::EOpSubgroupShuffleXor:
7262 case glslang::EOpSubgroupShuffleUp:
7263 case glslang::EOpSubgroupShuffleDown:
7264 case glslang::EOpSubgroupClusteredAdd:
7265 case glslang::EOpSubgroupClusteredMul:
7266 case glslang::EOpSubgroupClusteredMin:
7267 case glslang::EOpSubgroupClusteredMax:
7268 case glslang::EOpSubgroupClusteredAnd:
7269 case glslang::EOpSubgroupClusteredOr:
7270 case glslang::EOpSubgroupClusteredXor:
7271 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007272#ifdef NV_EXTENSIONS
7273 case glslang::EOpSubgroupPartitionedAdd:
7274 case glslang::EOpSubgroupPartitionedMul:
7275 case glslang::EOpSubgroupPartitionedMin:
7276 case glslang::EOpSubgroupPartitionedMax:
7277 case glslang::EOpSubgroupPartitionedAnd:
7278 case glslang::EOpSubgroupPartitionedOr:
7279 case glslang::EOpSubgroupPartitionedXor:
7280 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7281 case glslang::EOpSubgroupPartitionedInclusiveMul:
7282 case glslang::EOpSubgroupPartitionedInclusiveMin:
7283 case glslang::EOpSubgroupPartitionedInclusiveMax:
7284 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7285 case glslang::EOpSubgroupPartitionedInclusiveOr:
7286 case glslang::EOpSubgroupPartitionedInclusiveXor:
7287 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7288 case glslang::EOpSubgroupPartitionedExclusiveMul:
7289 case glslang::EOpSubgroupPartitionedExclusiveMin:
7290 case glslang::EOpSubgroupPartitionedExclusiveMax:
7291 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7292 case glslang::EOpSubgroupPartitionedExclusiveOr:
7293 case glslang::EOpSubgroupPartitionedExclusiveXor:
7294#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007295 return createSubgroupOperation(op, typeId, operands, typeProxy);
7296
Rex Xu9d93a232016-05-05 12:30:44 +08007297#ifdef AMD_EXTENSIONS
7298 case glslang::EOpSwizzleInvocations:
7299 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7300 libCall = spv::SwizzleInvocationsAMD;
7301 break;
7302 case glslang::EOpSwizzleInvocationsMasked:
7303 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7304 libCall = spv::SwizzleInvocationsMaskedAMD;
7305 break;
7306 case glslang::EOpWriteInvocation:
7307 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7308 libCall = spv::WriteInvocationAMD;
7309 break;
7310
7311 case glslang::EOpMin3:
7312 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7313 if (isFloat)
7314 libCall = spv::FMin3AMD;
7315 else {
7316 if (isUnsigned)
7317 libCall = spv::UMin3AMD;
7318 else
7319 libCall = spv::SMin3AMD;
7320 }
7321 break;
7322 case glslang::EOpMax3:
7323 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7324 if (isFloat)
7325 libCall = spv::FMax3AMD;
7326 else {
7327 if (isUnsigned)
7328 libCall = spv::UMax3AMD;
7329 else
7330 libCall = spv::SMax3AMD;
7331 }
7332 break;
7333 case glslang::EOpMid3:
7334 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7335 if (isFloat)
7336 libCall = spv::FMid3AMD;
7337 else {
7338 if (isUnsigned)
7339 libCall = spv::UMid3AMD;
7340 else
7341 libCall = spv::SMid3AMD;
7342 }
7343 break;
7344
7345 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007346 if (typeProxy == glslang::EbtFloat16)
7347 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007348 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7349 libCall = spv::InterpolateAtVertexAMD;
7350 break;
7351#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007352 case glslang::EOpBarrier:
7353 {
7354 // This is for the extended controlBarrier function, with four operands.
7355 // The unextended barrier() goes through createNoArgOperation.
7356 assert(operands.size() == 4);
7357 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7358 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7359 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7360 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007361 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7362 spv::MemorySemanticsMakeVisibleKHRMask |
7363 spv::MemorySemanticsOutputMemoryKHRMask |
7364 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007365 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7366 }
7367 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7368 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7369 }
7370 return 0;
7371 }
7372 break;
7373 case glslang::EOpMemoryBarrier:
7374 {
7375 // This is for the extended memoryBarrier function, with three operands.
7376 // The unextended memoryBarrier() goes through createNoArgOperation.
7377 assert(operands.size() == 3);
7378 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7379 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7380 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007381 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7382 spv::MemorySemanticsMakeVisibleKHRMask |
7383 spv::MemorySemanticsOutputMemoryKHRMask |
7384 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007385 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7386 }
7387 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7388 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7389 }
7390 return 0;
7391 }
7392 break;
Chao Chen3c366992018-09-19 11:41:59 -07007393
7394#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007395 case glslang::EOpReportIntersectionNV:
7396 {
7397 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007398 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007399 }
7400 break;
7401 case glslang::EOpTraceNV:
7402 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007403 builder.createNoResultOp(spv::OpTraceNV, operands);
7404 return 0;
7405 }
7406 break;
7407 case glslang::EOpExecuteCallableNV:
7408 {
7409 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007410 return 0;
7411 }
7412 break;
Chao Chen3c366992018-09-19 11:41:59 -07007413 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7414 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7415 return 0;
7416#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007417 case glslang::EOpCooperativeMatrixMulAdd:
7418 opCode = spv::OpCooperativeMatrixMulAddNV;
7419 break;
7420
John Kessenich140f3df2015-06-26 16:58:36 -06007421 default:
7422 return 0;
7423 }
7424
7425 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007426 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007427 // Use an extended instruction from the standard library.
7428 // Construct the call arguments, without modifying the original operands vector.
7429 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7430 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007431 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007432 } else if (opCode == spv::OpDot && !isFloat) {
7433 // int dot(int, int)
7434 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7435 const int componentCount = builder.getNumComponents(operands[0]);
7436 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7437 builder.setPrecision(mulOp, precision);
7438 id = builder.createCompositeExtract(mulOp, typeId, 0);
7439 for (int i = 1; i < componentCount; ++i) {
7440 builder.setPrecision(id, precision);
7441 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7442 }
John Kessenich2359bd02015-12-06 19:29:11 -07007443 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007444 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007445 case 0:
7446 // should all be handled by visitAggregate and createNoArgOperation
7447 assert(0);
7448 return 0;
7449 case 1:
7450 // should all be handled by createUnaryOperation
7451 assert(0);
7452 return 0;
7453 case 2:
7454 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7455 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007456 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007457 // anything 3 or over doesn't have l-value operands, so all should be consumed
7458 assert(consumedOperands == operands.size());
7459 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007460 break;
7461 }
7462 }
7463
John Kessenich55e7d112015-11-15 21:33:39 -07007464 // Decode the return types that were structures
7465 switch (op) {
7466 case glslang::EOpAddCarry:
7467 case glslang::EOpSubBorrow:
7468 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7469 id = builder.createCompositeExtract(id, typeId0, 0);
7470 break;
7471 case glslang::EOpUMulExtended:
7472 case glslang::EOpIMulExtended:
7473 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7474 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7475 break;
7476 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007477 {
7478 assert(operands.size() == 2);
7479 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7480 // "exp" is floating-point type (from HLSL intrinsic)
7481 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7482 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7483 builder.createStore(member1, operands[1]);
7484 } else
7485 // "exp" is integer type (from GLSL built-in function)
7486 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7487 id = builder.createCompositeExtract(id, typeId0, 0);
7488 }
John Kessenich55e7d112015-11-15 21:33:39 -07007489 break;
7490 default:
7491 break;
7492 }
7493
John Kessenich32cfd492016-02-02 12:37:46 -07007494 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007495}
7496
Rex Xu9d93a232016-05-05 12:30:44 +08007497// Intrinsics with no arguments (or no return value, and no precision).
7498spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007499{
Jeff Bolz36831c92018-09-05 10:11:41 -05007500 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7501 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007502
7503 switch (op) {
7504 case glslang::EOpEmitVertex:
7505 builder.createNoResultOp(spv::OpEmitVertex);
7506 return 0;
7507 case glslang::EOpEndPrimitive:
7508 builder.createNoResultOp(spv::OpEndPrimitive);
7509 return 0;
7510 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007511 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007512 if (glslangIntermediate->usingVulkanMemoryModel()) {
7513 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7514 spv::MemorySemanticsOutputMemoryKHRMask |
7515 spv::MemorySemanticsAcquireReleaseMask);
7516 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7517 } else {
7518 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7519 }
John Kessenich82979362017-12-11 04:02:24 -07007520 } else {
7521 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7522 spv::MemorySemanticsWorkgroupMemoryMask |
7523 spv::MemorySemanticsAcquireReleaseMask);
7524 }
John Kessenich140f3df2015-06-26 16:58:36 -06007525 return 0;
7526 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007527 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7528 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007529 return 0;
7530 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007531 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7532 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007533 return 0;
7534 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007535 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7536 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007537 return 0;
7538 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007539 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7540 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007541 return 0;
7542 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007543 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7544 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007545 return 0;
7546 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007547 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7548 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007549 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007550 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007551 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007552 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007553 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007554 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007555 case glslang::EOpDeviceMemoryBarrier:
7556 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7557 spv::MemorySemanticsImageMemoryMask |
7558 spv::MemorySemanticsAcquireReleaseMask);
7559 return 0;
7560 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7561 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7562 spv::MemorySemanticsImageMemoryMask |
7563 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007564 return 0;
7565 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007566 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7567 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007568 return 0;
7569 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007570 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7571 spv::MemorySemanticsWorkgroupMemoryMask |
7572 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007573 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007574 case glslang::EOpSubgroupBarrier:
7575 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7576 spv::MemorySemanticsAcquireReleaseMask);
7577 return spv::NoResult;
7578 case glslang::EOpSubgroupMemoryBarrier:
7579 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7580 spv::MemorySemanticsAcquireReleaseMask);
7581 return spv::NoResult;
7582 case glslang::EOpSubgroupMemoryBarrierBuffer:
7583 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7584 spv::MemorySemanticsAcquireReleaseMask);
7585 return spv::NoResult;
7586 case glslang::EOpSubgroupMemoryBarrierImage:
7587 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7588 spv::MemorySemanticsAcquireReleaseMask);
7589 return spv::NoResult;
7590 case glslang::EOpSubgroupMemoryBarrierShared:
7591 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7592 spv::MemorySemanticsAcquireReleaseMask);
7593 return spv::NoResult;
7594 case glslang::EOpSubgroupElect: {
7595 std::vector<spv::Id> operands;
7596 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7597 }
Rex Xu9d93a232016-05-05 12:30:44 +08007598#ifdef AMD_EXTENSIONS
7599 case glslang::EOpTime:
7600 {
7601 std::vector<spv::Id> args; // Dummy arguments
7602 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7603 return builder.setPrecision(id, precision);
7604 }
7605#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007606#ifdef NV_EXTENSIONS
7607 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007608 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007609 return 0;
7610 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007611 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007612 return 0;
7613#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007614
7615 case glslang::EOpBeginInvocationInterlock:
7616 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7617 return 0;
7618 case glslang::EOpEndInvocationInterlock:
7619 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7620 return 0;
7621
Jeff Bolzba6170b2019-07-01 09:23:23 -05007622 case glslang::EOpIsHelperInvocation:
7623 {
7624 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007625 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7626 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7627 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007628 }
7629
amhagan91fb0092019-07-10 21:14:38 -04007630 case glslang::EOpReadClockSubgroupKHR: {
7631 std::vector<spv::Id> args;
7632 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7633 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7634 builder.addCapability(spv::CapabilityShaderClockKHR);
7635 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7636 }
7637
7638 case glslang::EOpReadClockDeviceKHR: {
7639 std::vector<spv::Id> args;
7640 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7641 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7642 builder.addCapability(spv::CapabilityShaderClockKHR);
7643 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7644 }
7645
John Kessenich140f3df2015-06-26 16:58:36 -06007646 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007647 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007648 return 0;
7649 }
7650}
7651
7652spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7653{
John Kessenich2f273362015-07-18 22:34:27 -06007654 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007655 spv::Id id;
7656 if (symbolValues.end() != iter) {
7657 id = iter->second;
7658 return id;
7659 }
7660
7661 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007662 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7663 auto forcedType = getForcedType(builtIn, symbol->getType());
7664 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007665 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007666 if (forcedType.second != spv::NoType)
7667 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007668
Rex Xuc884b4a2016-06-29 15:03:44 +08007669 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007670 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7671 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7672 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007673#ifdef NV_EXTENSIONS
7674 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7675#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007676 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007677 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007678 if (symbol->getQualifier().hasIndex())
7679 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7680 if (symbol->getQualifier().hasComponent())
7681 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007682 // atomic counters use this:
7683 if (symbol->getQualifier().hasOffset())
7684 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007685 }
7686
scygan2c864272016-05-18 18:09:17 +02007687 if (symbol->getQualifier().hasLocation())
7688 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007689 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007690 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007691 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007692 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007693 }
John Kessenich140f3df2015-06-26 16:58:36 -06007694 if (symbol->getQualifier().hasSet())
7695 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007696 else if (IsDescriptorResource(symbol->getType())) {
7697 // default to 0
7698 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7699 }
John Kessenich140f3df2015-06-26 16:58:36 -06007700 if (symbol->getQualifier().hasBinding())
7701 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007702 else if (IsDescriptorResource(symbol->getType())) {
7703 // default to 0
7704 builder.addDecoration(id, spv::DecorationBinding, 0);
7705 }
John Kessenich6c292d32016-02-15 20:58:50 -07007706 if (symbol->getQualifier().hasAttachment())
7707 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007708 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007709 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007710 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007711 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007712 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7713 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7714 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7715 }
7716 if (symbol->getQualifier().hasXfbOffset())
7717 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007718 }
7719
Rex Xu1da878f2016-02-21 20:59:01 +08007720 if (symbol->getType().isImage()) {
7721 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007722 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007723 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007724 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007725 }
7726
John Kessenich9c14f772019-06-17 08:38:35 -06007727 // add built-in variable decoration
7728 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007729 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007730 }
John Kessenich140f3df2015-06-26 16:58:36 -06007731
John Kessenich5611c6d2018-04-05 11:25:02 -06007732 // nonuniform
7733 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7734
John Kessenichecba76f2017-01-06 00:34:48 -07007735#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007736 if (builtIn == spv::BuiltInSampleMask) {
7737 spv::Decoration decoration;
7738 // GL_NV_sample_mask_override_coverage extension
7739 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007740 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007741 else
7742 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007743 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007744 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007745 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007746 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7747 }
7748 }
chaoc771d89f2017-01-13 01:10:53 -08007749 else if (builtIn == spv::BuiltInLayer) {
7750 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007751 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007752 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007753 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7754 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7755 }
John Kessenichb41bff62017-08-11 13:07:17 -06007756 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007757 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7758 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007759 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7760 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7761 }
7762 }
7763
chaoc6e5acae2016-12-20 13:28:52 -08007764 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007765 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007766 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007767 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7768 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007769 if (symbol->getQualifier().pervertexNV) {
7770 builder.addDecoration(id, spv::DecorationPerVertexNV);
7771 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7772 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7773 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007774#endif
7775
John Kessenich5d610ee2018-03-07 18:05:55 -07007776 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7777 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7778 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7779 symbol->getType().getQualifier().semanticName);
7780 }
7781
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007782 if (symbol->getBasicType() == glslang::EbtReference) {
7783 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7784 }
7785
John Kessenich140f3df2015-06-26 16:58:36 -06007786 return id;
7787}
7788
Chao Chen3c366992018-09-19 11:41:59 -07007789#ifdef NV_EXTENSIONS
7790// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7791void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7792{
7793 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007794 if (qualifier.perPrimitiveNV) {
7795 // Need to add capability/extension for fragment shader.
7796 // Mesh shader already adds this by default.
7797 if (glslangIntermediate->getStage() == EShLangFragment) {
7798 builder.addCapability(spv::CapabilityMeshShadingNV);
7799 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7800 }
Chao Chen3c366992018-09-19 11:41:59 -07007801 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007802 }
Chao Chen3c366992018-09-19 11:41:59 -07007803 if (qualifier.perViewNV)
7804 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7805 if (qualifier.perTaskNV)
7806 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7807 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007808 if (qualifier.perPrimitiveNV) {
7809 // Need to add capability/extension for fragment shader.
7810 // Mesh shader already adds this by default.
7811 if (glslangIntermediate->getStage() == EShLangFragment) {
7812 builder.addCapability(spv::CapabilityMeshShadingNV);
7813 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7814 }
Chao Chen3c366992018-09-19 11:41:59 -07007815 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007816 }
Chao Chen3c366992018-09-19 11:41:59 -07007817 if (qualifier.perViewNV)
7818 builder.addDecoration(id, spv::DecorationPerViewNV);
7819 if (qualifier.perTaskNV)
7820 builder.addDecoration(id, spv::DecorationPerTaskNV);
7821 }
7822}
7823#endif
7824
John Kessenich55e7d112015-11-15 21:33:39 -07007825// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007826// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007827//
7828// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7829//
7830// Recursively walk the nodes. The nodes form a tree whose leaves are
7831// regular constants, which themselves are trees that createSpvConstant()
7832// recursively walks. So, this function walks the "top" of the tree:
7833// - emit specialization constant-building instructions for specConstant
7834// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007835spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007836{
John Kessenich7cc0e282016-03-20 00:46:02 -06007837 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007838
qining4f4bb812016-04-03 23:55:17 -04007839 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007840 if (! node.getQualifier().specConstant) {
7841 // hand off to the non-spec-constant path
7842 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7843 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007844 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007845 nextConst, false);
7846 }
7847
7848 // We now know we have a specialization constant to build
7849
John Kessenichd94c0032016-05-30 19:29:40 -06007850 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007851 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7852 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7853 std::vector<spv::Id> dimConstId;
7854 for (int dim = 0; dim < 3; ++dim) {
7855 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7856 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007857 if (specConst) {
7858 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7859 glslangIntermediate->getLocalSizeSpecId(dim));
7860 }
qining4f4bb812016-04-03 23:55:17 -04007861 }
7862 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7863 }
7864
7865 // An AST node labelled as specialization constant should be a symbol node.
7866 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7867 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007868 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007869 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007870 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7871 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7872 // will set the builder into spec constant op instruction generating mode.
7873 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007874 result = accessChainLoad(sub_tree->getType());
7875 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007876 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007877 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007878 } else {
7879 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007880 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007881 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007882 builder.addName(result, sn->getName().c_str());
7883 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007884 }
qining4f4bb812016-04-03 23:55:17 -04007885
7886 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7887 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007888 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007889 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007890}
7891
John Kessenich140f3df2015-06-26 16:58:36 -06007892// Use 'consts' as the flattened glslang source of scalar constants to recursively
7893// build the aggregate SPIR-V constant.
7894//
7895// If there are not enough elements present in 'consts', 0 will be substituted;
7896// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7897//
qining08408382016-03-21 09:51:37 -04007898spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007899{
7900 // vector of constants for SPIR-V
7901 std::vector<spv::Id> spvConsts;
7902
7903 // Type is used for struct and array constants
7904 spv::Id typeId = convertGlslangToSpvType(glslangType);
7905
7906 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007907 glslang::TType elementType(glslangType, 0);
7908 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007909 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007910 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007911 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007912 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007913 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007914 } else if (glslangType.isCoopMat()) {
7915 glslang::TType componentType(glslangType.getBasicType());
7916 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007917 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007918 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7919 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007920 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007921 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007922 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7923 bool zero = nextConst >= consts.size();
7924 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007925 case glslang::EbtInt8:
7926 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7927 break;
7928 case glslang::EbtUint8:
7929 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7930 break;
7931 case glslang::EbtInt16:
7932 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7933 break;
7934 case glslang::EbtUint16:
7935 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7936 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007937 case glslang::EbtInt:
7938 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7939 break;
7940 case glslang::EbtUint:
7941 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7942 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007943 case glslang::EbtInt64:
7944 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7945 break;
7946 case glslang::EbtUint64:
7947 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7948 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007949 case glslang::EbtFloat:
7950 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7951 break;
7952 case glslang::EbtDouble:
7953 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7954 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007955 case glslang::EbtFloat16:
7956 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7957 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007958 case glslang::EbtBool:
7959 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7960 break;
7961 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007962 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007963 break;
7964 }
7965 ++nextConst;
7966 }
7967 } else {
7968 // we have a non-aggregate (scalar) constant
7969 bool zero = nextConst >= consts.size();
7970 spv::Id scalar = 0;
7971 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007972 case glslang::EbtInt8:
7973 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7974 break;
7975 case glslang::EbtUint8:
7976 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7977 break;
7978 case glslang::EbtInt16:
7979 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7980 break;
7981 case glslang::EbtUint16:
7982 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7983 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007984 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007985 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007986 break;
7987 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007988 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007989 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007990 case glslang::EbtInt64:
7991 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7992 break;
7993 case glslang::EbtUint64:
7994 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7995 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007996 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007997 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007998 break;
7999 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008000 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008001 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008002 case glslang::EbtFloat16:
8003 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8004 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008005 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07008006 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008007 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008008 case glslang::EbtReference:
8009 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8010 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8011 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008012 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008013 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008014 break;
8015 }
8016 ++nextConst;
8017 return scalar;
8018 }
8019
8020 return builder.makeCompositeConstant(typeId, spvConsts);
8021}
8022
John Kessenich7c1aa102015-10-15 13:29:11 -06008023// Return true if the node is a constant or symbol whose reading has no
8024// non-trivial observable cost or effect.
8025bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8026{
8027 // don't know what this is
8028 if (node == nullptr)
8029 return false;
8030
8031 // a constant is safe
8032 if (node->getAsConstantUnion() != nullptr)
8033 return true;
8034
8035 // not a symbol means non-trivial
8036 if (node->getAsSymbolNode() == nullptr)
8037 return false;
8038
8039 // a symbol, depends on what's being read
8040 switch (node->getType().getQualifier().storage) {
8041 case glslang::EvqTemporary:
8042 case glslang::EvqGlobal:
8043 case glslang::EvqIn:
8044 case glslang::EvqInOut:
8045 case glslang::EvqConst:
8046 case glslang::EvqConstReadOnly:
8047 case glslang::EvqUniform:
8048 return true;
8049 default:
8050 return false;
8051 }
qining25262b32016-05-06 17:25:16 -04008052}
John Kessenich7c1aa102015-10-15 13:29:11 -06008053
8054// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008055// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008056// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008057// Return true if trivial.
8058bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8059{
8060 if (node == nullptr)
8061 return false;
8062
John Kessenich84cc15f2017-05-24 16:44:47 -06008063 // count non scalars as trivial, as well as anything coming from HLSL
8064 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008065 return true;
8066
John Kessenich7c1aa102015-10-15 13:29:11 -06008067 // symbols and constants are trivial
8068 if (isTrivialLeaf(node))
8069 return true;
8070
8071 // otherwise, it needs to be a simple operation or one or two leaf nodes
8072
8073 // not a simple operation
8074 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8075 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8076 if (binaryNode == nullptr && unaryNode == nullptr)
8077 return false;
8078
8079 // not on leaf nodes
8080 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8081 return false;
8082
8083 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8084 return false;
8085 }
8086
8087 switch (node->getAsOperator()->getOp()) {
8088 case glslang::EOpLogicalNot:
8089 case glslang::EOpConvIntToBool:
8090 case glslang::EOpConvUintToBool:
8091 case glslang::EOpConvFloatToBool:
8092 case glslang::EOpConvDoubleToBool:
8093 case glslang::EOpEqual:
8094 case glslang::EOpNotEqual:
8095 case glslang::EOpLessThan:
8096 case glslang::EOpGreaterThan:
8097 case glslang::EOpLessThanEqual:
8098 case glslang::EOpGreaterThanEqual:
8099 case glslang::EOpIndexDirect:
8100 case glslang::EOpIndexDirectStruct:
8101 case glslang::EOpLogicalXor:
8102 case glslang::EOpAny:
8103 case glslang::EOpAll:
8104 return true;
8105 default:
8106 return false;
8107 }
8108}
8109
8110// Emit short-circuiting code, where 'right' is never evaluated unless
8111// the left side is true (for &&) or false (for ||).
8112spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8113{
8114 spv::Id boolTypeId = builder.makeBoolType();
8115
8116 // emit left operand
8117 builder.clearAccessChain();
8118 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008119 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008120
8121 // Operands to accumulate OpPhi operands
8122 std::vector<spv::Id> phiOperands;
8123 // accumulate left operand's phi information
8124 phiOperands.push_back(leftId);
8125 phiOperands.push_back(builder.getBuildPoint()->getId());
8126
8127 // Make the two kinds of operation symmetric with a "!"
8128 // || => emit "if (! left) result = right"
8129 // && => emit "if ( left) result = right"
8130 //
8131 // TODO: this runtime "not" for || could be avoided by adding functionality
8132 // to 'builder' to have an "else" without an "then"
8133 if (op == glslang::EOpLogicalOr)
8134 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8135
8136 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008137 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008138
8139 // emit right operand as the "then" part of the "if"
8140 builder.clearAccessChain();
8141 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008142 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008143
8144 // accumulate left operand's phi information
8145 phiOperands.push_back(rightId);
8146 phiOperands.push_back(builder.getBuildPoint()->getId());
8147
8148 // finish the "if"
8149 ifBuilder.makeEndIf();
8150
8151 // phi together the two results
8152 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8153}
8154
Frank Henigman541f7bb2018-01-16 00:18:26 -05008155#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08008156// Return type Id of the imported set of extended instructions corresponds to the name.
8157// Import this set if it has not been imported yet.
8158spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8159{
8160 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8161 return extBuiltinMap[name];
8162 else {
Rex Xu51596642016-09-21 18:56:12 +08008163 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008164 spv::Id extBuiltins = builder.import(name);
8165 extBuiltinMap[name] = extBuiltins;
8166 return extBuiltins;
8167 }
8168}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008169#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008170
John Kessenich140f3df2015-06-26 16:58:36 -06008171}; // end anonymous namespace
8172
8173namespace glslang {
8174
John Kessenich68d78fd2015-07-12 19:28:10 -06008175void GetSpirvVersion(std::string& version)
8176{
John Kessenich9e55f632015-07-15 10:03:39 -06008177 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008178 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008179 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008180 version = buf;
8181}
8182
John Kessenicha372a3e2017-11-02 22:32:14 -06008183// For low-order part of the generator's magic number. Bump up
8184// when there is a change in the style (e.g., if SSA form changes,
8185// or a different instruction sequence to do something gets used).
8186int GetSpirvGeneratorVersion()
8187{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008188 // return 1; // start
8189 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008190 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008191 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008192 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008193 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8194 // versions 4 and 6 each generate OpArrayLength as it has long been done
8195 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008196}
8197
John Kessenich140f3df2015-06-26 16:58:36 -06008198// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008199void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008200{
8201 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008202 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008203 if (out.fail())
8204 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008205 for (int i = 0; i < (int)spirv.size(); ++i) {
8206 unsigned int word = spirv[i];
8207 out.write((const char*)&word, 4);
8208 }
8209 out.close();
8210}
8211
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008212// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008213void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008214{
8215 std::ofstream out;
8216 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008217 if (out.fail())
8218 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008219 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008220 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008221 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008222 if (varName != nullptr) {
8223 out << "\t #pragma once" << std::endl;
8224 out << "const uint32_t " << varName << "[] = {" << std::endl;
8225 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008226 const int WORDS_PER_LINE = 8;
8227 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8228 out << "\t";
8229 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8230 const unsigned int word = spirv[i + j];
8231 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8232 if (i + j + 1 < (int)spirv.size()) {
8233 out << ",";
8234 }
8235 }
8236 out << std::endl;
8237 }
Flavio15017db2017-02-15 14:29:33 -08008238 if (varName != nullptr) {
8239 out << "};";
8240 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008241 out.close();
8242}
8243
John Kessenich140f3df2015-06-26 16:58:36 -06008244//
8245// Set up the glslang traversal
8246//
John Kessenich4e11b612018-08-30 16:56:59 -06008247void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008248{
Lei Zhang17535f72016-05-04 15:55:59 -04008249 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008250 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008251}
8252
John Kessenich4e11b612018-08-30 16:56:59 -06008253void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008254 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008255{
John Kessenich140f3df2015-06-26 16:58:36 -06008256 TIntermNode* root = intermediate.getTreeRoot();
8257
8258 if (root == 0)
8259 return;
8260
John Kessenich4e11b612018-08-30 16:56:59 -06008261 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008262 if (options == nullptr)
8263 options = &defaultOptions;
8264
John Kessenich4e11b612018-08-30 16:56:59 -06008265 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008266
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008267 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008268 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008269 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008270 it.dumpSpv(spirv);
8271
GregFfb03a552018-03-29 11:49:14 -06008272#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008273 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8274 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008275 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8276 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008277 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008278 prelegalization = false;
8279 }
John Kessenich717c80a2018-08-23 15:17:10 -06008280
John Kessenich4e11b612018-08-30 16:56:59 -06008281 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008282 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008283
John Kessenich717c80a2018-08-23 15:17:10 -06008284 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008285 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008286
GregFcd1f1692017-09-21 18:40:22 -06008287#endif
8288
John Kessenich4e11b612018-08-30 16:56:59 -06008289 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008290}
8291
8292}; // end namespace glslang