Path: blob/main/contrib/llvm-project/clang/lib/AST/ItaniumMangle.cpp
35259 views
//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// Implements C++ name mangling according to the Itanium C++ ABI,9// which is used in GCC 3.2 and newer (and many compilers that are10// ABI-compatible with GCC):11//12// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling13//14//===----------------------------------------------------------------------===//1516#include "clang/AST/ASTContext.h"17#include "clang/AST/Attr.h"18#include "clang/AST/Decl.h"19#include "clang/AST/DeclCXX.h"20#include "clang/AST/DeclObjC.h"21#include "clang/AST/DeclOpenMP.h"22#include "clang/AST/DeclTemplate.h"23#include "clang/AST/Expr.h"24#include "clang/AST/ExprCXX.h"25#include "clang/AST/ExprConcepts.h"26#include "clang/AST/ExprObjC.h"27#include "clang/AST/Mangle.h"28#include "clang/AST/TypeLoc.h"29#include "clang/Basic/ABI.h"30#include "clang/Basic/DiagnosticAST.h"31#include "clang/Basic/Module.h"32#include "clang/Basic/SourceManager.h"33#include "clang/Basic/TargetInfo.h"34#include "clang/Basic/Thunk.h"35#include "llvm/ADT/StringExtras.h"36#include "llvm/Support/ErrorHandling.h"37#include "llvm/Support/raw_ostream.h"38#include "llvm/TargetParser/RISCVTargetParser.h"39#include <optional>4041using namespace clang;4243namespace {4445static bool isLocalContainerContext(const DeclContext *DC) {46return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);47}4849static const FunctionDecl *getStructor(const FunctionDecl *fn) {50if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())51return ftd->getTemplatedDecl();5253return fn;54}5556static const NamedDecl *getStructor(const NamedDecl *decl) {57const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);58return (fn ? getStructor(fn) : decl);59}6061static bool isLambda(const NamedDecl *ND) {62const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);63if (!Record)64return false;6566return Record->isLambda();67}6869static const unsigned UnknownArity = ~0U;7071class ItaniumMangleContextImpl : public ItaniumMangleContext {72typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;73llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;74llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;75const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;76NamespaceDecl *StdNamespace = nullptr;7778bool NeedsUniqueInternalLinkageNames = false;7980public:81explicit ItaniumMangleContextImpl(82ASTContext &Context, DiagnosticsEngine &Diags,83DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)84: ItaniumMangleContext(Context, Diags, IsAux),85DiscriminatorOverride(DiscriminatorOverride) {}8687/// @name Mangler Entry Points88/// @{8990bool shouldMangleCXXName(const NamedDecl *D) override;91bool shouldMangleStringLiteral(const StringLiteral *) override {92return false;93}9495bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;96void needsUniqueInternalLinkageNames() override {97NeedsUniqueInternalLinkageNames = true;98}99100void mangleCXXName(GlobalDecl GD, raw_ostream &) override;101void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, bool,102raw_ostream &) override;103void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,104const ThunkInfo &Thunk, bool, raw_ostream &) override;105void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,106raw_ostream &) override;107void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;108void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;109void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,110const CXXRecordDecl *Type, raw_ostream &) override;111void mangleCXXRTTI(QualType T, raw_ostream &) override;112void mangleCXXRTTIName(QualType T, raw_ostream &,113bool NormalizeIntegers) override;114void mangleCanonicalTypeName(QualType T, raw_ostream &,115bool NormalizeIntegers) override;116117void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;118void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;119void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;120void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;121void mangleDynamicAtExitDestructor(const VarDecl *D,122raw_ostream &Out) override;123void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;124void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,125raw_ostream &Out) override;126void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,127raw_ostream &Out) override;128void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;129void mangleItaniumThreadLocalWrapper(const VarDecl *D,130raw_ostream &) override;131132void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;133134void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;135136void mangleModuleInitializer(const Module *Module, raw_ostream &) override;137138bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {139// Lambda closure types are already numbered.140if (isLambda(ND))141return false;142143// Anonymous tags are already numbered.144if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {145if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())146return false;147}148149// Use the canonical number for externally visible decls.150if (ND->isExternallyVisible()) {151unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());152if (discriminator == 1)153return false;154disc = discriminator - 2;155return true;156}157158// Make up a reasonable number for internal decls.159unsigned &discriminator = Uniquifier[ND];160if (!discriminator) {161const DeclContext *DC = getEffectiveDeclContext(ND);162discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];163}164if (discriminator == 1)165return false;166disc = discriminator-2;167return true;168}169170std::string getLambdaString(const CXXRecordDecl *Lambda) override {171// This function matches the one in MicrosoftMangle, which returns172// the string that is used in lambda mangled names.173assert(Lambda->isLambda() && "RD must be a lambda!");174std::string Name("<lambda");175Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();176unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();177unsigned LambdaId;178const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);179const FunctionDecl *Func =180Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;181182if (Func) {183unsigned DefaultArgNo =184Func->getNumParams() - Parm->getFunctionScopeIndex();185Name += llvm::utostr(DefaultArgNo);186Name += "_";187}188189if (LambdaManglingNumber)190LambdaId = LambdaManglingNumber;191else192LambdaId = getAnonymousStructIdForDebugInfo(Lambda);193194Name += llvm::utostr(LambdaId);195Name += '>';196return Name;197}198199DiscriminatorOverrideTy getDiscriminatorOverride() const override {200return DiscriminatorOverride;201}202203NamespaceDecl *getStdNamespace();204205const DeclContext *getEffectiveDeclContext(const Decl *D);206const DeclContext *getEffectiveParentContext(const DeclContext *DC) {207return getEffectiveDeclContext(cast<Decl>(DC));208}209210bool isInternalLinkageDecl(const NamedDecl *ND);211212/// @}213};214215/// Manage the mangling of a single name.216class CXXNameMangler {217ItaniumMangleContextImpl &Context;218raw_ostream &Out;219/// Normalize integer types for cross-language CFI support with other220/// languages that can't represent and encode C/C++ integer types.221bool NormalizeIntegers = false;222223bool NullOut = false;224/// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.225/// This mode is used when mangler creates another mangler recursively to226/// calculate ABI tags for the function return value or the variable type.227/// Also it is required to avoid infinite recursion in some cases.228bool DisableDerivedAbiTags = false;229230/// The "structor" is the top-level declaration being mangled, if231/// that's not a template specialization; otherwise it's the pattern232/// for that specialization.233const NamedDecl *Structor;234unsigned StructorType = 0;235236// An offset to add to all template parameter depths while mangling. Used237// when mangling a template parameter list to see if it matches a template238// template parameter exactly.239unsigned TemplateDepthOffset = 0;240241/// The next substitution sequence number.242unsigned SeqID = 0;243244class FunctionTypeDepthState {245unsigned Bits = 0;246247enum { InResultTypeMask = 1 };248249public:250FunctionTypeDepthState() = default;251252/// The number of function types we're inside.253unsigned getDepth() const {254return Bits >> 1;255}256257/// True if we're in the return type of the innermost function type.258bool isInResultType() const {259return Bits & InResultTypeMask;260}261262FunctionTypeDepthState push() {263FunctionTypeDepthState tmp = *this;264Bits = (Bits & ~InResultTypeMask) + 2;265return tmp;266}267268void enterResultType() {269Bits |= InResultTypeMask;270}271272void leaveResultType() {273Bits &= ~InResultTypeMask;274}275276void pop(FunctionTypeDepthState saved) {277assert(getDepth() == saved.getDepth() + 1);278Bits = saved.Bits;279}280281} FunctionTypeDepth;282283// abi_tag is a gcc attribute, taking one or more strings called "tags".284// The goal is to annotate against which version of a library an object was285// built and to be able to provide backwards compatibility ("dual abi").286// For more information see docs/ItaniumMangleAbiTags.rst.287typedef SmallVector<StringRef, 4> AbiTagList;288289// State to gather all implicit and explicit tags used in a mangled name.290// Must always have an instance of this while emitting any name to keep291// track.292class AbiTagState final {293public:294explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {295Parent = LinkHead;296LinkHead = this;297}298299// No copy, no move.300AbiTagState(const AbiTagState &) = delete;301AbiTagState &operator=(const AbiTagState &) = delete;302303~AbiTagState() { pop(); }304305void write(raw_ostream &Out, const NamedDecl *ND,306const AbiTagList *AdditionalAbiTags) {307ND = cast<NamedDecl>(ND->getCanonicalDecl());308if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {309assert(310!AdditionalAbiTags &&311"only function and variables need a list of additional abi tags");312if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {313if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {314UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),315AbiTag->tags().end());316}317// Don't emit abi tags for namespaces.318return;319}320}321322AbiTagList TagList;323if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {324UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),325AbiTag->tags().end());326TagList.insert(TagList.end(), AbiTag->tags().begin(),327AbiTag->tags().end());328}329330if (AdditionalAbiTags) {331UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),332AdditionalAbiTags->end());333TagList.insert(TagList.end(), AdditionalAbiTags->begin(),334AdditionalAbiTags->end());335}336337llvm::sort(TagList);338TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());339340writeSortedUniqueAbiTags(Out, TagList);341}342343const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }344void setUsedAbiTags(const AbiTagList &AbiTags) {345UsedAbiTags = AbiTags;346}347348const AbiTagList &getEmittedAbiTags() const {349return EmittedAbiTags;350}351352const AbiTagList &getSortedUniqueUsedAbiTags() {353llvm::sort(UsedAbiTags);354UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),355UsedAbiTags.end());356return UsedAbiTags;357}358359private:360//! All abi tags used implicitly or explicitly.361AbiTagList UsedAbiTags;362//! All explicit abi tags (i.e. not from namespace).363AbiTagList EmittedAbiTags;364365AbiTagState *&LinkHead;366AbiTagState *Parent = nullptr;367368void pop() {369assert(LinkHead == this &&370"abi tag link head must point to us on destruction");371if (Parent) {372Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),373UsedAbiTags.begin(), UsedAbiTags.end());374Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),375EmittedAbiTags.begin(),376EmittedAbiTags.end());377}378LinkHead = Parent;379}380381void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {382for (const auto &Tag : AbiTags) {383EmittedAbiTags.push_back(Tag);384Out << "B";385Out << Tag.size();386Out << Tag;387}388}389};390391AbiTagState *AbiTags = nullptr;392AbiTagState AbiTagsRoot;393394llvm::DenseMap<uintptr_t, unsigned> Substitutions;395llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;396397ASTContext &getASTContext() const { return Context.getASTContext(); }398399bool isCompatibleWith(LangOptions::ClangABI Ver) {400return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver;401}402403bool isStd(const NamespaceDecl *NS);404bool isStdNamespace(const DeclContext *DC);405406const RecordDecl *GetLocalClassDecl(const Decl *D);407bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);408bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,409llvm::StringRef Name, bool HasAllocator);410411public:412CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,413const NamedDecl *D = nullptr, bool NullOut_ = false)414: Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),415AbiTagsRoot(AbiTags) {416// These can't be mangled without a ctor type or dtor type.417assert(!D || (!isa<CXXDestructorDecl>(D) &&418!isa<CXXConstructorDecl>(D)));419}420CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,421const CXXConstructorDecl *D, CXXCtorType Type)422: Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),423AbiTagsRoot(AbiTags) {}424CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,425const CXXDestructorDecl *D, CXXDtorType Type)426: Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),427AbiTagsRoot(AbiTags) {}428429CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,430bool NormalizeIntegers_)431: Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),432NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}433CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)434: Context(Outer.Context), Out(Out_), Structor(Outer.Structor),435StructorType(Outer.StructorType), SeqID(Outer.SeqID),436FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),437Substitutions(Outer.Substitutions),438ModuleSubstitutions(Outer.ModuleSubstitutions) {}439440CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)441: CXXNameMangler(Outer, (raw_ostream &)Out_) {442NullOut = true;443}444445struct WithTemplateDepthOffset { unsigned Offset; };446CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out,447WithTemplateDepthOffset Offset)448: CXXNameMangler(C, Out) {449TemplateDepthOffset = Offset.Offset;450}451452raw_ostream &getStream() { return Out; }453454void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }455static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);456457void mangle(GlobalDecl GD);458void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);459void mangleNumber(const llvm::APSInt &I);460void mangleNumber(int64_t Number);461void mangleFloat(const llvm::APFloat &F);462void mangleFunctionEncoding(GlobalDecl GD);463void mangleSeqID(unsigned SeqID);464void mangleName(GlobalDecl GD);465void mangleType(QualType T);466void mangleNameOrStandardSubstitution(const NamedDecl *ND);467void mangleLambdaSig(const CXXRecordDecl *Lambda);468void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);469void mangleVendorQualifier(StringRef Name);470471private:472473bool mangleSubstitution(const NamedDecl *ND);474bool mangleSubstitution(NestedNameSpecifier *NNS);475bool mangleSubstitution(QualType T);476bool mangleSubstitution(TemplateName Template);477bool mangleSubstitution(uintptr_t Ptr);478479void mangleExistingSubstitution(TemplateName name);480481bool mangleStandardSubstitution(const NamedDecl *ND);482483void addSubstitution(const NamedDecl *ND) {484ND = cast<NamedDecl>(ND->getCanonicalDecl());485486addSubstitution(reinterpret_cast<uintptr_t>(ND));487}488void addSubstitution(NestedNameSpecifier *NNS) {489NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);490491addSubstitution(reinterpret_cast<uintptr_t>(NNS));492}493void addSubstitution(QualType T);494void addSubstitution(TemplateName Template);495void addSubstitution(uintptr_t Ptr);496// Destructive copy substitutions from other mangler.497void extendSubstitutions(CXXNameMangler* Other);498499void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,500bool recursive = false);501void mangleUnresolvedName(NestedNameSpecifier *qualifier,502DeclarationName name,503const TemplateArgumentLoc *TemplateArgs,504unsigned NumTemplateArgs,505unsigned KnownArity = UnknownArity);506507void mangleFunctionEncodingBareType(const FunctionDecl *FD);508509void mangleNameWithAbiTags(GlobalDecl GD,510const AbiTagList *AdditionalAbiTags);511void mangleModuleName(const NamedDecl *ND);512void mangleTemplateName(const TemplateDecl *TD,513ArrayRef<TemplateArgument> Args);514void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,515const AbiTagList *AdditionalAbiTags) {516mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,517UnknownArity, AdditionalAbiTags);518}519void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,520const DeclContext *DC, unsigned KnownArity,521const AbiTagList *AdditionalAbiTags);522void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,523const AbiTagList *AdditionalAbiTags);524void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,525const AbiTagList *AdditionalAbiTags);526void mangleSourceName(const IdentifierInfo *II);527void mangleRegCallName(const IdentifierInfo *II);528void mangleDeviceStubName(const IdentifierInfo *II);529void mangleSourceNameWithAbiTags(530const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);531void mangleLocalName(GlobalDecl GD,532const AbiTagList *AdditionalAbiTags);533void mangleBlockForPrefix(const BlockDecl *Block);534void mangleUnqualifiedBlock(const BlockDecl *Block);535void mangleTemplateParamDecl(const NamedDecl *Decl);536void mangleTemplateParameterList(const TemplateParameterList *Params);537void mangleTypeConstraint(const ConceptDecl *Concept,538ArrayRef<TemplateArgument> Arguments);539void mangleTypeConstraint(const TypeConstraint *Constraint);540void mangleRequiresClause(const Expr *RequiresClause);541void mangleLambda(const CXXRecordDecl *Lambda);542void mangleNestedName(GlobalDecl GD, const DeclContext *DC,543const AbiTagList *AdditionalAbiTags,544bool NoFunction=false);545void mangleNestedName(const TemplateDecl *TD,546ArrayRef<TemplateArgument> Args);547void mangleNestedNameWithClosurePrefix(GlobalDecl GD,548const NamedDecl *PrefixND,549const AbiTagList *AdditionalAbiTags);550void manglePrefix(NestedNameSpecifier *qualifier);551void manglePrefix(const DeclContext *DC, bool NoFunction=false);552void manglePrefix(QualType type);553void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);554void mangleTemplatePrefix(TemplateName Template);555const NamedDecl *getClosurePrefix(const Decl *ND);556void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);557bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,558StringRef Prefix = "");559void mangleOperatorName(DeclarationName Name, unsigned Arity);560void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);561void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);562void mangleRefQualifier(RefQualifierKind RefQualifier);563564void mangleObjCMethodName(const ObjCMethodDecl *MD);565566// Declare manglers for every type class.567#define ABSTRACT_TYPE(CLASS, PARENT)568#define NON_CANONICAL_TYPE(CLASS, PARENT)569#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);570#include "clang/AST/TypeNodes.inc"571572void mangleType(const TagType*);573void mangleType(TemplateName);574static StringRef getCallingConvQualifierName(CallingConv CC);575void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);576void mangleExtFunctionInfo(const FunctionType *T);577void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,578const FunctionDecl *FD = nullptr);579void mangleNeonVectorType(const VectorType *T);580void mangleNeonVectorType(const DependentVectorType *T);581void mangleAArch64NeonVectorType(const VectorType *T);582void mangleAArch64NeonVectorType(const DependentVectorType *T);583void mangleAArch64FixedSveVectorType(const VectorType *T);584void mangleAArch64FixedSveVectorType(const DependentVectorType *T);585void mangleRISCVFixedRVVVectorType(const VectorType *T);586void mangleRISCVFixedRVVVectorType(const DependentVectorType *T);587588void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);589void mangleFloatLiteral(QualType T, const llvm::APFloat &V);590void mangleFixedPointLiteral();591void mangleNullPointer(QualType T);592593void mangleMemberExprBase(const Expr *base, bool isArrow);594void mangleMemberExpr(const Expr *base, bool isArrow,595NestedNameSpecifier *qualifier,596NamedDecl *firstQualifierLookup,597DeclarationName name,598const TemplateArgumentLoc *TemplateArgs,599unsigned NumTemplateArgs,600unsigned knownArity);601void mangleCastExpression(const Expr *E, StringRef CastEncoding);602void mangleInitListElements(const InitListExpr *InitList);603void mangleRequirement(SourceLocation RequiresExprLoc,604const concepts::Requirement *Req);605void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,606bool AsTemplateArg = false);607void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);608void mangleCXXDtorType(CXXDtorType T);609610struct TemplateArgManglingInfo;611void mangleTemplateArgs(TemplateName TN,612const TemplateArgumentLoc *TemplateArgs,613unsigned NumTemplateArgs);614void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);615void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);616void mangleTemplateArg(TemplateArgManglingInfo &Info, unsigned Index,617TemplateArgument A);618void mangleTemplateArg(TemplateArgument A, bool NeedExactType);619void mangleTemplateArgExpr(const Expr *E);620void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,621bool NeedExactType = false);622623void mangleTemplateParameter(unsigned Depth, unsigned Index);624625void mangleFunctionParam(const ParmVarDecl *parm);626627void writeAbiTags(const NamedDecl *ND,628const AbiTagList *AdditionalAbiTags);629630// Returns sorted unique list of ABI tags.631AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);632// Returns sorted unique list of ABI tags.633AbiTagList makeVariableTypeTags(const VarDecl *VD);634};635636}637638NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {639if (!StdNamespace) {640StdNamespace = NamespaceDecl::Create(641getASTContext(), getASTContext().getTranslationUnitDecl(),642/*Inline=*/false, SourceLocation(), SourceLocation(),643&getASTContext().Idents.get("std"),644/*PrevDecl=*/nullptr, /*Nested=*/false);645StdNamespace->setImplicit();646}647return StdNamespace;648}649650/// Retrieve the declaration context that should be used when mangling the given651/// declaration.652const DeclContext *653ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {654// The ABI assumes that lambda closure types that occur within655// default arguments live in the context of the function. However, due to656// the way in which Clang parses and creates function declarations, this is657// not the case: the lambda closure type ends up living in the context658// where the function itself resides, because the function declaration itself659// had not yet been created. Fix the context here.660if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {661if (RD->isLambda())662if (ParmVarDecl *ContextParam =663dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))664return ContextParam->getDeclContext();665}666667// Perform the same check for block literals.668if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {669if (ParmVarDecl *ContextParam =670dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))671return ContextParam->getDeclContext();672}673674// On ARM and AArch64, the va_list tag is always mangled as if in the std675// namespace. We do not represent va_list as actually being in the std676// namespace in C because this would result in incorrect debug info in C,677// among other things. It is important for both languages to have the same678// mangling in order for -fsanitize=cfi-icall to work.679if (D == getASTContext().getVaListTagDecl()) {680const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();681if (T.isARM() || T.isThumb() || T.isAArch64())682return getStdNamespace();683}684685const DeclContext *DC = D->getDeclContext();686if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||687isa<OMPDeclareMapperDecl>(DC)) {688return getEffectiveDeclContext(cast<Decl>(DC));689}690691if (const auto *VD = dyn_cast<VarDecl>(D))692if (VD->isExternC())693return getASTContext().getTranslationUnitDecl();694695if (const auto *FD = dyn_cast<FunctionDecl>(D)) {696if (FD->isExternC())697return getASTContext().getTranslationUnitDecl();698// Member-like constrained friends are mangled as if they were members of699// the enclosing class.700if (FD->isMemberLikeConstrainedFriend() &&701getASTContext().getLangOpts().getClangABICompat() >702LangOptions::ClangABI::Ver17)703return D->getLexicalDeclContext()->getRedeclContext();704}705706return DC->getRedeclContext();707}708709bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {710if (ND && ND->getFormalLinkage() == Linkage::Internal &&711!ND->isExternallyVisible() &&712getEffectiveDeclContext(ND)->isFileContext() &&713!ND->isInAnonymousNamespace())714return true;715return false;716}717718// Check if this Function Decl needs a unique internal linkage name.719bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(720const NamedDecl *ND) {721if (!NeedsUniqueInternalLinkageNames || !ND)722return false;723724const auto *FD = dyn_cast<FunctionDecl>(ND);725if (!FD)726return false;727728// For C functions without prototypes, return false as their729// names should not be mangled.730if (!FD->getType()->getAs<FunctionProtoType>())731return false;732733if (isInternalLinkageDecl(ND))734return true;735736return false;737}738739bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {740if (const auto *FD = dyn_cast<FunctionDecl>(D)) {741LanguageLinkage L = FD->getLanguageLinkage();742// Overloadable functions need mangling.743if (FD->hasAttr<OverloadableAttr>())744return true;745746// "main" is not mangled.747if (FD->isMain())748return false;749750// The Windows ABI expects that we would never mangle "typical"751// user-defined entry points regardless of visibility or freestanding-ness.752//753// N.B. This is distinct from asking about "main". "main" has a lot of754// special rules associated with it in the standard while these755// user-defined entry points are outside of the purview of the standard.756// For example, there can be only one definition for "main" in a standards757// compliant program; however nothing forbids the existence of wmain and758// WinMain in the same translation unit.759if (FD->isMSVCRTEntryPoint())760return false;761762// C++ functions and those whose names are not a simple identifier need763// mangling.764if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)765return true;766767// C functions are not mangled.768if (L == CLanguageLinkage)769return false;770}771772// Otherwise, no mangling is done outside C++ mode.773if (!getASTContext().getLangOpts().CPlusPlus)774return false;775776if (const auto *VD = dyn_cast<VarDecl>(D)) {777// Decompositions are mangled.778if (isa<DecompositionDecl>(VD))779return true;780781// C variables are not mangled.782if (VD->isExternC())783return false;784785// Variables at global scope are not mangled unless they have internal786// linkage or are specializations or are attached to a named module.787const DeclContext *DC = getEffectiveDeclContext(D);788// Check for extern variable declared locally.789if (DC->isFunctionOrMethod() && D->hasLinkage())790while (!DC->isFileContext())791DC = getEffectiveParentContext(DC);792if (DC->isTranslationUnit() && D->getFormalLinkage() != Linkage::Internal &&793!CXXNameMangler::shouldHaveAbiTags(*this, VD) &&794!isa<VarTemplateSpecializationDecl>(VD) &&795!VD->getOwningModuleForLinkage())796return false;797}798799return true;800}801802void CXXNameMangler::writeAbiTags(const NamedDecl *ND,803const AbiTagList *AdditionalAbiTags) {804assert(AbiTags && "require AbiTagState");805AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);806}807808void CXXNameMangler::mangleSourceNameWithAbiTags(809const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {810mangleSourceName(ND->getIdentifier());811writeAbiTags(ND, AdditionalAbiTags);812}813814void CXXNameMangler::mangle(GlobalDecl GD) {815// <mangled-name> ::= _Z <encoding>816// ::= <data name>817// ::= <special-name>818Out << "_Z";819if (isa<FunctionDecl>(GD.getDecl()))820mangleFunctionEncoding(GD);821else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,822BindingDecl>(GD.getDecl()))823mangleName(GD);824else if (const IndirectFieldDecl *IFD =825dyn_cast<IndirectFieldDecl>(GD.getDecl()))826mangleName(IFD->getAnonField());827else828llvm_unreachable("unexpected kind of global decl");829}830831void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {832const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());833// <encoding> ::= <function name> <bare-function-type>834835// Don't mangle in the type if this isn't a decl we should typically mangle.836if (!Context.shouldMangleDeclName(FD)) {837mangleName(GD);838return;839}840841AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);842if (ReturnTypeAbiTags.empty()) {843// There are no tags for return type, the simplest case. Enter the function844// parameter scope before mangling the name, because a template using845// constrained `auto` can have references to its parameters within its846// template argument list:847//848// template<typename T> void f(T x, C<decltype(x)> auto)849// ... is mangled as ...850// template<typename T, C<decltype(param 1)> U> void f(T, U)851FunctionTypeDepthState Saved = FunctionTypeDepth.push();852mangleName(GD);853FunctionTypeDepth.pop(Saved);854mangleFunctionEncodingBareType(FD);855return;856}857858// Mangle function name and encoding to temporary buffer.859// We have to output name and encoding to the same mangler to get the same860// substitution as it will be in final mangling.861SmallString<256> FunctionEncodingBuf;862llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);863CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);864// Output name of the function.865FunctionEncodingMangler.disableDerivedAbiTags();866867FunctionTypeDepthState Saved = FunctionTypeDepth.push();868FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);869FunctionTypeDepth.pop(Saved);870871// Remember length of the function name in the buffer.872size_t EncodingPositionStart = FunctionEncodingStream.str().size();873FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);874875// Get tags from return type that are not present in function name or876// encoding.877const AbiTagList &UsedAbiTags =878FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();879AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());880AdditionalAbiTags.erase(881std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),882UsedAbiTags.begin(), UsedAbiTags.end(),883AdditionalAbiTags.begin()),884AdditionalAbiTags.end());885886// Output name with implicit tags and function encoding from temporary buffer.887Saved = FunctionTypeDepth.push();888mangleNameWithAbiTags(FD, &AdditionalAbiTags);889FunctionTypeDepth.pop(Saved);890Out << FunctionEncodingStream.str().substr(EncodingPositionStart);891892// Function encoding could create new substitutions so we have to add893// temp mangled substitutions to main mangler.894extendSubstitutions(&FunctionEncodingMangler);895}896897void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {898if (FD->hasAttr<EnableIfAttr>()) {899FunctionTypeDepthState Saved = FunctionTypeDepth.push();900Out << "Ua9enable_ifI";901for (AttrVec::const_iterator I = FD->getAttrs().begin(),902E = FD->getAttrs().end();903I != E; ++I) {904EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);905if (!EIA)906continue;907if (isCompatibleWith(LangOptions::ClangABI::Ver11)) {908// Prior to Clang 12, we hardcoded the X/E around enable-if's argument,909// even though <template-arg> should not include an X/E around910// <expr-primary>.911Out << 'X';912mangleExpression(EIA->getCond());913Out << 'E';914} else {915mangleTemplateArgExpr(EIA->getCond());916}917}918Out << 'E';919FunctionTypeDepth.pop(Saved);920}921922// When mangling an inheriting constructor, the bare function type used is923// that of the inherited constructor.924if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))925if (auto Inherited = CD->getInheritedConstructor())926FD = Inherited.getConstructor();927928// Whether the mangling of a function type includes the return type depends on929// the context and the nature of the function. The rules for deciding whether930// the return type is included are:931//932// 1. Template functions (names or types) have return types encoded, with933// the exceptions listed below.934// 2. Function types not appearing as part of a function name mangling,935// e.g. parameters, pointer types, etc., have return type encoded, with the936// exceptions listed below.937// 3. Non-template function names do not have return types encoded.938//939// The exceptions mentioned in (1) and (2) above, for which the return type is940// never included, are941// 1. Constructors.942// 2. Destructors.943// 3. Conversion operator functions, e.g. operator int.944bool MangleReturnType = false;945if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {946if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||947isa<CXXConversionDecl>(FD)))948MangleReturnType = true;949950// Mangle the type of the primary template.951FD = PrimaryTemplate->getTemplatedDecl();952}953954mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),955MangleReturnType, FD);956}957958/// Return whether a given namespace is the 'std' namespace.959bool CXXNameMangler::isStd(const NamespaceDecl *NS) {960if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())961return false;962963const IdentifierInfo *II = NS->getFirstDecl()->getIdentifier();964return II && II->isStr("std");965}966967// isStdNamespace - Return whether a given decl context is a toplevel 'std'968// namespace.969bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {970if (!DC->isNamespace())971return false;972973return isStd(cast<NamespaceDecl>(DC));974}975976static const GlobalDecl977isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {978const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());979// Check if we have a function template.980if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {981if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {982TemplateArgs = FD->getTemplateSpecializationArgs();983return GD.getWithDecl(TD);984}985}986987// Check if we have a class template.988if (const ClassTemplateSpecializationDecl *Spec =989dyn_cast<ClassTemplateSpecializationDecl>(ND)) {990TemplateArgs = &Spec->getTemplateArgs();991return GD.getWithDecl(Spec->getSpecializedTemplate());992}993994// Check if we have a variable template.995if (const VarTemplateSpecializationDecl *Spec =996dyn_cast<VarTemplateSpecializationDecl>(ND)) {997TemplateArgs = &Spec->getTemplateArgs();998return GD.getWithDecl(Spec->getSpecializedTemplate());999}10001001return GlobalDecl();1002}10031004static TemplateName asTemplateName(GlobalDecl GD) {1005const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());1006return TemplateName(const_cast<TemplateDecl*>(TD));1007}10081009void CXXNameMangler::mangleName(GlobalDecl GD) {1010const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());1011if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {1012// Variables should have implicit tags from its type.1013AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);1014if (VariableTypeAbiTags.empty()) {1015// Simple case no variable type tags.1016mangleNameWithAbiTags(VD, nullptr);1017return;1018}10191020// Mangle variable name to null stream to collect tags.1021llvm::raw_null_ostream NullOutStream;1022CXXNameMangler VariableNameMangler(*this, NullOutStream);1023VariableNameMangler.disableDerivedAbiTags();1024VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);10251026// Get tags from variable type that are not present in its name.1027const AbiTagList &UsedAbiTags =1028VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();1029AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());1030AdditionalAbiTags.erase(1031std::set_difference(VariableTypeAbiTags.begin(),1032VariableTypeAbiTags.end(), UsedAbiTags.begin(),1033UsedAbiTags.end(), AdditionalAbiTags.begin()),1034AdditionalAbiTags.end());10351036// Output name with implicit tags.1037mangleNameWithAbiTags(VD, &AdditionalAbiTags);1038} else {1039mangleNameWithAbiTags(GD, nullptr);1040}1041}10421043const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {1044const DeclContext *DC = Context.getEffectiveDeclContext(D);1045while (!DC->isNamespace() && !DC->isTranslationUnit()) {1046if (isLocalContainerContext(DC))1047return dyn_cast<RecordDecl>(D);1048D = cast<Decl>(DC);1049DC = Context.getEffectiveDeclContext(D);1050}1051return nullptr;1052}10531054void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,1055const AbiTagList *AdditionalAbiTags) {1056const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());1057// <name> ::= [<module-name>] <nested-name>1058// ::= [<module-name>] <unscoped-name>1059// ::= [<module-name>] <unscoped-template-name> <template-args>1060// ::= <local-name>1061//1062const DeclContext *DC = Context.getEffectiveDeclContext(ND);1063bool IsLambda = isLambda(ND);10641065// If this is an extern variable declared locally, the relevant DeclContext1066// is that of the containing namespace, or the translation unit.1067// FIXME: This is a hack; extern variables declared locally should have1068// a proper semantic declaration context!1069if (isLocalContainerContext(DC) && ND->hasLinkage() && !IsLambda)1070while (!DC->isNamespace() && !DC->isTranslationUnit())1071DC = Context.getEffectiveParentContext(DC);1072else if (GetLocalClassDecl(ND) &&1073(!IsLambda || isCompatibleWith(LangOptions::ClangABI::Ver18))) {1074mangleLocalName(GD, AdditionalAbiTags);1075return;1076}10771078assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");10791080// Closures can require a nested-name mangling even if they're semantically1081// in the global namespace.1082if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {1083mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);1084return;1085}10861087if (isLocalContainerContext(DC)) {1088mangleLocalName(GD, AdditionalAbiTags);1089return;1090}10911092if (DC->isTranslationUnit() || isStdNamespace(DC)) {1093// Check if we have a template.1094const TemplateArgumentList *TemplateArgs = nullptr;1095if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {1096mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);1097mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);1098return;1099}11001101mangleUnscopedName(GD, DC, AdditionalAbiTags);1102return;1103}11041105mangleNestedName(GD, DC, AdditionalAbiTags);1106}11071108void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {1109if (ND->isExternallyVisible())1110if (Module *M = ND->getOwningModuleForLinkage())1111mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());1112}11131114// <module-name> ::= <module-subname>1115// ::= <module-name> <module-subname>1116// ::= <substitution>1117// <module-subname> ::= W <source-name>1118// ::= W P <source-name>1119void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {1120// <substitution> ::= S <seq-id> _1121auto It = ModuleSubstitutions.find(Name);1122if (It != ModuleSubstitutions.end()) {1123Out << 'S';1124mangleSeqID(It->second);1125return;1126}11271128// FIXME: Preserve hierarchy in module names rather than flattening1129// them to strings; use Module*s as substitution keys.1130auto Parts = Name.rsplit('.');1131if (Parts.second.empty())1132Parts.second = Parts.first;1133else {1134mangleModuleNamePrefix(Parts.first, IsPartition);1135IsPartition = false;1136}11371138Out << 'W';1139if (IsPartition)1140Out << 'P';1141Out << Parts.second.size() << Parts.second;1142ModuleSubstitutions.insert({Name, SeqID++});1143}11441145void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,1146ArrayRef<TemplateArgument> Args) {1147const DeclContext *DC = Context.getEffectiveDeclContext(TD);11481149if (DC->isTranslationUnit() || isStdNamespace(DC)) {1150mangleUnscopedTemplateName(TD, DC, nullptr);1151mangleTemplateArgs(asTemplateName(TD), Args);1152} else {1153mangleNestedName(TD, Args);1154}1155}11561157void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,1158const AbiTagList *AdditionalAbiTags) {1159// <unscoped-name> ::= <unqualified-name>1160// ::= St <unqualified-name> # ::std::11611162assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");1163if (isStdNamespace(DC))1164Out << "St";11651166mangleUnqualifiedName(GD, DC, AdditionalAbiTags);1167}11681169void CXXNameMangler::mangleUnscopedTemplateName(1170GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {1171const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());1172// <unscoped-template-name> ::= <unscoped-name>1173// ::= <substitution>1174if (mangleSubstitution(ND))1175return;11761177// <template-template-param> ::= <template-param>1178if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {1179assert(!AdditionalAbiTags &&1180"template template param cannot have abi tags");1181mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());1182} else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {1183mangleUnscopedName(GD, DC, AdditionalAbiTags);1184} else {1185mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,1186AdditionalAbiTags);1187}11881189addSubstitution(ND);1190}11911192void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {1193// ABI:1194// Floating-point literals are encoded using a fixed-length1195// lowercase hexadecimal string corresponding to the internal1196// representation (IEEE on Itanium), high-order bytes first,1197// without leading zeroes. For example: "Lf bf800000 E" is -1.0f1198// on Itanium.1199// The 'without leading zeroes' thing seems to be an editorial1200// mistake; see the discussion on cxx-abi-dev beginning on1201// 2012-01-16.12021203// Our requirements here are just barely weird enough to justify1204// using a custom algorithm instead of post-processing APInt::toString().12051206llvm::APInt valueBits = f.bitcastToAPInt();1207unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;1208assert(numCharacters != 0);12091210// Allocate a buffer of the right number of characters.1211SmallVector<char, 20> buffer(numCharacters);12121213// Fill the buffer left-to-right.1214for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {1215// The bit-index of the next hex digit.1216unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);12171218// Project out 4 bits starting at 'digitIndex'.1219uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];1220hexDigit >>= (digitBitIndex % 64);1221hexDigit &= 0xF;12221223// Map that over to a lowercase hex digit.1224static const char charForHex[16] = {1225'0', '1', '2', '3', '4', '5', '6', '7',1226'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'1227};1228buffer[stringIndex] = charForHex[hexDigit];1229}12301231Out.write(buffer.data(), numCharacters);1232}12331234void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {1235Out << 'L';1236mangleType(T);1237mangleFloat(V);1238Out << 'E';1239}12401241void CXXNameMangler::mangleFixedPointLiteral() {1242DiagnosticsEngine &Diags = Context.getDiags();1243unsigned DiagID = Diags.getCustomDiagID(1244DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");1245Diags.Report(DiagID);1246}12471248void CXXNameMangler::mangleNullPointer(QualType T) {1249// <expr-primary> ::= L <type> 0 E1250Out << 'L';1251mangleType(T);1252Out << "0E";1253}12541255void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {1256if (Value.isSigned() && Value.isNegative()) {1257Out << 'n';1258Value.abs().print(Out, /*signed*/ false);1259} else {1260Value.print(Out, /*signed*/ false);1261}1262}12631264void CXXNameMangler::mangleNumber(int64_t Number) {1265// <number> ::= [n] <non-negative decimal integer>1266if (Number < 0) {1267Out << 'n';1268Number = -Number;1269}12701271Out << Number;1272}12731274void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {1275// <call-offset> ::= h <nv-offset> _1276// ::= v <v-offset> _1277// <nv-offset> ::= <offset number> # non-virtual base override1278// <v-offset> ::= <offset number> _ <virtual offset number>1279// # virtual base override, with vcall offset1280if (!Virtual) {1281Out << 'h';1282mangleNumber(NonVirtual);1283Out << '_';1284return;1285}12861287Out << 'v';1288mangleNumber(NonVirtual);1289Out << '_';1290mangleNumber(Virtual);1291Out << '_';1292}12931294void CXXNameMangler::manglePrefix(QualType type) {1295if (const auto *TST = type->getAs<TemplateSpecializationType>()) {1296if (!mangleSubstitution(QualType(TST, 0))) {1297mangleTemplatePrefix(TST->getTemplateName());12981299// FIXME: GCC does not appear to mangle the template arguments when1300// the template in question is a dependent template name. Should we1301// emulate that badness?1302mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());1303addSubstitution(QualType(TST, 0));1304}1305} else if (const auto *DTST =1306type->getAs<DependentTemplateSpecializationType>()) {1307if (!mangleSubstitution(QualType(DTST, 0))) {1308TemplateName Template = getASTContext().getDependentTemplateName(1309DTST->getQualifier(), DTST->getIdentifier());1310mangleTemplatePrefix(Template);13111312// FIXME: GCC does not appear to mangle the template arguments when1313// the template in question is a dependent template name. Should we1314// emulate that badness?1315mangleTemplateArgs(Template, DTST->template_arguments());1316addSubstitution(QualType(DTST, 0));1317}1318} else {1319// We use the QualType mangle type variant here because it handles1320// substitutions.1321mangleType(type);1322}1323}13241325/// Mangle everything prior to the base-unresolved-name in an unresolved-name.1326///1327/// \param recursive - true if this is being called recursively,1328/// i.e. if there is more prefix "to the right".1329void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,1330bool recursive) {13311332// x, ::x1333// <unresolved-name> ::= [gs] <base-unresolved-name>13341335// T::x / decltype(p)::x1336// <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>13371338// T::N::x /decltype(p)::N::x1339// <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E1340// <base-unresolved-name>13411342// A::x, N::y, A<T>::z; "gs" means leading "::"1343// <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E1344// <base-unresolved-name>13451346switch (qualifier->getKind()) {1347case NestedNameSpecifier::Global:1348Out << "gs";13491350// We want an 'sr' unless this is the entire NNS.1351if (recursive)1352Out << "sr";13531354// We never want an 'E' here.1355return;13561357case NestedNameSpecifier::Super:1358llvm_unreachable("Can't mangle __super specifier");13591360case NestedNameSpecifier::Namespace:1361if (qualifier->getPrefix())1362mangleUnresolvedPrefix(qualifier->getPrefix(),1363/*recursive*/ true);1364else1365Out << "sr";1366mangleSourceNameWithAbiTags(qualifier->getAsNamespace());1367break;1368case NestedNameSpecifier::NamespaceAlias:1369if (qualifier->getPrefix())1370mangleUnresolvedPrefix(qualifier->getPrefix(),1371/*recursive*/ true);1372else1373Out << "sr";1374mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());1375break;13761377case NestedNameSpecifier::TypeSpec:1378case NestedNameSpecifier::TypeSpecWithTemplate: {1379const Type *type = qualifier->getAsType();13801381// We only want to use an unresolved-type encoding if this is one of:1382// - a decltype1383// - a template type parameter1384// - a template template parameter with arguments1385// In all of these cases, we should have no prefix.1386if (qualifier->getPrefix()) {1387mangleUnresolvedPrefix(qualifier->getPrefix(),1388/*recursive*/ true);1389} else {1390// Otherwise, all the cases want this.1391Out << "sr";1392}13931394if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))1395return;13961397break;1398}13991400case NestedNameSpecifier::Identifier:1401// Member expressions can have these without prefixes.1402if (qualifier->getPrefix())1403mangleUnresolvedPrefix(qualifier->getPrefix(),1404/*recursive*/ true);1405else1406Out << "sr";14071408mangleSourceName(qualifier->getAsIdentifier());1409// An Identifier has no type information, so we can't emit abi tags for it.1410break;1411}14121413// If this was the innermost part of the NNS, and we fell out to1414// here, append an 'E'.1415if (!recursive)1416Out << 'E';1417}14181419/// Mangle an unresolved-name, which is generally used for names which1420/// weren't resolved to specific entities.1421void CXXNameMangler::mangleUnresolvedName(1422NestedNameSpecifier *qualifier, DeclarationName name,1423const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,1424unsigned knownArity) {1425if (qualifier) mangleUnresolvedPrefix(qualifier);1426switch (name.getNameKind()) {1427// <base-unresolved-name> ::= <simple-id>1428case DeclarationName::Identifier:1429mangleSourceName(name.getAsIdentifierInfo());1430break;1431// <base-unresolved-name> ::= dn <destructor-name>1432case DeclarationName::CXXDestructorName:1433Out << "dn";1434mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());1435break;1436// <base-unresolved-name> ::= on <operator-name>1437case DeclarationName::CXXConversionFunctionName:1438case DeclarationName::CXXLiteralOperatorName:1439case DeclarationName::CXXOperatorName:1440Out << "on";1441mangleOperatorName(name, knownArity);1442break;1443case DeclarationName::CXXConstructorName:1444llvm_unreachable("Can't mangle a constructor name!");1445case DeclarationName::CXXUsingDirective:1446llvm_unreachable("Can't mangle a using directive name!");1447case DeclarationName::CXXDeductionGuideName:1448llvm_unreachable("Can't mangle a deduction guide name!");1449case DeclarationName::ObjCMultiArgSelector:1450case DeclarationName::ObjCOneArgSelector:1451case DeclarationName::ObjCZeroArgSelector:1452llvm_unreachable("Can't mangle Objective-C selector names here!");1453}14541455// The <simple-id> and on <operator-name> productions end in an optional1456// <template-args>.1457if (TemplateArgs)1458mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);1459}14601461void CXXNameMangler::mangleUnqualifiedName(1462GlobalDecl GD, DeclarationName Name, const DeclContext *DC,1463unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {1464const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());1465// <unqualified-name> ::= [<module-name>] [F] <operator-name>1466// ::= <ctor-dtor-name>1467// ::= [<module-name>] [F] <source-name>1468// ::= [<module-name>] DC <source-name>* E14691470if (ND && DC && DC->isFileContext())1471mangleModuleName(ND);14721473// A member-like constrained friend is mangled with a leading 'F'.1474// Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.1475auto *FD = dyn_cast<FunctionDecl>(ND);1476auto *FTD = dyn_cast<FunctionTemplateDecl>(ND);1477if ((FD && FD->isMemberLikeConstrainedFriend()) ||1478(FTD && FTD->getTemplatedDecl()->isMemberLikeConstrainedFriend())) {1479if (!isCompatibleWith(LangOptions::ClangABI::Ver17))1480Out << 'F';1481}14821483unsigned Arity = KnownArity;1484switch (Name.getNameKind()) {1485case DeclarationName::Identifier: {1486const IdentifierInfo *II = Name.getAsIdentifierInfo();14871488// We mangle decomposition declarations as the names of their bindings.1489if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {1490// FIXME: Non-standard mangling for decomposition declarations:1491//1492// <unqualified-name> ::= DC <source-name>* E1493//1494// Proposed on cxx-abi-dev on 2016-08-121495Out << "DC";1496for (auto *BD : DD->bindings())1497mangleSourceName(BD->getDeclName().getAsIdentifierInfo());1498Out << 'E';1499writeAbiTags(ND, AdditionalAbiTags);1500break;1501}15021503if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {1504// We follow MSVC in mangling GUID declarations as if they were variables1505// with a particular reserved name. Continue the pretense here.1506SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;1507llvm::raw_svector_ostream GUIDOS(GUID);1508Context.mangleMSGuidDecl(GD, GUIDOS);1509Out << GUID.size() << GUID;1510break;1511}15121513if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {1514// Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.1515Out << "TA";1516mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),1517TPO->getValue(), /*TopLevel=*/true);1518break;1519}15201521if (II) {1522// Match GCC's naming convention for internal linkage symbols, for1523// symbols that are not actually visible outside of this TU. GCC1524// distinguishes between internal and external linkage symbols in1525// its mangling, to support cases like this that were valid C++ prior1526// to DR426:1527//1528// void test() { extern void foo(); }1529// static void foo();1530//1531// Don't bother with the L marker for names in anonymous namespaces; the1532// 12_GLOBAL__N_1 mangling is quite sufficient there, and this better1533// matches GCC anyway, because GCC does not treat anonymous namespaces as1534// implying internal linkage.1535if (Context.isInternalLinkageDecl(ND))1536Out << 'L';15371538bool IsRegCall = FD &&1539FD->getType()->castAs<FunctionType>()->getCallConv() ==1540clang::CC_X86RegCall;1541bool IsDeviceStub =1542FD && FD->hasAttr<CUDAGlobalAttr>() &&1543GD.getKernelReferenceKind() == KernelReferenceKind::Stub;1544if (IsDeviceStub)1545mangleDeviceStubName(II);1546else if (IsRegCall)1547mangleRegCallName(II);1548else1549mangleSourceName(II);15501551writeAbiTags(ND, AdditionalAbiTags);1552break;1553}15541555// Otherwise, an anonymous entity. We must have a declaration.1556assert(ND && "mangling empty name without declaration");15571558if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {1559if (NS->isAnonymousNamespace()) {1560// This is how gcc mangles these names.1561Out << "12_GLOBAL__N_1";1562break;1563}1564}15651566if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {1567// We must have an anonymous union or struct declaration.1568const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();15691570// Itanium C++ ABI 5.1.2:1571//1572// For the purposes of mangling, the name of an anonymous union is1573// considered to be the name of the first named data member found by a1574// pre-order, depth-first, declaration-order walk of the data members of1575// the anonymous union. If there is no such data member (i.e., if all of1576// the data members in the union are unnamed), then there is no way for1577// a program to refer to the anonymous union, and there is therefore no1578// need to mangle its name.1579assert(RD->isAnonymousStructOrUnion()1580&& "Expected anonymous struct or union!");1581const FieldDecl *FD = RD->findFirstNamedDataMember();15821583// It's actually possible for various reasons for us to get here1584// with an empty anonymous struct / union. Fortunately, it1585// doesn't really matter what name we generate.1586if (!FD) break;1587assert(FD->getIdentifier() && "Data member name isn't an identifier!");15881589mangleSourceName(FD->getIdentifier());1590// Not emitting abi tags: internal name anyway.1591break;1592}15931594// Class extensions have no name as a category, and it's possible1595// for them to be the semantic parent of certain declarations1596// (primarily, tag decls defined within declarations). Such1597// declarations will always have internal linkage, so the name1598// doesn't really matter, but we shouldn't crash on them. For1599// safety, just handle all ObjC containers here.1600if (isa<ObjCContainerDecl>(ND))1601break;16021603// We must have an anonymous struct.1604const TagDecl *TD = cast<TagDecl>(ND);1605if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {1606assert(TD->getDeclContext() == D->getDeclContext() &&1607"Typedef should not be in another decl context!");1608assert(D->getDeclName().getAsIdentifierInfo() &&1609"Typedef was not named!");1610mangleSourceName(D->getDeclName().getAsIdentifierInfo());1611assert(!AdditionalAbiTags && "Type cannot have additional abi tags");1612// Explicit abi tags are still possible; take from underlying type, not1613// from typedef.1614writeAbiTags(TD, nullptr);1615break;1616}16171618// <unnamed-type-name> ::= <closure-type-name>1619//1620// <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _1621// <lambda-sig> ::= <template-param-decl>* <parameter-type>+1622// # Parameter types or 'v' for 'void'.1623if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {1624std::optional<unsigned> DeviceNumber =1625Context.getDiscriminatorOverride()(Context.getASTContext(), Record);16261627// If we have a device-number via the discriminator, use that to mangle1628// the lambda, otherwise use the typical lambda-mangling-number. In either1629// case, a '0' should be mangled as a normal unnamed class instead of as a1630// lambda.1631if (Record->isLambda() &&1632((DeviceNumber && *DeviceNumber > 0) ||1633(!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {1634assert(!AdditionalAbiTags &&1635"Lambda type cannot have additional abi tags");1636mangleLambda(Record);1637break;1638}1639}16401641if (TD->isExternallyVisible()) {1642unsigned UnnamedMangle =1643getASTContext().getManglingNumber(TD, Context.isAux());1644Out << "Ut";1645if (UnnamedMangle > 1)1646Out << UnnamedMangle - 2;1647Out << '_';1648writeAbiTags(TD, AdditionalAbiTags);1649break;1650}16511652// Get a unique id for the anonymous struct. If it is not a real output1653// ID doesn't matter so use fake one.1654unsigned AnonStructId =1655NullOut ? 01656: Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));16571658// Mangle it as a source name in the form1659// [n] $_<id>1660// where n is the length of the string.1661SmallString<8> Str;1662Str += "$_";1663Str += llvm::utostr(AnonStructId);16641665Out << Str.size();1666Out << Str;1667break;1668}16691670case DeclarationName::ObjCZeroArgSelector:1671case DeclarationName::ObjCOneArgSelector:1672case DeclarationName::ObjCMultiArgSelector:1673llvm_unreachable("Can't mangle Objective-C selector names here!");16741675case DeclarationName::CXXConstructorName: {1676const CXXRecordDecl *InheritedFrom = nullptr;1677TemplateName InheritedTemplateName;1678const TemplateArgumentList *InheritedTemplateArgs = nullptr;1679if (auto Inherited =1680cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {1681InheritedFrom = Inherited.getConstructor()->getParent();1682InheritedTemplateName =1683TemplateName(Inherited.getConstructor()->getPrimaryTemplate());1684InheritedTemplateArgs =1685Inherited.getConstructor()->getTemplateSpecializationArgs();1686}16871688if (ND == Structor)1689// If the named decl is the C++ constructor we're mangling, use the type1690// we were given.1691mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);1692else1693// Otherwise, use the complete constructor name. This is relevant if a1694// class with a constructor is declared within a constructor.1695mangleCXXCtorType(Ctor_Complete, InheritedFrom);16961697// FIXME: The template arguments are part of the enclosing prefix or1698// nested-name, but it's more convenient to mangle them here.1699if (InheritedTemplateArgs)1700mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);17011702writeAbiTags(ND, AdditionalAbiTags);1703break;1704}17051706case DeclarationName::CXXDestructorName:1707if (ND == Structor)1708// If the named decl is the C++ destructor we're mangling, use the type we1709// were given.1710mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));1711else1712// Otherwise, use the complete destructor name. This is relevant if a1713// class with a destructor is declared within a destructor.1714mangleCXXDtorType(Dtor_Complete);1715assert(ND);1716writeAbiTags(ND, AdditionalAbiTags);1717break;17181719case DeclarationName::CXXOperatorName:1720if (ND && Arity == UnknownArity) {1721Arity = cast<FunctionDecl>(ND)->getNumParams();17221723// If we have a member function, we need to include the 'this' pointer.1724if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))1725if (MD->isImplicitObjectMemberFunction())1726Arity++;1727}1728[[fallthrough]];1729case DeclarationName::CXXConversionFunctionName:1730case DeclarationName::CXXLiteralOperatorName:1731mangleOperatorName(Name, Arity);1732writeAbiTags(ND, AdditionalAbiTags);1733break;17341735case DeclarationName::CXXDeductionGuideName:1736llvm_unreachable("Can't mangle a deduction guide name!");17371738case DeclarationName::CXXUsingDirective:1739llvm_unreachable("Can't mangle a using directive name!");1740}1741}17421743void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {1744// <source-name> ::= <positive length number> __regcall3__ <identifier>1745// <number> ::= [n] <non-negative decimal integer>1746// <identifier> ::= <unqualified source code identifier>1747if (getASTContext().getLangOpts().RegCall4)1748Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"1749<< II->getName();1750else1751Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"1752<< II->getName();1753}17541755void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {1756// <source-name> ::= <positive length number> __device_stub__ <identifier>1757// <number> ::= [n] <non-negative decimal integer>1758// <identifier> ::= <unqualified source code identifier>1759Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"1760<< II->getName();1761}17621763void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {1764// <source-name> ::= <positive length number> <identifier>1765// <number> ::= [n] <non-negative decimal integer>1766// <identifier> ::= <unqualified source code identifier>1767Out << II->getLength() << II->getName();1768}17691770void CXXNameMangler::mangleNestedName(GlobalDecl GD,1771const DeclContext *DC,1772const AbiTagList *AdditionalAbiTags,1773bool NoFunction) {1774const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());1775// <nested-name>1776// ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E1777// ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>1778// <template-args> E17791780Out << 'N';1781if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {1782Qualifiers MethodQuals = Method->getMethodQualifiers();1783// We do not consider restrict a distinguishing attribute for overloading1784// purposes so we must not mangle it.1785if (Method->isExplicitObjectMemberFunction())1786Out << 'H';1787MethodQuals.removeRestrict();1788mangleQualifiers(MethodQuals);1789mangleRefQualifier(Method->getRefQualifier());1790}17911792// Check if we have a template.1793const TemplateArgumentList *TemplateArgs = nullptr;1794if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {1795mangleTemplatePrefix(TD, NoFunction);1796mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);1797} else {1798manglePrefix(DC, NoFunction);1799mangleUnqualifiedName(GD, DC, AdditionalAbiTags);1800}18011802Out << 'E';1803}1804void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,1805ArrayRef<TemplateArgument> Args) {1806// <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E18071808Out << 'N';18091810mangleTemplatePrefix(TD);1811mangleTemplateArgs(asTemplateName(TD), Args);18121813Out << 'E';1814}18151816void CXXNameMangler::mangleNestedNameWithClosurePrefix(1817GlobalDecl GD, const NamedDecl *PrefixND,1818const AbiTagList *AdditionalAbiTags) {1819// A <closure-prefix> represents a variable or field, not a regular1820// DeclContext, so needs special handling. In this case we're mangling a1821// limited form of <nested-name>:1822//1823// <nested-name> ::= N <closure-prefix> <closure-type-name> E18241825Out << 'N';18261827mangleClosurePrefix(PrefixND);1828mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);18291830Out << 'E';1831}18321833static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {1834GlobalDecl GD;1835// The Itanium spec says:1836// For entities in constructors and destructors, the mangling of the1837// complete object constructor or destructor is used as the base function1838// name, i.e. the C1 or D1 version.1839if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))1840GD = GlobalDecl(CD, Ctor_Complete);1841else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))1842GD = GlobalDecl(DD, Dtor_Complete);1843else1844GD = GlobalDecl(cast<FunctionDecl>(DC));1845return GD;1846}18471848void CXXNameMangler::mangleLocalName(GlobalDecl GD,1849const AbiTagList *AdditionalAbiTags) {1850const Decl *D = GD.getDecl();1851// <local-name> := Z <function encoding> E <entity name> [<discriminator>]1852// := Z <function encoding> E s [<discriminator>]1853// <local-name> := Z <function encoding> E d [ <parameter number> ]1854// _ <entity name>1855// <discriminator> := _ <non-negative number>1856assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));1857const RecordDecl *RD = GetLocalClassDecl(D);1858const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);18591860Out << 'Z';18611862{1863AbiTagState LocalAbiTags(AbiTags);18641865if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))1866mangleObjCMethodName(MD);1867else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))1868mangleBlockForPrefix(BD);1869else1870mangleFunctionEncoding(getParentOfLocalEntity(DC));18711872// Implicit ABI tags (from namespace) are not available in the following1873// entity; reset to actually emitted tags, which are available.1874LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());1875}18761877Out << 'E';18781879// GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to1880// be a bug that is fixed in trunk.18811882if (RD) {1883// The parameter number is omitted for the last parameter, 0 for the1884// second-to-last parameter, 1 for the third-to-last parameter, etc. The1885// <entity name> will of course contain a <closure-type-name>: Its1886// numbering will be local to the particular argument in which it appears1887// -- other default arguments do not affect its encoding.1888const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);1889if (CXXRD && CXXRD->isLambda()) {1890if (const ParmVarDecl *Parm1891= dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {1892if (const FunctionDecl *Func1893= dyn_cast<FunctionDecl>(Parm->getDeclContext())) {1894Out << 'd';1895unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();1896if (Num > 1)1897mangleNumber(Num - 2);1898Out << '_';1899}1900}1901}19021903// Mangle the name relative to the closest enclosing function.1904// equality ok because RD derived from ND above1905if (D == RD) {1906mangleUnqualifiedName(RD, DC, AdditionalAbiTags);1907} else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {1908if (const NamedDecl *PrefixND = getClosurePrefix(BD))1909mangleClosurePrefix(PrefixND, true /*NoFunction*/);1910else1911manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);1912assert(!AdditionalAbiTags && "Block cannot have additional abi tags");1913mangleUnqualifiedBlock(BD);1914} else {1915const NamedDecl *ND = cast<NamedDecl>(D);1916mangleNestedName(GD, Context.getEffectiveDeclContext(ND),1917AdditionalAbiTags, true /*NoFunction*/);1918}1919} else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {1920// Mangle a block in a default parameter; see above explanation for1921// lambdas.1922if (const ParmVarDecl *Parm1923= dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {1924if (const FunctionDecl *Func1925= dyn_cast<FunctionDecl>(Parm->getDeclContext())) {1926Out << 'd';1927unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();1928if (Num > 1)1929mangleNumber(Num - 2);1930Out << '_';1931}1932}19331934assert(!AdditionalAbiTags && "Block cannot have additional abi tags");1935mangleUnqualifiedBlock(BD);1936} else {1937mangleUnqualifiedName(GD, DC, AdditionalAbiTags);1938}19391940if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {1941unsigned disc;1942if (Context.getNextDiscriminator(ND, disc)) {1943if (disc < 10)1944Out << '_' << disc;1945else1946Out << "__" << disc << '_';1947}1948}1949}19501951void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {1952if (GetLocalClassDecl(Block)) {1953mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);1954return;1955}1956const DeclContext *DC = Context.getEffectiveDeclContext(Block);1957if (isLocalContainerContext(DC)) {1958mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);1959return;1960}1961if (const NamedDecl *PrefixND = getClosurePrefix(Block))1962mangleClosurePrefix(PrefixND);1963else1964manglePrefix(DC);1965mangleUnqualifiedBlock(Block);1966}19671968void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {1969// When trying to be ABI-compatibility with clang 12 and before, mangle a1970// <data-member-prefix> now, with no substitutions and no <template-args>.1971if (Decl *Context = Block->getBlockManglingContextDecl()) {1972if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&1973(isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&1974Context->getDeclContext()->isRecord()) {1975const auto *ND = cast<NamedDecl>(Context);1976if (ND->getIdentifier()) {1977mangleSourceNameWithAbiTags(ND);1978Out << 'M';1979}1980}1981}19821983// If we have a block mangling number, use it.1984unsigned Number = Block->getBlockManglingNumber();1985// Otherwise, just make up a number. It doesn't matter what it is because1986// the symbol in question isn't externally visible.1987if (!Number)1988Number = Context.getBlockId(Block, false);1989else {1990// Stored mangling numbers are 1-based.1991--Number;1992}1993Out << "Ub";1994if (Number > 0)1995Out << Number - 1;1996Out << '_';1997}19981999// <template-param-decl>2000// ::= Ty # template type parameter2001// ::= Tk <concept name> [<template-args>] # constrained type parameter2002// ::= Tn <type> # template non-type parameter2003// ::= Tt <template-param-decl>* E [Q <requires-clause expr>]2004// # template template parameter2005// ::= Tp <template-param-decl> # template parameter pack2006void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {2007// Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.2008if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {2009if (Ty->isParameterPack())2010Out << "Tp";2011const TypeConstraint *Constraint = Ty->getTypeConstraint();2012if (Constraint && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {2013// Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.2014Out << "Tk";2015mangleTypeConstraint(Constraint);2016} else {2017Out << "Ty";2018}2019} else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {2020if (Tn->isExpandedParameterPack()) {2021for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {2022Out << "Tn";2023mangleType(Tn->getExpansionType(I));2024}2025} else {2026QualType T = Tn->getType();2027if (Tn->isParameterPack()) {2028Out << "Tp";2029if (auto *PackExpansion = T->getAs<PackExpansionType>())2030T = PackExpansion->getPattern();2031}2032Out << "Tn";2033mangleType(T);2034}2035} else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {2036if (Tt->isExpandedParameterPack()) {2037for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;2038++I)2039mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I));2040} else {2041if (Tt->isParameterPack())2042Out << "Tp";2043mangleTemplateParameterList(Tt->getTemplateParameters());2044}2045}2046}20472048void CXXNameMangler::mangleTemplateParameterList(2049const TemplateParameterList *Params) {2050Out << "Tt";2051for (auto *Param : *Params)2052mangleTemplateParamDecl(Param);2053mangleRequiresClause(Params->getRequiresClause());2054Out << "E";2055}20562057void CXXNameMangler::mangleTypeConstraint(2058const ConceptDecl *Concept, ArrayRef<TemplateArgument> Arguments) {2059const DeclContext *DC = Context.getEffectiveDeclContext(Concept);2060if (!Arguments.empty())2061mangleTemplateName(Concept, Arguments);2062else if (DC->isTranslationUnit() || isStdNamespace(DC))2063mangleUnscopedName(Concept, DC, nullptr);2064else2065mangleNestedName(Concept, DC, nullptr);2066}20672068void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) {2069llvm::SmallVector<TemplateArgument, 8> Args;2070if (Constraint->getTemplateArgsAsWritten()) {2071for (const TemplateArgumentLoc &ArgLoc :2072Constraint->getTemplateArgsAsWritten()->arguments())2073Args.push_back(ArgLoc.getArgument());2074}2075return mangleTypeConstraint(Constraint->getNamedConcept(), Args);2076}20772078void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) {2079// Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.2080if (RequiresClause && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {2081Out << 'Q';2082mangleExpression(RequiresClause);2083}2084}20852086void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {2087// When trying to be ABI-compatibility with clang 12 and before, mangle a2088// <data-member-prefix> now, with no substitutions.2089if (Decl *Context = Lambda->getLambdaContextDecl()) {2090if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&2091(isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&2092!isa<ParmVarDecl>(Context)) {2093if (const IdentifierInfo *Name2094= cast<NamedDecl>(Context)->getIdentifier()) {2095mangleSourceName(Name);2096const TemplateArgumentList *TemplateArgs = nullptr;2097if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))2098mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);2099Out << 'M';2100}2101}2102}21032104Out << "Ul";2105mangleLambdaSig(Lambda);2106Out << "E";21072108// The number is omitted for the first closure type with a given2109// <lambda-sig> in a given context; it is n-2 for the nth closure type2110// (in lexical order) with that same <lambda-sig> and context.2111//2112// The AST keeps track of the number for us.2113//2114// In CUDA/HIP, to ensure the consistent lamba numbering between the device-2115// and host-side compilations, an extra device mangle context may be created2116// if the host-side CXX ABI has different numbering for lambda. In such case,2117// if the mangle context is that device-side one, use the device-side lambda2118// mangling number for this lambda.2119std::optional<unsigned> DeviceNumber =2120Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);2121unsigned Number =2122DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();21232124assert(Number > 0 && "Lambda should be mangled as an unnamed class");2125if (Number > 1)2126mangleNumber(Number - 2);2127Out << '_';2128}21292130void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {2131// Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.2132for (auto *D : Lambda->getLambdaExplicitTemplateParameters())2133mangleTemplateParamDecl(D);21342135// Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.2136if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList())2137mangleRequiresClause(TPL->getRequiresClause());21382139auto *Proto =2140Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();2141mangleBareFunctionType(Proto, /*MangleReturnType=*/false,2142Lambda->getLambdaStaticInvoker());2143}21442145void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {2146switch (qualifier->getKind()) {2147case NestedNameSpecifier::Global:2148// nothing2149return;21502151case NestedNameSpecifier::Super:2152llvm_unreachable("Can't mangle __super specifier");21532154case NestedNameSpecifier::Namespace:2155mangleName(qualifier->getAsNamespace());2156return;21572158case NestedNameSpecifier::NamespaceAlias:2159mangleName(qualifier->getAsNamespaceAlias()->getNamespace());2160return;21612162case NestedNameSpecifier::TypeSpec:2163case NestedNameSpecifier::TypeSpecWithTemplate:2164manglePrefix(QualType(qualifier->getAsType(), 0));2165return;21662167case NestedNameSpecifier::Identifier:2168// Clang 14 and before did not consider this substitutable.2169bool Clang14Compat = isCompatibleWith(LangOptions::ClangABI::Ver14);2170if (!Clang14Compat && mangleSubstitution(qualifier))2171return;21722173// Member expressions can have these without prefixes, but that2174// should end up in mangleUnresolvedPrefix instead.2175assert(qualifier->getPrefix());2176manglePrefix(qualifier->getPrefix());21772178mangleSourceName(qualifier->getAsIdentifier());21792180if (!Clang14Compat)2181addSubstitution(qualifier);2182return;2183}21842185llvm_unreachable("unexpected nested name specifier");2186}21872188void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {2189// <prefix> ::= <prefix> <unqualified-name>2190// ::= <template-prefix> <template-args>2191// ::= <closure-prefix>2192// ::= <template-param>2193// ::= # empty2194// ::= <substitution>21952196assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");21972198if (DC->isTranslationUnit())2199return;22002201if (NoFunction && isLocalContainerContext(DC))2202return;22032204const NamedDecl *ND = cast<NamedDecl>(DC);2205if (mangleSubstitution(ND))2206return;22072208// Check if we have a template-prefix or a closure-prefix.2209const TemplateArgumentList *TemplateArgs = nullptr;2210if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {2211mangleTemplatePrefix(TD);2212mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);2213} else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {2214mangleClosurePrefix(PrefixND, NoFunction);2215mangleUnqualifiedName(ND, nullptr, nullptr);2216} else {2217const DeclContext *DC = Context.getEffectiveDeclContext(ND);2218manglePrefix(DC, NoFunction);2219mangleUnqualifiedName(ND, DC, nullptr);2220}22212222addSubstitution(ND);2223}22242225void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {2226// <template-prefix> ::= <prefix> <template unqualified-name>2227// ::= <template-param>2228// ::= <substitution>2229if (TemplateDecl *TD = Template.getAsTemplateDecl())2230return mangleTemplatePrefix(TD);22312232DependentTemplateName *Dependent = Template.getAsDependentTemplateName();2233assert(Dependent && "unexpected template name kind");22342235// Clang 11 and before mangled the substitution for a dependent template name2236// after already having emitted (a substitution for) the prefix.2237bool Clang11Compat = isCompatibleWith(LangOptions::ClangABI::Ver11);2238if (!Clang11Compat && mangleSubstitution(Template))2239return;22402241if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())2242manglePrefix(Qualifier);22432244if (Clang11Compat && mangleSubstitution(Template))2245return;22462247if (const IdentifierInfo *Id = Dependent->getIdentifier())2248mangleSourceName(Id);2249else2250mangleOperatorName(Dependent->getOperator(), UnknownArity);22512252addSubstitution(Template);2253}22542255void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,2256bool NoFunction) {2257const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());2258// <template-prefix> ::= <prefix> <template unqualified-name>2259// ::= <template-param>2260// ::= <substitution>2261// <template-template-param> ::= <template-param>2262// <substitution>22632264if (mangleSubstitution(ND))2265return;22662267// <template-template-param> ::= <template-param>2268if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {2269mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());2270} else {2271const DeclContext *DC = Context.getEffectiveDeclContext(ND);2272manglePrefix(DC, NoFunction);2273if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))2274mangleUnqualifiedName(GD, DC, nullptr);2275else2276mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,2277nullptr);2278}22792280addSubstitution(ND);2281}22822283const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {2284if (isCompatibleWith(LangOptions::ClangABI::Ver12))2285return nullptr;22862287const NamedDecl *Context = nullptr;2288if (auto *Block = dyn_cast<BlockDecl>(ND)) {2289Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());2290} else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {2291if (RD->isLambda())2292Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());2293}2294if (!Context)2295return nullptr;22962297// Only lambdas within the initializer of a non-local variable or non-static2298// data member get a <closure-prefix>.2299if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||2300isa<FieldDecl>(Context))2301return Context;23022303return nullptr;2304}23052306void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {2307// <closure-prefix> ::= [ <prefix> ] <unqualified-name> M2308// ::= <template-prefix> <template-args> M2309if (mangleSubstitution(ND))2310return;23112312const TemplateArgumentList *TemplateArgs = nullptr;2313if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {2314mangleTemplatePrefix(TD, NoFunction);2315mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);2316} else {2317const auto *DC = Context.getEffectiveDeclContext(ND);2318manglePrefix(DC, NoFunction);2319mangleUnqualifiedName(ND, DC, nullptr);2320}23212322Out << 'M';23232324addSubstitution(ND);2325}23262327/// Mangles a template name under the production <type>. Required for2328/// template template arguments.2329/// <type> ::= <class-enum-type>2330/// ::= <template-param>2331/// ::= <substitution>2332void CXXNameMangler::mangleType(TemplateName TN) {2333if (mangleSubstitution(TN))2334return;23352336TemplateDecl *TD = nullptr;23372338switch (TN.getKind()) {2339case TemplateName::QualifiedTemplate:2340case TemplateName::UsingTemplate:2341case TemplateName::Template:2342TD = TN.getAsTemplateDecl();2343goto HaveDecl;23442345HaveDecl:2346if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))2347mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());2348else2349mangleName(TD);2350break;23512352case TemplateName::OverloadedTemplate:2353case TemplateName::AssumedTemplate:2354llvm_unreachable("can't mangle an overloaded template name as a <type>");23552356case TemplateName::DependentTemplate: {2357const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();2358assert(Dependent->isIdentifier());23592360// <class-enum-type> ::= <name>2361// <name> ::= <nested-name>2362mangleUnresolvedPrefix(Dependent->getQualifier());2363mangleSourceName(Dependent->getIdentifier());2364break;2365}23662367case TemplateName::SubstTemplateTemplateParm: {2368// Substituted template parameters are mangled as the substituted2369// template. This will check for the substitution twice, which is2370// fine, but we have to return early so that we don't try to *add*2371// the substitution twice.2372SubstTemplateTemplateParmStorage *subst2373= TN.getAsSubstTemplateTemplateParm();2374mangleType(subst->getReplacement());2375return;2376}23772378case TemplateName::SubstTemplateTemplateParmPack: {2379// FIXME: not clear how to mangle this!2380// template <template <class> class T...> class A {2381// template <template <class> class U...> void foo(B<T,U> x...);2382// };2383Out << "_SUBSTPACK_";2384break;2385}2386}23872388addSubstitution(TN);2389}23902391bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,2392StringRef Prefix) {2393// Only certain other types are valid as prefixes; enumerate them.2394switch (Ty->getTypeClass()) {2395case Type::Builtin:2396case Type::Complex:2397case Type::Adjusted:2398case Type::Decayed:2399case Type::ArrayParameter:2400case Type::Pointer:2401case Type::BlockPointer:2402case Type::LValueReference:2403case Type::RValueReference:2404case Type::MemberPointer:2405case Type::ConstantArray:2406case Type::IncompleteArray:2407case Type::VariableArray:2408case Type::DependentSizedArray:2409case Type::DependentAddressSpace:2410case Type::DependentVector:2411case Type::DependentSizedExtVector:2412case Type::Vector:2413case Type::ExtVector:2414case Type::ConstantMatrix:2415case Type::DependentSizedMatrix:2416case Type::FunctionProto:2417case Type::FunctionNoProto:2418case Type::Paren:2419case Type::Attributed:2420case Type::BTFTagAttributed:2421case Type::Auto:2422case Type::DeducedTemplateSpecialization:2423case Type::PackExpansion:2424case Type::ObjCObject:2425case Type::ObjCInterface:2426case Type::ObjCObjectPointer:2427case Type::ObjCTypeParam:2428case Type::Atomic:2429case Type::Pipe:2430case Type::MacroQualified:2431case Type::BitInt:2432case Type::DependentBitInt:2433case Type::CountAttributed:2434llvm_unreachable("type is illegal as a nested name specifier");24352436case Type::SubstTemplateTypeParmPack:2437// FIXME: not clear how to mangle this!2438// template <class T...> class A {2439// template <class U...> void foo(decltype(T::foo(U())) x...);2440// };2441Out << "_SUBSTPACK_";2442break;24432444// <unresolved-type> ::= <template-param>2445// ::= <decltype>2446// ::= <template-template-param> <template-args>2447// (this last is not official yet)2448case Type::TypeOfExpr:2449case Type::TypeOf:2450case Type::Decltype:2451case Type::PackIndexing:2452case Type::TemplateTypeParm:2453case Type::UnaryTransform:2454case Type::SubstTemplateTypeParm:2455unresolvedType:2456// Some callers want a prefix before the mangled type.2457Out << Prefix;24582459// This seems to do everything we want. It's not really2460// sanctioned for a substituted template parameter, though.2461mangleType(Ty);24622463// We never want to print 'E' directly after an unresolved-type,2464// so we return directly.2465return true;24662467case Type::Typedef:2468mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());2469break;24702471case Type::UnresolvedUsing:2472mangleSourceNameWithAbiTags(2473cast<UnresolvedUsingType>(Ty)->getDecl());2474break;24752476case Type::Enum:2477case Type::Record:2478mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());2479break;24802481case Type::TemplateSpecialization: {2482const TemplateSpecializationType *TST =2483cast<TemplateSpecializationType>(Ty);2484TemplateName TN = TST->getTemplateName();2485switch (TN.getKind()) {2486case TemplateName::Template:2487case TemplateName::QualifiedTemplate: {2488TemplateDecl *TD = TN.getAsTemplateDecl();24892490// If the base is a template template parameter, this is an2491// unresolved type.2492assert(TD && "no template for template specialization type");2493if (isa<TemplateTemplateParmDecl>(TD))2494goto unresolvedType;24952496mangleSourceNameWithAbiTags(TD);2497break;2498}24992500case TemplateName::OverloadedTemplate:2501case TemplateName::AssumedTemplate:2502case TemplateName::DependentTemplate:2503llvm_unreachable("invalid base for a template specialization type");25042505case TemplateName::SubstTemplateTemplateParm: {2506SubstTemplateTemplateParmStorage *subst =2507TN.getAsSubstTemplateTemplateParm();2508mangleExistingSubstitution(subst->getReplacement());2509break;2510}25112512case TemplateName::SubstTemplateTemplateParmPack: {2513// FIXME: not clear how to mangle this!2514// template <template <class U> class T...> class A {2515// template <class U...> void foo(decltype(T<U>::foo) x...);2516// };2517Out << "_SUBSTPACK_";2518break;2519}2520case TemplateName::UsingTemplate: {2521TemplateDecl *TD = TN.getAsTemplateDecl();2522assert(TD && !isa<TemplateTemplateParmDecl>(TD));2523mangleSourceNameWithAbiTags(TD);2524break;2525}2526}25272528// Note: we don't pass in the template name here. We are mangling the2529// original source-level template arguments, so we shouldn't consider2530// conversions to the corresponding template parameter.2531// FIXME: Other compilers mangle partially-resolved template arguments in2532// unresolved-qualifier-levels.2533mangleTemplateArgs(TemplateName(), TST->template_arguments());2534break;2535}25362537case Type::InjectedClassName:2538mangleSourceNameWithAbiTags(2539cast<InjectedClassNameType>(Ty)->getDecl());2540break;25412542case Type::DependentName:2543mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());2544break;25452546case Type::DependentTemplateSpecialization: {2547const DependentTemplateSpecializationType *DTST =2548cast<DependentTemplateSpecializationType>(Ty);2549TemplateName Template = getASTContext().getDependentTemplateName(2550DTST->getQualifier(), DTST->getIdentifier());2551mangleSourceName(DTST->getIdentifier());2552mangleTemplateArgs(Template, DTST->template_arguments());2553break;2554}25552556case Type::Using:2557return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),2558Prefix);2559case Type::Elaborated:2560return mangleUnresolvedTypeOrSimpleId(2561cast<ElaboratedType>(Ty)->getNamedType(), Prefix);2562}25632564return false;2565}25662567void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {2568switch (Name.getNameKind()) {2569case DeclarationName::CXXConstructorName:2570case DeclarationName::CXXDestructorName:2571case DeclarationName::CXXDeductionGuideName:2572case DeclarationName::CXXUsingDirective:2573case DeclarationName::Identifier:2574case DeclarationName::ObjCMultiArgSelector:2575case DeclarationName::ObjCOneArgSelector:2576case DeclarationName::ObjCZeroArgSelector:2577llvm_unreachable("Not an operator name");25782579case DeclarationName::CXXConversionFunctionName:2580// <operator-name> ::= cv <type> # (cast)2581Out << "cv";2582mangleType(Name.getCXXNameType());2583break;25842585case DeclarationName::CXXLiteralOperatorName:2586Out << "li";2587mangleSourceName(Name.getCXXLiteralIdentifier());2588return;25892590case DeclarationName::CXXOperatorName:2591mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);2592break;2593}2594}25952596void2597CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {2598switch (OO) {2599// <operator-name> ::= nw # new2600case OO_New: Out << "nw"; break;2601// ::= na # new[]2602case OO_Array_New: Out << "na"; break;2603// ::= dl # delete2604case OO_Delete: Out << "dl"; break;2605// ::= da # delete[]2606case OO_Array_Delete: Out << "da"; break;2607// ::= ps # + (unary)2608// ::= pl # + (binary or unknown)2609case OO_Plus:2610Out << (Arity == 1? "ps" : "pl"); break;2611// ::= ng # - (unary)2612// ::= mi # - (binary or unknown)2613case OO_Minus:2614Out << (Arity == 1? "ng" : "mi"); break;2615// ::= ad # & (unary)2616// ::= an # & (binary or unknown)2617case OO_Amp:2618Out << (Arity == 1? "ad" : "an"); break;2619// ::= de # * (unary)2620// ::= ml # * (binary or unknown)2621case OO_Star:2622// Use binary when unknown.2623Out << (Arity == 1? "de" : "ml"); break;2624// ::= co # ~2625case OO_Tilde: Out << "co"; break;2626// ::= dv # /2627case OO_Slash: Out << "dv"; break;2628// ::= rm # %2629case OO_Percent: Out << "rm"; break;2630// ::= or # |2631case OO_Pipe: Out << "or"; break;2632// ::= eo # ^2633case OO_Caret: Out << "eo"; break;2634// ::= aS # =2635case OO_Equal: Out << "aS"; break;2636// ::= pL # +=2637case OO_PlusEqual: Out << "pL"; break;2638// ::= mI # -=2639case OO_MinusEqual: Out << "mI"; break;2640// ::= mL # *=2641case OO_StarEqual: Out << "mL"; break;2642// ::= dV # /=2643case OO_SlashEqual: Out << "dV"; break;2644// ::= rM # %=2645case OO_PercentEqual: Out << "rM"; break;2646// ::= aN # &=2647case OO_AmpEqual: Out << "aN"; break;2648// ::= oR # |=2649case OO_PipeEqual: Out << "oR"; break;2650// ::= eO # ^=2651case OO_CaretEqual: Out << "eO"; break;2652// ::= ls # <<2653case OO_LessLess: Out << "ls"; break;2654// ::= rs # >>2655case OO_GreaterGreater: Out << "rs"; break;2656// ::= lS # <<=2657case OO_LessLessEqual: Out << "lS"; break;2658// ::= rS # >>=2659case OO_GreaterGreaterEqual: Out << "rS"; break;2660// ::= eq # ==2661case OO_EqualEqual: Out << "eq"; break;2662// ::= ne # !=2663case OO_ExclaimEqual: Out << "ne"; break;2664// ::= lt # <2665case OO_Less: Out << "lt"; break;2666// ::= gt # >2667case OO_Greater: Out << "gt"; break;2668// ::= le # <=2669case OO_LessEqual: Out << "le"; break;2670// ::= ge # >=2671case OO_GreaterEqual: Out << "ge"; break;2672// ::= nt # !2673case OO_Exclaim: Out << "nt"; break;2674// ::= aa # &&2675case OO_AmpAmp: Out << "aa"; break;2676// ::= oo # ||2677case OO_PipePipe: Out << "oo"; break;2678// ::= pp # ++2679case OO_PlusPlus: Out << "pp"; break;2680// ::= mm # --2681case OO_MinusMinus: Out << "mm"; break;2682// ::= cm # ,2683case OO_Comma: Out << "cm"; break;2684// ::= pm # ->*2685case OO_ArrowStar: Out << "pm"; break;2686// ::= pt # ->2687case OO_Arrow: Out << "pt"; break;2688// ::= cl # ()2689case OO_Call: Out << "cl"; break;2690// ::= ix # []2691case OO_Subscript: Out << "ix"; break;26922693// ::= qu # ?2694// The conditional operator can't be overloaded, but we still handle it when2695// mangling expressions.2696case OO_Conditional: Out << "qu"; break;2697// Proposal on cxx-abi-dev, 2015-10-21.2698// ::= aw # co_await2699case OO_Coawait: Out << "aw"; break;2700// Proposed in cxx-abi github issue 43.2701// ::= ss # <=>2702case OO_Spaceship: Out << "ss"; break;27032704case OO_None:2705case NUM_OVERLOADED_OPERATORS:2706llvm_unreachable("Not an overloaded operator");2707}2708}27092710void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {2711// Vendor qualifiers come first and if they are order-insensitive they must2712// be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.27132714// <type> ::= U <addrspace-expr>2715if (DAST) {2716Out << "U2ASI";2717mangleExpression(DAST->getAddrSpaceExpr());2718Out << "E";2719}27202721// Address space qualifiers start with an ordinary letter.2722if (Quals.hasAddressSpace()) {2723// Address space extension:2724//2725// <type> ::= U <target-addrspace>2726// <type> ::= U <OpenCL-addrspace>2727// <type> ::= U <CUDA-addrspace>27282729SmallString<64> ASString;2730LangAS AS = Quals.getAddressSpace();27312732if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {2733// <target-addrspace> ::= "AS" <address-space-number>2734unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);2735if (TargetAS != 0 ||2736Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)2737ASString = "AS" + llvm::utostr(TargetAS);2738} else {2739switch (AS) {2740default: llvm_unreachable("Not a language specific address space");2741// <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |2742// "private"| "generic" | "device" |2743// "host" ]2744case LangAS::opencl_global:2745ASString = "CLglobal";2746break;2747case LangAS::opencl_global_device:2748ASString = "CLdevice";2749break;2750case LangAS::opencl_global_host:2751ASString = "CLhost";2752break;2753case LangAS::opencl_local:2754ASString = "CLlocal";2755break;2756case LangAS::opencl_constant:2757ASString = "CLconstant";2758break;2759case LangAS::opencl_private:2760ASString = "CLprivate";2761break;2762case LangAS::opencl_generic:2763ASString = "CLgeneric";2764break;2765// <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |2766// "device" | "host" ]2767case LangAS::sycl_global:2768ASString = "SYglobal";2769break;2770case LangAS::sycl_global_device:2771ASString = "SYdevice";2772break;2773case LangAS::sycl_global_host:2774ASString = "SYhost";2775break;2776case LangAS::sycl_local:2777ASString = "SYlocal";2778break;2779case LangAS::sycl_private:2780ASString = "SYprivate";2781break;2782// <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]2783case LangAS::cuda_device:2784ASString = "CUdevice";2785break;2786case LangAS::cuda_constant:2787ASString = "CUconstant";2788break;2789case LangAS::cuda_shared:2790ASString = "CUshared";2791break;2792// <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]2793case LangAS::ptr32_sptr:2794ASString = "ptr32_sptr";2795break;2796case LangAS::ptr32_uptr:2797ASString = "ptr32_uptr";2798break;2799case LangAS::ptr64:2800ASString = "ptr64";2801break;2802}2803}2804if (!ASString.empty())2805mangleVendorQualifier(ASString);2806}28072808// The ARC ownership qualifiers start with underscores.2809// Objective-C ARC Extension:2810//2811// <type> ::= U "__strong"2812// <type> ::= U "__weak"2813// <type> ::= U "__autoreleasing"2814//2815// Note: we emit __weak first to preserve the order as2816// required by the Itanium ABI.2817if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)2818mangleVendorQualifier("__weak");28192820// __unaligned (from -fms-extensions)2821if (Quals.hasUnaligned())2822mangleVendorQualifier("__unaligned");28232824// Remaining ARC ownership qualifiers.2825switch (Quals.getObjCLifetime()) {2826case Qualifiers::OCL_None:2827break;28282829case Qualifiers::OCL_Weak:2830// Do nothing as we already handled this case above.2831break;28322833case Qualifiers::OCL_Strong:2834mangleVendorQualifier("__strong");2835break;28362837case Qualifiers::OCL_Autoreleasing:2838mangleVendorQualifier("__autoreleasing");2839break;28402841case Qualifiers::OCL_ExplicitNone:2842// The __unsafe_unretained qualifier is *not* mangled, so that2843// __unsafe_unretained types in ARC produce the same manglings as the2844// equivalent (but, naturally, unqualified) types in non-ARC, providing2845// better ABI compatibility.2846//2847// It's safe to do this because unqualified 'id' won't show up2848// in any type signatures that need to be mangled.2849break;2850}28512852// <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const2853if (Quals.hasRestrict())2854Out << 'r';2855if (Quals.hasVolatile())2856Out << 'V';2857if (Quals.hasConst())2858Out << 'K';2859}28602861void CXXNameMangler::mangleVendorQualifier(StringRef name) {2862Out << 'U' << name.size() << name;2863}28642865void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {2866// <ref-qualifier> ::= R # lvalue reference2867// ::= O # rvalue-reference2868switch (RefQualifier) {2869case RQ_None:2870break;28712872case RQ_LValue:2873Out << 'R';2874break;28752876case RQ_RValue:2877Out << 'O';2878break;2879}2880}28812882void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {2883Context.mangleObjCMethodNameAsSourceName(MD, Out);2884}28852886static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,2887ASTContext &Ctx) {2888if (Quals)2889return true;2890if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))2891return true;2892if (Ty->isOpenCLSpecificType())2893return true;2894// From Clang 18.0 we correctly treat SVE types as substitution candidates.2895if (Ty->isSVESizelessBuiltinType() &&2896Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)2897return true;2898if (Ty->isBuiltinType())2899return false;2900// Through to Clang 6.0, we accidentally treated undeduced auto types as2901// substitution candidates.2902if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&2903isa<AutoType>(Ty))2904return false;2905// A placeholder type for class template deduction is substitutable with2906// its corresponding template name; this is handled specially when mangling2907// the type.2908if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())2909if (DeducedTST->getDeducedType().isNull())2910return false;2911return true;2912}29132914void CXXNameMangler::mangleType(QualType T) {2915// If our type is instantiation-dependent but not dependent, we mangle2916// it as it was written in the source, removing any top-level sugar.2917// Otherwise, use the canonical type.2918//2919// FIXME: This is an approximation of the instantiation-dependent name2920// mangling rules, since we should really be using the type as written and2921// augmented via semantic analysis (i.e., with implicit conversions and2922// default template arguments) for any instantiation-dependent type.2923// Unfortunately, that requires several changes to our AST:2924// - Instantiation-dependent TemplateSpecializationTypes will need to be2925// uniqued, so that we can handle substitutions properly2926// - Default template arguments will need to be represented in the2927// TemplateSpecializationType, since they need to be mangled even though2928// they aren't written.2929// - Conversions on non-type template arguments need to be expressed, since2930// they can affect the mangling of sizeof/alignof.2931//2932// FIXME: This is wrong when mapping to the canonical type for a dependent2933// type discards instantiation-dependent portions of the type, such as for:2934//2935// template<typename T, int N> void f(T (&)[sizeof(N)]);2936// template<typename T> void f(T() throw(typename T::type)); (pre-C++17)2937//2938// It's also wrong in the opposite direction when instantiation-dependent,2939// canonically-equivalent types differ in some irrelevant portion of inner2940// type sugar. In such cases, we fail to form correct substitutions, eg:2941//2942// template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));2943//2944// We should instead canonicalize the non-instantiation-dependent parts,2945// regardless of whether the type as a whole is dependent or instantiation2946// dependent.2947if (!T->isInstantiationDependentType() || T->isDependentType())2948T = T.getCanonicalType();2949else {2950// Desugar any types that are purely sugar.2951do {2952// Don't desugar through template specialization types that aren't2953// type aliases. We need to mangle the template arguments as written.2954if (const TemplateSpecializationType *TST2955= dyn_cast<TemplateSpecializationType>(T))2956if (!TST->isTypeAlias())2957break;29582959// FIXME: We presumably shouldn't strip off ElaboratedTypes with2960// instantation-dependent qualifiers. See2961// https://github.com/itanium-cxx-abi/cxx-abi/issues/114.29622963QualType Desugared2964= T.getSingleStepDesugaredType(Context.getASTContext());2965if (Desugared == T)2966break;29672968T = Desugared;2969} while (true);2970}2971SplitQualType split = T.split();2972Qualifiers quals = split.Quals;2973const Type *ty = split.Ty;29742975bool isSubstitutable =2976isTypeSubstitutable(quals, ty, Context.getASTContext());2977if (isSubstitutable && mangleSubstitution(T))2978return;29792980// If we're mangling a qualified array type, push the qualifiers to2981// the element type.2982if (quals && isa<ArrayType>(T)) {2983ty = Context.getASTContext().getAsArrayType(T);2984quals = Qualifiers();29852986// Note that we don't update T: we want to add the2987// substitution at the original type.2988}29892990if (quals || ty->isDependentAddressSpaceType()) {2991if (const DependentAddressSpaceType *DAST =2992dyn_cast<DependentAddressSpaceType>(ty)) {2993SplitQualType splitDAST = DAST->getPointeeType().split();2994mangleQualifiers(splitDAST.Quals, DAST);2995mangleType(QualType(splitDAST.Ty, 0));2996} else {2997mangleQualifiers(quals);29982999// Recurse: even if the qualified type isn't yet substitutable,3000// the unqualified type might be.3001mangleType(QualType(ty, 0));3002}3003} else {3004switch (ty->getTypeClass()) {3005#define ABSTRACT_TYPE(CLASS, PARENT)3006#define NON_CANONICAL_TYPE(CLASS, PARENT) \3007case Type::CLASS: \3008llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \3009return;3010#define TYPE(CLASS, PARENT) \3011case Type::CLASS: \3012mangleType(static_cast<const CLASS##Type*>(ty)); \3013break;3014#include "clang/AST/TypeNodes.inc"3015}3016}30173018// Add the substitution.3019if (isSubstitutable)3020addSubstitution(T);3021}30223023void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {3024if (!mangleStandardSubstitution(ND))3025mangleName(ND);3026}30273028void CXXNameMangler::mangleType(const BuiltinType *T) {3029// <type> ::= <builtin-type>3030// <builtin-type> ::= v # void3031// ::= w # wchar_t3032// ::= b # bool3033// ::= c # char3034// ::= a # signed char3035// ::= h # unsigned char3036// ::= s # short3037// ::= t # unsigned short3038// ::= i # int3039// ::= j # unsigned int3040// ::= l # long3041// ::= m # unsigned long3042// ::= x # long long, __int643043// ::= y # unsigned long long, __int643044// ::= n # __int1283045// ::= o # unsigned __int1283046// ::= f # float3047// ::= d # double3048// ::= e # long double, __float803049// ::= g # __float1283050// ::= g # __ibm1283051// UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)3052// UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)3053// UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)3054// ::= Dh # IEEE 754r half-precision floating point (16 bits)3055// ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);3056// ::= Di # char32_t3057// ::= Ds # char16_t3058// ::= Dn # std::nullptr_t (i.e., decltype(nullptr))3059// ::= [DS] DA # N1169 fixed-point [_Sat] T _Accum3060// ::= [DS] DR # N1169 fixed-point [_Sat] T _Fract3061// ::= u <source-name> # vendor extended type3062//3063// <fixed-point-size>3064// ::= s # short3065// ::= t # unsigned short3066// ::= i # plain3067// ::= j # unsigned3068// ::= l # long3069// ::= m # unsigned long3070std::string type_name;3071// Normalize integer types as vendor extended types:3072// u<length>i<type size>3073// u<length>u<type size>3074if (NormalizeIntegers && T->isInteger()) {3075if (T->isSignedInteger()) {3076switch (getASTContext().getTypeSize(T)) {3077case 8:3078// Pick a representative for each integer size in the substitution3079// dictionary. (Its actual defined size is not relevant.)3080if (mangleSubstitution(BuiltinType::SChar))3081break;3082Out << "u2i8";3083addSubstitution(BuiltinType::SChar);3084break;3085case 16:3086if (mangleSubstitution(BuiltinType::Short))3087break;3088Out << "u3i16";3089addSubstitution(BuiltinType::Short);3090break;3091case 32:3092if (mangleSubstitution(BuiltinType::Int))3093break;3094Out << "u3i32";3095addSubstitution(BuiltinType::Int);3096break;3097case 64:3098if (mangleSubstitution(BuiltinType::Long))3099break;3100Out << "u3i64";3101addSubstitution(BuiltinType::Long);3102break;3103case 128:3104if (mangleSubstitution(BuiltinType::Int128))3105break;3106Out << "u4i128";3107addSubstitution(BuiltinType::Int128);3108break;3109default:3110llvm_unreachable("Unknown integer size for normalization");3111}3112} else {3113switch (getASTContext().getTypeSize(T)) {3114case 8:3115if (mangleSubstitution(BuiltinType::UChar))3116break;3117Out << "u2u8";3118addSubstitution(BuiltinType::UChar);3119break;3120case 16:3121if (mangleSubstitution(BuiltinType::UShort))3122break;3123Out << "u3u16";3124addSubstitution(BuiltinType::UShort);3125break;3126case 32:3127if (mangleSubstitution(BuiltinType::UInt))3128break;3129Out << "u3u32";3130addSubstitution(BuiltinType::UInt);3131break;3132case 64:3133if (mangleSubstitution(BuiltinType::ULong))3134break;3135Out << "u3u64";3136addSubstitution(BuiltinType::ULong);3137break;3138case 128:3139if (mangleSubstitution(BuiltinType::UInt128))3140break;3141Out << "u4u128";3142addSubstitution(BuiltinType::UInt128);3143break;3144default:3145llvm_unreachable("Unknown integer size for normalization");3146}3147}3148return;3149}3150switch (T->getKind()) {3151case BuiltinType::Void:3152Out << 'v';3153break;3154case BuiltinType::Bool:3155Out << 'b';3156break;3157case BuiltinType::Char_U:3158case BuiltinType::Char_S:3159Out << 'c';3160break;3161case BuiltinType::UChar:3162Out << 'h';3163break;3164case BuiltinType::UShort:3165Out << 't';3166break;3167case BuiltinType::UInt:3168Out << 'j';3169break;3170case BuiltinType::ULong:3171Out << 'm';3172break;3173case BuiltinType::ULongLong:3174Out << 'y';3175break;3176case BuiltinType::UInt128:3177Out << 'o';3178break;3179case BuiltinType::SChar:3180Out << 'a';3181break;3182case BuiltinType::WChar_S:3183case BuiltinType::WChar_U:3184Out << 'w';3185break;3186case BuiltinType::Char8:3187Out << "Du";3188break;3189case BuiltinType::Char16:3190Out << "Ds";3191break;3192case BuiltinType::Char32:3193Out << "Di";3194break;3195case BuiltinType::Short:3196Out << 's';3197break;3198case BuiltinType::Int:3199Out << 'i';3200break;3201case BuiltinType::Long:3202Out << 'l';3203break;3204case BuiltinType::LongLong:3205Out << 'x';3206break;3207case BuiltinType::Int128:3208Out << 'n';3209break;3210case BuiltinType::Float16:3211Out << "DF16_";3212break;3213case BuiltinType::ShortAccum:3214Out << "DAs";3215break;3216case BuiltinType::Accum:3217Out << "DAi";3218break;3219case BuiltinType::LongAccum:3220Out << "DAl";3221break;3222case BuiltinType::UShortAccum:3223Out << "DAt";3224break;3225case BuiltinType::UAccum:3226Out << "DAj";3227break;3228case BuiltinType::ULongAccum:3229Out << "DAm";3230break;3231case BuiltinType::ShortFract:3232Out << "DRs";3233break;3234case BuiltinType::Fract:3235Out << "DRi";3236break;3237case BuiltinType::LongFract:3238Out << "DRl";3239break;3240case BuiltinType::UShortFract:3241Out << "DRt";3242break;3243case BuiltinType::UFract:3244Out << "DRj";3245break;3246case BuiltinType::ULongFract:3247Out << "DRm";3248break;3249case BuiltinType::SatShortAccum:3250Out << "DSDAs";3251break;3252case BuiltinType::SatAccum:3253Out << "DSDAi";3254break;3255case BuiltinType::SatLongAccum:3256Out << "DSDAl";3257break;3258case BuiltinType::SatUShortAccum:3259Out << "DSDAt";3260break;3261case BuiltinType::SatUAccum:3262Out << "DSDAj";3263break;3264case BuiltinType::SatULongAccum:3265Out << "DSDAm";3266break;3267case BuiltinType::SatShortFract:3268Out << "DSDRs";3269break;3270case BuiltinType::SatFract:3271Out << "DSDRi";3272break;3273case BuiltinType::SatLongFract:3274Out << "DSDRl";3275break;3276case BuiltinType::SatUShortFract:3277Out << "DSDRt";3278break;3279case BuiltinType::SatUFract:3280Out << "DSDRj";3281break;3282case BuiltinType::SatULongFract:3283Out << "DSDRm";3284break;3285case BuiltinType::Half:3286Out << "Dh";3287break;3288case BuiltinType::Float:3289Out << 'f';3290break;3291case BuiltinType::Double:3292Out << 'd';3293break;3294case BuiltinType::LongDouble: {3295const TargetInfo *TI =3296getASTContext().getLangOpts().OpenMP &&3297getASTContext().getLangOpts().OpenMPIsTargetDevice3298? getASTContext().getAuxTargetInfo()3299: &getASTContext().getTargetInfo();3300Out << TI->getLongDoubleMangling();3301break;3302}3303case BuiltinType::Float128: {3304const TargetInfo *TI =3305getASTContext().getLangOpts().OpenMP &&3306getASTContext().getLangOpts().OpenMPIsTargetDevice3307? getASTContext().getAuxTargetInfo()3308: &getASTContext().getTargetInfo();3309Out << TI->getFloat128Mangling();3310break;3311}3312case BuiltinType::BFloat16: {3313const TargetInfo *TI =3314((getASTContext().getLangOpts().OpenMP &&3315getASTContext().getLangOpts().OpenMPIsTargetDevice) ||3316getASTContext().getLangOpts().SYCLIsDevice)3317? getASTContext().getAuxTargetInfo()3318: &getASTContext().getTargetInfo();3319Out << TI->getBFloat16Mangling();3320break;3321}3322case BuiltinType::Ibm128: {3323const TargetInfo *TI = &getASTContext().getTargetInfo();3324Out << TI->getIbm128Mangling();3325break;3326}3327case BuiltinType::NullPtr:3328Out << "Dn";3329break;33303331#define BUILTIN_TYPE(Id, SingletonId)3332#define PLACEHOLDER_TYPE(Id, SingletonId) \3333case BuiltinType::Id:3334#include "clang/AST/BuiltinTypes.def"3335case BuiltinType::Dependent:3336if (!NullOut)3337llvm_unreachable("mangling a placeholder type");3338break;3339case BuiltinType::ObjCId:3340Out << "11objc_object";3341break;3342case BuiltinType::ObjCClass:3343Out << "10objc_class";3344break;3345case BuiltinType::ObjCSel:3346Out << "13objc_selector";3347break;3348#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \3349case BuiltinType::Id: \3350type_name = "ocl_" #ImgType "_" #Suffix; \3351Out << type_name.size() << type_name; \3352break;3353#include "clang/Basic/OpenCLImageTypes.def"3354case BuiltinType::OCLSampler:3355Out << "11ocl_sampler";3356break;3357case BuiltinType::OCLEvent:3358Out << "9ocl_event";3359break;3360case BuiltinType::OCLClkEvent:3361Out << "12ocl_clkevent";3362break;3363case BuiltinType::OCLQueue:3364Out << "9ocl_queue";3365break;3366case BuiltinType::OCLReserveID:3367Out << "13ocl_reserveid";3368break;3369#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \3370case BuiltinType::Id: \3371type_name = "ocl_" #ExtType; \3372Out << type_name.size() << type_name; \3373break;3374#include "clang/Basic/OpenCLExtensionTypes.def"3375// The SVE types are effectively target-specific. The mangling scheme3376// is defined in the appendices to the Procedure Call Standard for the3377// Arm Architecture.3378#define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \3379ElBits, IsSigned, IsFP, IsBF) \3380case BuiltinType::Id: \3381if (T->getKind() == BuiltinType::SveBFloat16 && \3382isCompatibleWith(LangOptions::ClangABI::Ver17)) { \3383/* Prior to Clang 18.0 we used this incorrect mangled name */ \3384type_name = "__SVBFloat16_t"; \3385Out << "u" << type_name.size() << type_name; \3386} else { \3387type_name = MangledName; \3388Out << (type_name == InternalName ? "u" : "") << type_name.size() \3389<< type_name; \3390} \3391break;3392#define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \3393case BuiltinType::Id: \3394type_name = MangledName; \3395Out << (type_name == InternalName ? "u" : "") << type_name.size() \3396<< type_name; \3397break;3398#define SVE_OPAQUE_TYPE(InternalName, MangledName, Id, SingletonId) \3399case BuiltinType::Id: \3400type_name = MangledName; \3401Out << (type_name == InternalName ? "u" : "") << type_name.size() \3402<< type_name; \3403break;3404#include "clang/Basic/AArch64SVEACLETypes.def"3405#define PPC_VECTOR_TYPE(Name, Id, Size) \3406case BuiltinType::Id: \3407type_name = #Name; \3408Out << 'u' << type_name.size() << type_name; \3409break;3410#include "clang/Basic/PPCTypes.def"3411// TODO: Check the mangling scheme for RISC-V V.3412#define RVV_TYPE(Name, Id, SingletonId) \3413case BuiltinType::Id: \3414type_name = Name; \3415Out << 'u' << type_name.size() << type_name; \3416break;3417#include "clang/Basic/RISCVVTypes.def"3418#define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \3419case BuiltinType::Id: \3420type_name = MangledName; \3421Out << 'u' << type_name.size() << type_name; \3422break;3423#include "clang/Basic/WebAssemblyReferenceTypes.def"3424#define AMDGPU_TYPE(Name, Id, SingletonId) \3425case BuiltinType::Id: \3426type_name = Name; \3427Out << 'u' << type_name.size() << type_name; \3428break;3429#include "clang/Basic/AMDGPUTypes.def"3430}3431}34323433StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {3434switch (CC) {3435case CC_C:3436return "";34373438case CC_X86VectorCall:3439case CC_X86Pascal:3440case CC_X86RegCall:3441case CC_AAPCS:3442case CC_AAPCS_VFP:3443case CC_AArch64VectorCall:3444case CC_AArch64SVEPCS:3445case CC_AMDGPUKernelCall:3446case CC_IntelOclBicc:3447case CC_SpirFunction:3448case CC_OpenCLKernel:3449case CC_PreserveMost:3450case CC_PreserveAll:3451case CC_M68kRTD:3452case CC_PreserveNone:3453case CC_RISCVVectorCall:3454// FIXME: we should be mangling all of the above.3455return "";34563457case CC_X86ThisCall:3458// FIXME: To match mingw GCC, thiscall should only be mangled in when it is3459// used explicitly. At this point, we don't have that much information in3460// the AST, since clang tends to bake the convention into the canonical3461// function type. thiscall only rarely used explicitly, so don't mangle it3462// for now.3463return "";34643465case CC_X86StdCall:3466return "stdcall";3467case CC_X86FastCall:3468return "fastcall";3469case CC_X86_64SysV:3470return "sysv_abi";3471case CC_Win64:3472return "ms_abi";3473case CC_Swift:3474return "swiftcall";3475case CC_SwiftAsync:3476return "swiftasynccall";3477}3478llvm_unreachable("bad calling convention");3479}34803481void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {3482// Fast path.3483if (T->getExtInfo() == FunctionType::ExtInfo())3484return;34853486// Vendor-specific qualifiers are emitted in reverse alphabetical order.3487// This will get more complicated in the future if we mangle other3488// things here; but for now, since we mangle ns_returns_retained as3489// a qualifier on the result type, we can get away with this:3490StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());3491if (!CCQualifier.empty())3492mangleVendorQualifier(CCQualifier);34933494// FIXME: regparm3495// FIXME: noreturn3496}34973498void3499CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {3500// Vendor-specific qualifiers are emitted in reverse alphabetical order.35013502// Note that these are *not* substitution candidates. Demanglers might3503// have trouble with this if the parameter type is fully substituted.35043505switch (PI.getABI()) {3506case ParameterABI::Ordinary:3507break;35083509// All of these start with "swift", so they come before "ns_consumed".3510case ParameterABI::SwiftContext:3511case ParameterABI::SwiftAsyncContext:3512case ParameterABI::SwiftErrorResult:3513case ParameterABI::SwiftIndirectResult:3514mangleVendorQualifier(getParameterABISpelling(PI.getABI()));3515break;3516}35173518if (PI.isConsumed())3519mangleVendorQualifier("ns_consumed");35203521if (PI.isNoEscape())3522mangleVendorQualifier("noescape");3523}35243525// <type> ::= <function-type>3526// <function-type> ::= [<CV-qualifiers>] F [Y]3527// <bare-function-type> [<ref-qualifier>] E3528void CXXNameMangler::mangleType(const FunctionProtoType *T) {3529mangleExtFunctionInfo(T);35303531// Mangle CV-qualifiers, if present. These are 'this' qualifiers,3532// e.g. "const" in "int (A::*)() const".3533mangleQualifiers(T->getMethodQuals());35343535// Mangle instantiation-dependent exception-specification, if present,3536// per cxx-abi-dev proposal on 2016-10-11.3537if (T->hasInstantiationDependentExceptionSpec()) {3538if (isComputedNoexcept(T->getExceptionSpecType())) {3539Out << "DO";3540mangleExpression(T->getNoexceptExpr());3541Out << "E";3542} else {3543assert(T->getExceptionSpecType() == EST_Dynamic);3544Out << "Dw";3545for (auto ExceptTy : T->exceptions())3546mangleType(ExceptTy);3547Out << "E";3548}3549} else if (T->isNothrow()) {3550Out << "Do";3551}35523553Out << 'F';35543555// FIXME: We don't have enough information in the AST to produce the 'Y'3556// encoding for extern "C" function types.3557mangleBareFunctionType(T, /*MangleReturnType=*/true);35583559// Mangle the ref-qualifier, if present.3560mangleRefQualifier(T->getRefQualifier());35613562Out << 'E';3563}35643565void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {3566// Function types without prototypes can arise when mangling a function type3567// within an overloadable function in C. We mangle these as the absence of any3568// parameter types (not even an empty parameter list).3569Out << 'F';35703571FunctionTypeDepthState saved = FunctionTypeDepth.push();35723573FunctionTypeDepth.enterResultType();3574mangleType(T->getReturnType());3575FunctionTypeDepth.leaveResultType();35763577FunctionTypeDepth.pop(saved);3578Out << 'E';3579}35803581void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,3582bool MangleReturnType,3583const FunctionDecl *FD) {3584// Record that we're in a function type. See mangleFunctionParam3585// for details on what we're trying to achieve here.3586FunctionTypeDepthState saved = FunctionTypeDepth.push();35873588// <bare-function-type> ::= <signature type>+3589if (MangleReturnType) {3590FunctionTypeDepth.enterResultType();35913592// Mangle ns_returns_retained as an order-sensitive qualifier here.3593if (Proto->getExtInfo().getProducesResult() && FD == nullptr)3594mangleVendorQualifier("ns_returns_retained");35953596// Mangle the return type without any direct ARC ownership qualifiers.3597QualType ReturnTy = Proto->getReturnType();3598if (ReturnTy.getObjCLifetime()) {3599auto SplitReturnTy = ReturnTy.split();3600SplitReturnTy.Quals.removeObjCLifetime();3601ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);3602}3603mangleType(ReturnTy);36043605FunctionTypeDepth.leaveResultType();3606}36073608if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {3609// <builtin-type> ::= v # void3610Out << 'v';3611} else {3612assert(!FD || FD->getNumParams() == Proto->getNumParams());3613for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {3614// Mangle extended parameter info as order-sensitive qualifiers here.3615if (Proto->hasExtParameterInfos() && FD == nullptr) {3616mangleExtParameterInfo(Proto->getExtParameterInfo(I));3617}36183619// Mangle the type.3620QualType ParamTy = Proto->getParamType(I);3621mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));36223623if (FD) {3624if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {3625// Attr can only take 1 character, so we can hardcode the length3626// below.3627assert(Attr->getType() <= 9 && Attr->getType() >= 0);3628if (Attr->isDynamic())3629Out << "U25pass_dynamic_object_size" << Attr->getType();3630else3631Out << "U17pass_object_size" << Attr->getType();3632}3633}3634}36353636// <builtin-type> ::= z # ellipsis3637if (Proto->isVariadic())3638Out << 'z';3639}36403641if (FD) {3642FunctionTypeDepth.enterResultType();3643mangleRequiresClause(FD->getTrailingRequiresClause());3644}36453646FunctionTypeDepth.pop(saved);3647}36483649// <type> ::= <class-enum-type>3650// <class-enum-type> ::= <name>3651void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {3652mangleName(T->getDecl());3653}36543655// <type> ::= <class-enum-type>3656// <class-enum-type> ::= <name>3657void CXXNameMangler::mangleType(const EnumType *T) {3658mangleType(static_cast<const TagType*>(T));3659}3660void CXXNameMangler::mangleType(const RecordType *T) {3661mangleType(static_cast<const TagType*>(T));3662}3663void CXXNameMangler::mangleType(const TagType *T) {3664mangleName(T->getDecl());3665}36663667// <type> ::= <array-type>3668// <array-type> ::= A <positive dimension number> _ <element type>3669// ::= A [<dimension expression>] _ <element type>3670void CXXNameMangler::mangleType(const ConstantArrayType *T) {3671Out << 'A' << T->getSize() << '_';3672mangleType(T->getElementType());3673}3674void CXXNameMangler::mangleType(const VariableArrayType *T) {3675Out << 'A';3676// decayed vla types (size 0) will just be skipped.3677if (T->getSizeExpr())3678mangleExpression(T->getSizeExpr());3679Out << '_';3680mangleType(T->getElementType());3681}3682void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {3683Out << 'A';3684// A DependentSizedArrayType might not have size expression as below3685//3686// template<int ...N> int arr[] = {N...};3687if (T->getSizeExpr())3688mangleExpression(T->getSizeExpr());3689Out << '_';3690mangleType(T->getElementType());3691}3692void CXXNameMangler::mangleType(const IncompleteArrayType *T) {3693Out << "A_";3694mangleType(T->getElementType());3695}36963697// <type> ::= <pointer-to-member-type>3698// <pointer-to-member-type> ::= M <class type> <member type>3699void CXXNameMangler::mangleType(const MemberPointerType *T) {3700Out << 'M';3701mangleType(QualType(T->getClass(), 0));3702QualType PointeeType = T->getPointeeType();3703if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {3704mangleType(FPT);37053706// Itanium C++ ABI 5.1.8:3707//3708// The type of a non-static member function is considered to be different,3709// for the purposes of substitution, from the type of a namespace-scope or3710// static member function whose type appears similar. The types of two3711// non-static member functions are considered to be different, for the3712// purposes of substitution, if the functions are members of different3713// classes. In other words, for the purposes of substitution, the class of3714// which the function is a member is considered part of the type of3715// function.37163717// Given that we already substitute member function pointers as a3718// whole, the net effect of this rule is just to unconditionally3719// suppress substitution on the function type in a member pointer.3720// We increment the SeqID here to emulate adding an entry to the3721// substitution table.3722++SeqID;3723} else3724mangleType(PointeeType);3725}37263727// <type> ::= <template-param>3728void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {3729mangleTemplateParameter(T->getDepth(), T->getIndex());3730}37313732// <type> ::= <template-param>3733void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {3734// FIXME: not clear how to mangle this!3735// template <class T...> class A {3736// template <class U...> void foo(T(*)(U) x...);3737// };3738Out << "_SUBSTPACK_";3739}37403741// <type> ::= P <type> # pointer-to3742void CXXNameMangler::mangleType(const PointerType *T) {3743Out << 'P';3744mangleType(T->getPointeeType());3745}3746void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {3747Out << 'P';3748mangleType(T->getPointeeType());3749}37503751// <type> ::= R <type> # reference-to3752void CXXNameMangler::mangleType(const LValueReferenceType *T) {3753Out << 'R';3754mangleType(T->getPointeeType());3755}37563757// <type> ::= O <type> # rvalue reference-to (C++0x)3758void CXXNameMangler::mangleType(const RValueReferenceType *T) {3759Out << 'O';3760mangleType(T->getPointeeType());3761}37623763// <type> ::= C <type> # complex pair (C 2000)3764void CXXNameMangler::mangleType(const ComplexType *T) {3765Out << 'C';3766mangleType(T->getElementType());3767}37683769// ARM's ABI for Neon vector types specifies that they should be mangled as3770// if they are structs (to match ARM's initial implementation). The3771// vector type must be one of the special types predefined by ARM.3772void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {3773QualType EltType = T->getElementType();3774assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");3775const char *EltName = nullptr;3776if (T->getVectorKind() == VectorKind::NeonPoly) {3777switch (cast<BuiltinType>(EltType)->getKind()) {3778case BuiltinType::SChar:3779case BuiltinType::UChar:3780EltName = "poly8_t";3781break;3782case BuiltinType::Short:3783case BuiltinType::UShort:3784EltName = "poly16_t";3785break;3786case BuiltinType::LongLong:3787case BuiltinType::ULongLong:3788EltName = "poly64_t";3789break;3790default: llvm_unreachable("unexpected Neon polynomial vector element type");3791}3792} else {3793switch (cast<BuiltinType>(EltType)->getKind()) {3794case BuiltinType::SChar: EltName = "int8_t"; break;3795case BuiltinType::UChar: EltName = "uint8_t"; break;3796case BuiltinType::Short: EltName = "int16_t"; break;3797case BuiltinType::UShort: EltName = "uint16_t"; break;3798case BuiltinType::Int: EltName = "int32_t"; break;3799case BuiltinType::UInt: EltName = "uint32_t"; break;3800case BuiltinType::LongLong: EltName = "int64_t"; break;3801case BuiltinType::ULongLong: EltName = "uint64_t"; break;3802case BuiltinType::Double: EltName = "float64_t"; break;3803case BuiltinType::Float: EltName = "float32_t"; break;3804case BuiltinType::Half: EltName = "float16_t"; break;3805case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;3806default:3807llvm_unreachable("unexpected Neon vector element type");3808}3809}3810const char *BaseName = nullptr;3811unsigned BitSize = (T->getNumElements() *3812getASTContext().getTypeSize(EltType));3813if (BitSize == 64)3814BaseName = "__simd64_";3815else {3816assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");3817BaseName = "__simd128_";3818}3819Out << strlen(BaseName) + strlen(EltName);3820Out << BaseName << EltName;3821}38223823void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {3824DiagnosticsEngine &Diags = Context.getDiags();3825unsigned DiagID = Diags.getCustomDiagID(3826DiagnosticsEngine::Error,3827"cannot mangle this dependent neon vector type yet");3828Diags.Report(T->getAttributeLoc(), DiagID);3829}38303831static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {3832switch (EltType->getKind()) {3833case BuiltinType::SChar:3834return "Int8";3835case BuiltinType::Short:3836return "Int16";3837case BuiltinType::Int:3838return "Int32";3839case BuiltinType::Long:3840case BuiltinType::LongLong:3841return "Int64";3842case BuiltinType::UChar:3843return "Uint8";3844case BuiltinType::UShort:3845return "Uint16";3846case BuiltinType::UInt:3847return "Uint32";3848case BuiltinType::ULong:3849case BuiltinType::ULongLong:3850return "Uint64";3851case BuiltinType::Half:3852return "Float16";3853case BuiltinType::Float:3854return "Float32";3855case BuiltinType::Double:3856return "Float64";3857case BuiltinType::BFloat16:3858return "Bfloat16";3859default:3860llvm_unreachable("Unexpected vector element base type");3861}3862}38633864// AArch64's ABI for Neon vector types specifies that they should be mangled as3865// the equivalent internal name. The vector type must be one of the special3866// types predefined by ARM.3867void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {3868QualType EltType = T->getElementType();3869assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");3870unsigned BitSize =3871(T->getNumElements() * getASTContext().getTypeSize(EltType));3872(void)BitSize; // Silence warning.38733874assert((BitSize == 64 || BitSize == 128) &&3875"Neon vector type not 64 or 128 bits");38763877StringRef EltName;3878if (T->getVectorKind() == VectorKind::NeonPoly) {3879switch (cast<BuiltinType>(EltType)->getKind()) {3880case BuiltinType::UChar:3881EltName = "Poly8";3882break;3883case BuiltinType::UShort:3884EltName = "Poly16";3885break;3886case BuiltinType::ULong:3887case BuiltinType::ULongLong:3888EltName = "Poly64";3889break;3890default:3891llvm_unreachable("unexpected Neon polynomial vector element type");3892}3893} else3894EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));38953896std::string TypeName =3897("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();3898Out << TypeName.length() << TypeName;3899}3900void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {3901DiagnosticsEngine &Diags = Context.getDiags();3902unsigned DiagID = Diags.getCustomDiagID(3903DiagnosticsEngine::Error,3904"cannot mangle this dependent neon vector type yet");3905Diags.Report(T->getAttributeLoc(), DiagID);3906}39073908// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types3909// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS643910// type as the sizeless variants.3911//3912// The mangling scheme for VLS types is implemented as a "pseudo" template:3913//3914// '__SVE_VLS<<type>, <vector length>>'3915//3916// Combining the existing SVE type and a specific vector length (in bits).3917// For example:3918//3919// typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));3920//3921// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:3922//3923// "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"3924//3925// i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE3926//3927// The latest ACLE specification (00bet5) does not contain details of this3928// mangling scheme, it will be specified in the next revision. The mangling3929// scheme is otherwise defined in the appendices to the Procedure Call Standard3930// for the Arm Architecture, see3931// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling3932void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {3933assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||3934T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&3935"expected fixed-length SVE vector!");39363937QualType EltType = T->getElementType();3938assert(EltType->isBuiltinType() &&3939"expected builtin type for fixed-length SVE vector!");39403941StringRef TypeName;3942switch (cast<BuiltinType>(EltType)->getKind()) {3943case BuiltinType::SChar:3944TypeName = "__SVInt8_t";3945break;3946case BuiltinType::UChar: {3947if (T->getVectorKind() == VectorKind::SveFixedLengthData)3948TypeName = "__SVUint8_t";3949else3950TypeName = "__SVBool_t";3951break;3952}3953case BuiltinType::Short:3954TypeName = "__SVInt16_t";3955break;3956case BuiltinType::UShort:3957TypeName = "__SVUint16_t";3958break;3959case BuiltinType::Int:3960TypeName = "__SVInt32_t";3961break;3962case BuiltinType::UInt:3963TypeName = "__SVUint32_t";3964break;3965case BuiltinType::Long:3966TypeName = "__SVInt64_t";3967break;3968case BuiltinType::ULong:3969TypeName = "__SVUint64_t";3970break;3971case BuiltinType::Half:3972TypeName = "__SVFloat16_t";3973break;3974case BuiltinType::Float:3975TypeName = "__SVFloat32_t";3976break;3977case BuiltinType::Double:3978TypeName = "__SVFloat64_t";3979break;3980case BuiltinType::BFloat16:3981TypeName = "__SVBfloat16_t";3982break;3983default:3984llvm_unreachable("unexpected element type for fixed-length SVE vector!");3985}39863987unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;39883989if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)3990VecSizeInBits *= 8;39913992Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"3993<< VecSizeInBits << "EE";3994}39953996void CXXNameMangler::mangleAArch64FixedSveVectorType(3997const DependentVectorType *T) {3998DiagnosticsEngine &Diags = Context.getDiags();3999unsigned DiagID = Diags.getCustomDiagID(4000DiagnosticsEngine::Error,4001"cannot mangle this dependent fixed-length SVE vector type yet");4002Diags.Report(T->getAttributeLoc(), DiagID);4003}40044005void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {4006assert((T->getVectorKind() == VectorKind::RVVFixedLengthData ||4007T->getVectorKind() == VectorKind::RVVFixedLengthMask) &&4008"expected fixed-length RVV vector!");40094010QualType EltType = T->getElementType();4011assert(EltType->isBuiltinType() &&4012"expected builtin type for fixed-length RVV vector!");40134014SmallString<20> TypeNameStr;4015llvm::raw_svector_ostream TypeNameOS(TypeNameStr);4016TypeNameOS << "__rvv_";4017switch (cast<BuiltinType>(EltType)->getKind()) {4018case BuiltinType::SChar:4019TypeNameOS << "int8";4020break;4021case BuiltinType::UChar:4022if (T->getVectorKind() == VectorKind::RVVFixedLengthData)4023TypeNameOS << "uint8";4024else4025TypeNameOS << "bool";4026break;4027case BuiltinType::Short:4028TypeNameOS << "int16";4029break;4030case BuiltinType::UShort:4031TypeNameOS << "uint16";4032break;4033case BuiltinType::Int:4034TypeNameOS << "int32";4035break;4036case BuiltinType::UInt:4037TypeNameOS << "uint32";4038break;4039case BuiltinType::Long:4040TypeNameOS << "int64";4041break;4042case BuiltinType::ULong:4043TypeNameOS << "uint64";4044break;4045case BuiltinType::Float16:4046TypeNameOS << "float16";4047break;4048case BuiltinType::Float:4049TypeNameOS << "float32";4050break;4051case BuiltinType::Double:4052TypeNameOS << "float64";4053break;4054default:4055llvm_unreachable("unexpected element type for fixed-length RVV vector!");4056}40574058unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;40594060// Apend the LMUL suffix.4061auto VScale = getASTContext().getTargetInfo().getVScaleRange(4062getASTContext().getLangOpts());4063unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;40644065if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {4066TypeNameOS << 'm';4067if (VecSizeInBits >= VLen)4068TypeNameOS << (VecSizeInBits / VLen);4069else4070TypeNameOS << 'f' << (VLen / VecSizeInBits);4071} else {4072TypeNameOS << (VLen / VecSizeInBits);4073}4074TypeNameOS << "_t";40754076Out << "9__RVV_VLSI" << 'u' << TypeNameStr.size() << TypeNameStr << "Lj"4077<< VecSizeInBits << "EE";4078}40794080void CXXNameMangler::mangleRISCVFixedRVVVectorType(4081const DependentVectorType *T) {4082DiagnosticsEngine &Diags = Context.getDiags();4083unsigned DiagID = Diags.getCustomDiagID(4084DiagnosticsEngine::Error,4085"cannot mangle this dependent fixed-length RVV vector type yet");4086Diags.Report(T->getAttributeLoc(), DiagID);4087}40884089// GNU extension: vector types4090// <type> ::= <vector-type>4091// <vector-type> ::= Dv <positive dimension number> _4092// <extended element type>4093// ::= Dv [<dimension expression>] _ <element type>4094// <extended element type> ::= <element type>4095// ::= p # AltiVec vector pixel4096// ::= b # Altivec vector bool4097void CXXNameMangler::mangleType(const VectorType *T) {4098if ((T->getVectorKind() == VectorKind::Neon ||4099T->getVectorKind() == VectorKind::NeonPoly)) {4100llvm::Triple Target = getASTContext().getTargetInfo().getTriple();4101llvm::Triple::ArchType Arch =4102getASTContext().getTargetInfo().getTriple().getArch();4103if ((Arch == llvm::Triple::aarch64 ||4104Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())4105mangleAArch64NeonVectorType(T);4106else4107mangleNeonVectorType(T);4108return;4109} else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||4110T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {4111mangleAArch64FixedSveVectorType(T);4112return;4113} else if (T->getVectorKind() == VectorKind::RVVFixedLengthData ||4114T->getVectorKind() == VectorKind::RVVFixedLengthMask) {4115mangleRISCVFixedRVVVectorType(T);4116return;4117}4118Out << "Dv" << T->getNumElements() << '_';4119if (T->getVectorKind() == VectorKind::AltiVecPixel)4120Out << 'p';4121else if (T->getVectorKind() == VectorKind::AltiVecBool)4122Out << 'b';4123else4124mangleType(T->getElementType());4125}41264127void CXXNameMangler::mangleType(const DependentVectorType *T) {4128if ((T->getVectorKind() == VectorKind::Neon ||4129T->getVectorKind() == VectorKind::NeonPoly)) {4130llvm::Triple Target = getASTContext().getTargetInfo().getTriple();4131llvm::Triple::ArchType Arch =4132getASTContext().getTargetInfo().getTriple().getArch();4133if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&4134!Target.isOSDarwin())4135mangleAArch64NeonVectorType(T);4136else4137mangleNeonVectorType(T);4138return;4139} else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||4140T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {4141mangleAArch64FixedSveVectorType(T);4142return;4143} else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {4144mangleRISCVFixedRVVVectorType(T);4145return;4146}41474148Out << "Dv";4149mangleExpression(T->getSizeExpr());4150Out << '_';4151if (T->getVectorKind() == VectorKind::AltiVecPixel)4152Out << 'p';4153else if (T->getVectorKind() == VectorKind::AltiVecBool)4154Out << 'b';4155else4156mangleType(T->getElementType());4157}41584159void CXXNameMangler::mangleType(const ExtVectorType *T) {4160mangleType(static_cast<const VectorType*>(T));4161}4162void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {4163Out << "Dv";4164mangleExpression(T->getSizeExpr());4165Out << '_';4166mangleType(T->getElementType());4167}41684169void CXXNameMangler::mangleType(const ConstantMatrixType *T) {4170// Mangle matrix types as a vendor extended type:4171// u<Len>matrix_typeI<Rows><Columns><element type>E41724173StringRef VendorQualifier = "matrix_type";4174Out << "u" << VendorQualifier.size() << VendorQualifier;41754176Out << "I";4177auto &ASTCtx = getASTContext();4178unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());4179llvm::APSInt Rows(BitWidth);4180Rows = T->getNumRows();4181mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);4182llvm::APSInt Columns(BitWidth);4183Columns = T->getNumColumns();4184mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);4185mangleType(T->getElementType());4186Out << "E";4187}41884189void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {4190// Mangle matrix types as a vendor extended type:4191// u<Len>matrix_typeI<row expr><column expr><element type>E4192StringRef VendorQualifier = "matrix_type";4193Out << "u" << VendorQualifier.size() << VendorQualifier;41944195Out << "I";4196mangleTemplateArgExpr(T->getRowExpr());4197mangleTemplateArgExpr(T->getColumnExpr());4198mangleType(T->getElementType());4199Out << "E";4200}42014202void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {4203SplitQualType split = T->getPointeeType().split();4204mangleQualifiers(split.Quals, T);4205mangleType(QualType(split.Ty, 0));4206}42074208void CXXNameMangler::mangleType(const PackExpansionType *T) {4209// <type> ::= Dp <type> # pack expansion (C++0x)4210Out << "Dp";4211mangleType(T->getPattern());4212}42134214void CXXNameMangler::mangleType(const PackIndexingType *T) {4215if (!T->hasSelectedType())4216mangleType(T->getPattern());4217else4218mangleType(T->getSelectedType());4219}42204221void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {4222mangleSourceName(T->getDecl()->getIdentifier());4223}42244225void CXXNameMangler::mangleType(const ObjCObjectType *T) {4226// Treat __kindof as a vendor extended type qualifier.4227if (T->isKindOfType())4228Out << "U8__kindof";42294230if (!T->qual_empty()) {4231// Mangle protocol qualifiers.4232SmallString<64> QualStr;4233llvm::raw_svector_ostream QualOS(QualStr);4234QualOS << "objcproto";4235for (const auto *I : T->quals()) {4236StringRef name = I->getName();4237QualOS << name.size() << name;4238}4239Out << 'U' << QualStr.size() << QualStr;4240}42414242mangleType(T->getBaseType());42434244if (T->isSpecialized()) {4245// Mangle type arguments as I <type>+ E4246Out << 'I';4247for (auto typeArg : T->getTypeArgs())4248mangleType(typeArg);4249Out << 'E';4250}4251}42524253void CXXNameMangler::mangleType(const BlockPointerType *T) {4254Out << "U13block_pointer";4255mangleType(T->getPointeeType());4256}42574258void CXXNameMangler::mangleType(const InjectedClassNameType *T) {4259// Mangle injected class name types as if the user had written the4260// specialization out fully. It may not actually be possible to see4261// this mangling, though.4262mangleType(T->getInjectedSpecializationType());4263}42644265void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {4266if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {4267mangleTemplateName(TD, T->template_arguments());4268} else {4269if (mangleSubstitution(QualType(T, 0)))4270return;42714272mangleTemplatePrefix(T->getTemplateName());42734274// FIXME: GCC does not appear to mangle the template arguments when4275// the template in question is a dependent template name. Should we4276// emulate that badness?4277mangleTemplateArgs(T->getTemplateName(), T->template_arguments());4278addSubstitution(QualType(T, 0));4279}4280}42814282void CXXNameMangler::mangleType(const DependentNameType *T) {4283// Proposal by cxx-abi-dev, 2014-03-264284// <class-enum-type> ::= <name> # non-dependent or dependent type name or4285// # dependent elaborated type specifier using4286// # 'typename'4287// ::= Ts <name> # dependent elaborated type specifier using4288// # 'struct' or 'class'4289// ::= Tu <name> # dependent elaborated type specifier using4290// # 'union'4291// ::= Te <name> # dependent elaborated type specifier using4292// # 'enum'4293switch (T->getKeyword()) {4294case ElaboratedTypeKeyword::None:4295case ElaboratedTypeKeyword::Typename:4296break;4297case ElaboratedTypeKeyword::Struct:4298case ElaboratedTypeKeyword::Class:4299case ElaboratedTypeKeyword::Interface:4300Out << "Ts";4301break;4302case ElaboratedTypeKeyword::Union:4303Out << "Tu";4304break;4305case ElaboratedTypeKeyword::Enum:4306Out << "Te";4307break;4308}4309// Typename types are always nested4310Out << 'N';4311manglePrefix(T->getQualifier());4312mangleSourceName(T->getIdentifier());4313Out << 'E';4314}43154316void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {4317// Dependently-scoped template types are nested if they have a prefix.4318Out << 'N';43194320// TODO: avoid making this TemplateName.4321TemplateName Prefix =4322getASTContext().getDependentTemplateName(T->getQualifier(),4323T->getIdentifier());4324mangleTemplatePrefix(Prefix);43254326// FIXME: GCC does not appear to mangle the template arguments when4327// the template in question is a dependent template name. Should we4328// emulate that badness?4329mangleTemplateArgs(Prefix, T->template_arguments());4330Out << 'E';4331}43324333void CXXNameMangler::mangleType(const TypeOfType *T) {4334// FIXME: this is pretty unsatisfactory, but there isn't an obvious4335// "extension with parameters" mangling.4336Out << "u6typeof";4337}43384339void CXXNameMangler::mangleType(const TypeOfExprType *T) {4340// FIXME: this is pretty unsatisfactory, but there isn't an obvious4341// "extension with parameters" mangling.4342Out << "u6typeof";4343}43444345void CXXNameMangler::mangleType(const DecltypeType *T) {4346Expr *E = T->getUnderlyingExpr();43474348// type ::= Dt <expression> E # decltype of an id-expression4349// # or class member access4350// ::= DT <expression> E # decltype of an expression43514352// This purports to be an exhaustive list of id-expressions and4353// class member accesses. Note that we do not ignore parentheses;4354// parentheses change the semantics of decltype for these4355// expressions (and cause the mangler to use the other form).4356if (isa<DeclRefExpr>(E) ||4357isa<MemberExpr>(E) ||4358isa<UnresolvedLookupExpr>(E) ||4359isa<DependentScopeDeclRefExpr>(E) ||4360isa<CXXDependentScopeMemberExpr>(E) ||4361isa<UnresolvedMemberExpr>(E))4362Out << "Dt";4363else4364Out << "DT";4365mangleExpression(E);4366Out << 'E';4367}43684369void CXXNameMangler::mangleType(const UnaryTransformType *T) {4370// If this is dependent, we need to record that. If not, we simply4371// mangle it as the underlying type since they are equivalent.4372if (T->isDependentType()) {4373Out << "u";43744375StringRef BuiltinName;4376switch (T->getUTTKind()) {4377#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \4378case UnaryTransformType::Enum: \4379BuiltinName = "__" #Trait; \4380break;4381#include "clang/Basic/TransformTypeTraits.def"4382}4383Out << BuiltinName.size() << BuiltinName;4384}43854386Out << "I";4387mangleType(T->getBaseType());4388Out << "E";4389}43904391void CXXNameMangler::mangleType(const AutoType *T) {4392assert(T->getDeducedType().isNull() &&4393"Deduced AutoType shouldn't be handled here!");4394assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&4395"shouldn't need to mangle __auto_type!");4396// <builtin-type> ::= Da # auto4397// ::= Dc # decltype(auto)4398// ::= Dk # constrained auto4399// ::= DK # constrained decltype(auto)4400if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {4401Out << (T->isDecltypeAuto() ? "DK" : "Dk");4402mangleTypeConstraint(T->getTypeConstraintConcept(),4403T->getTypeConstraintArguments());4404} else {4405Out << (T->isDecltypeAuto() ? "Dc" : "Da");4406}4407}44084409void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {4410QualType Deduced = T->getDeducedType();4411if (!Deduced.isNull())4412return mangleType(Deduced);44134414TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();4415assert(TD && "shouldn't form deduced TST unless we know we have a template");44164417if (mangleSubstitution(TD))4418return;44194420mangleName(GlobalDecl(TD));4421addSubstitution(TD);4422}44234424void CXXNameMangler::mangleType(const AtomicType *T) {4425// <type> ::= U <source-name> <type> # vendor extended type qualifier4426// (Until there's a standardized mangling...)4427Out << "U7_Atomic";4428mangleType(T->getValueType());4429}44304431void CXXNameMangler::mangleType(const PipeType *T) {4432// Pipe type mangling rules are described in SPIR 2.0 specification4433// A.1 Data types and A.3 Summary of changes4434// <type> ::= 8ocl_pipe4435Out << "8ocl_pipe";4436}44374438void CXXNameMangler::mangleType(const BitIntType *T) {4439// 5.1.5.2 Builtin types4440// <type> ::= DB <number | instantiation-dependent expression> _4441// ::= DU <number | instantiation-dependent expression> _4442Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";4443}44444445void CXXNameMangler::mangleType(const DependentBitIntType *T) {4446// 5.1.5.2 Builtin types4447// <type> ::= DB <number | instantiation-dependent expression> _4448// ::= DU <number | instantiation-dependent expression> _4449Out << "D" << (T->isUnsigned() ? "U" : "B");4450mangleExpression(T->getNumBitsExpr());4451Out << "_";4452}44534454void CXXNameMangler::mangleType(const ArrayParameterType *T) {4455mangleType(cast<ConstantArrayType>(T));4456}44574458void CXXNameMangler::mangleIntegerLiteral(QualType T,4459const llvm::APSInt &Value) {4460// <expr-primary> ::= L <type> <value number> E # integer literal4461Out << 'L';44624463mangleType(T);4464if (T->isBooleanType()) {4465// Boolean values are encoded as 0/1.4466Out << (Value.getBoolValue() ? '1' : '0');4467} else {4468mangleNumber(Value);4469}4470Out << 'E';44714472}44734474void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {4475// Ignore member expressions involving anonymous unions.4476while (const auto *RT = Base->getType()->getAs<RecordType>()) {4477if (!RT->getDecl()->isAnonymousStructOrUnion())4478break;4479const auto *ME = dyn_cast<MemberExpr>(Base);4480if (!ME)4481break;4482Base = ME->getBase();4483IsArrow = ME->isArrow();4484}44854486if (Base->isImplicitCXXThis()) {4487// Note: GCC mangles member expressions to the implicit 'this' as4488// *this., whereas we represent them as this->. The Itanium C++ ABI4489// does not specify anything here, so we follow GCC.4490Out << "dtdefpT";4491} else {4492Out << (IsArrow ? "pt" : "dt");4493mangleExpression(Base);4494}4495}44964497/// Mangles a member expression.4498void CXXNameMangler::mangleMemberExpr(const Expr *base,4499bool isArrow,4500NestedNameSpecifier *qualifier,4501NamedDecl *firstQualifierLookup,4502DeclarationName member,4503const TemplateArgumentLoc *TemplateArgs,4504unsigned NumTemplateArgs,4505unsigned arity) {4506// <expression> ::= dt <expression> <unresolved-name>4507// ::= pt <expression> <unresolved-name>4508if (base)4509mangleMemberExprBase(base, isArrow);4510mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);4511}45124513/// Look at the callee of the given call expression and determine if4514/// it's a parenthesized id-expression which would have triggered ADL4515/// otherwise.4516static bool isParenthesizedADLCallee(const CallExpr *call) {4517const Expr *callee = call->getCallee();4518const Expr *fn = callee->IgnoreParens();45194520// Must be parenthesized. IgnoreParens() skips __extension__ nodes,4521// too, but for those to appear in the callee, it would have to be4522// parenthesized.4523if (callee == fn) return false;45244525// Must be an unresolved lookup.4526const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);4527if (!lookup) return false;45284529assert(!lookup->requiresADL());45304531// Must be an unqualified lookup.4532if (lookup->getQualifier()) return false;45334534// Must not have found a class member. Note that if one is a class4535// member, they're all class members.4536if (lookup->getNumDecls() > 0 &&4537(*lookup->decls_begin())->isCXXClassMember())4538return false;45394540// Otherwise, ADL would have been triggered.4541return true;4542}45434544void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {4545const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);4546Out << CastEncoding;4547mangleType(ECE->getType());4548mangleExpression(ECE->getSubExpr());4549}45504551void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {4552if (auto *Syntactic = InitList->getSyntacticForm())4553InitList = Syntactic;4554for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)4555mangleExpression(InitList->getInit(i));4556}45574558void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc,4559const concepts::Requirement *Req) {4560using concepts::Requirement;45614562// TODO: We can't mangle the result of a failed substitution. It's not clear4563// whether we should be mangling the original form prior to any substitution4564// instead. See https://lists.isocpp.org/core/2023/04/14118.php4565auto HandleSubstitutionFailure =4566[&](SourceLocation Loc) {4567DiagnosticsEngine &Diags = Context.getDiags();4568unsigned DiagID = Diags.getCustomDiagID(4569DiagnosticsEngine::Error, "cannot mangle this requires-expression "4570"containing a substitution failure");4571Diags.Report(Loc, DiagID);4572Out << 'F';4573};45744575switch (Req->getKind()) {4576case Requirement::RK_Type: {4577const auto *TR = cast<concepts::TypeRequirement>(Req);4578if (TR->isSubstitutionFailure())4579return HandleSubstitutionFailure(4580TR->getSubstitutionDiagnostic()->DiagLoc);45814582Out << 'T';4583mangleType(TR->getType()->getType());4584break;4585}45864587case Requirement::RK_Simple:4588case Requirement::RK_Compound: {4589const auto *ER = cast<concepts::ExprRequirement>(Req);4590if (ER->isExprSubstitutionFailure())4591return HandleSubstitutionFailure(4592ER->getExprSubstitutionDiagnostic()->DiagLoc);45934594Out << 'X';4595mangleExpression(ER->getExpr());45964597if (ER->hasNoexceptRequirement())4598Out << 'N';45994600if (!ER->getReturnTypeRequirement().isEmpty()) {4601if (ER->getReturnTypeRequirement().isSubstitutionFailure())4602return HandleSubstitutionFailure(ER->getReturnTypeRequirement()4603.getSubstitutionDiagnostic()4604->DiagLoc);46054606Out << 'R';4607mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());4608}4609break;4610}46114612case Requirement::RK_Nested:4613const auto *NR = cast<concepts::NestedRequirement>(Req);4614if (NR->hasInvalidConstraint()) {4615// FIXME: NestedRequirement should track the location of its requires4616// keyword.4617return HandleSubstitutionFailure(RequiresExprLoc);4618}46194620Out << 'Q';4621mangleExpression(NR->getConstraintExpr());4622break;4623}4624}46254626void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,4627bool AsTemplateArg) {4628// <expression> ::= <unary operator-name> <expression>4629// ::= <binary operator-name> <expression> <expression>4630// ::= <trinary operator-name> <expression> <expression> <expression>4631// ::= cv <type> expression # conversion with one argument4632// ::= cv <type> _ <expression>* E # conversion with a different number of arguments4633// ::= dc <type> <expression> # dynamic_cast<type> (expression)4634// ::= sc <type> <expression> # static_cast<type> (expression)4635// ::= cc <type> <expression> # const_cast<type> (expression)4636// ::= rc <type> <expression> # reinterpret_cast<type> (expression)4637// ::= st <type> # sizeof (a type)4638// ::= at <type> # alignof (a type)4639// ::= <template-param>4640// ::= <function-param>4641// ::= fpT # 'this' expression (part of <function-param>)4642// ::= sr <type> <unqualified-name> # dependent name4643// ::= sr <type> <unqualified-name> <template-args> # dependent template-id4644// ::= ds <expression> <expression> # expr.*expr4645// ::= sZ <template-param> # size of a parameter pack4646// ::= sZ <function-param> # size of a function parameter pack4647// ::= u <source-name> <template-arg>* E # vendor extended expression4648// ::= <expr-primary>4649// <expr-primary> ::= L <type> <value number> E # integer literal4650// ::= L <type> <value float> E # floating literal4651// ::= L <type> <string type> E # string literal4652// ::= L <nullptr type> E # nullptr literal "LDnE"4653// ::= L <pointer type> 0 E # null pointer template argument4654// ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang4655// ::= L <mangled-name> E # external name4656QualType ImplicitlyConvertedToType;46574658// A top-level expression that's not <expr-primary> needs to be wrapped in4659// X...E in a template arg.4660bool IsPrimaryExpr = true;4661auto NotPrimaryExpr = [&] {4662if (AsTemplateArg && IsPrimaryExpr)4663Out << 'X';4664IsPrimaryExpr = false;4665};46664667auto MangleDeclRefExpr = [&](const NamedDecl *D) {4668switch (D->getKind()) {4669default:4670// <expr-primary> ::= L <mangled-name> E # external name4671Out << 'L';4672mangle(D);4673Out << 'E';4674break;46754676case Decl::ParmVar:4677NotPrimaryExpr();4678mangleFunctionParam(cast<ParmVarDecl>(D));4679break;46804681case Decl::EnumConstant: {4682// <expr-primary>4683const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);4684mangleIntegerLiteral(ED->getType(), ED->getInitVal());4685break;4686}46874688case Decl::NonTypeTemplateParm:4689NotPrimaryExpr();4690const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);4691mangleTemplateParameter(PD->getDepth(), PD->getIndex());4692break;4693}4694};46954696// 'goto recurse' is used when handling a simple "unwrapping" node which4697// produces no output, where ImplicitlyConvertedToType and AsTemplateArg need4698// to be preserved.4699recurse:4700switch (E->getStmtClass()) {4701case Expr::NoStmtClass:4702#define ABSTRACT_STMT(Type)4703#define EXPR(Type, Base)4704#define STMT(Type, Base) \4705case Expr::Type##Class:4706#include "clang/AST/StmtNodes.inc"4707// fallthrough47084709// These all can only appear in local or variable-initialization4710// contexts and so should never appear in a mangling.4711case Expr::AddrLabelExprClass:4712case Expr::DesignatedInitUpdateExprClass:4713case Expr::ImplicitValueInitExprClass:4714case Expr::ArrayInitLoopExprClass:4715case Expr::ArrayInitIndexExprClass:4716case Expr::NoInitExprClass:4717case Expr::ParenListExprClass:4718case Expr::MSPropertyRefExprClass:4719case Expr::MSPropertySubscriptExprClass:4720case Expr::TypoExprClass: // This should no longer exist in the AST by now.4721case Expr::RecoveryExprClass:4722case Expr::ArraySectionExprClass:4723case Expr::OMPArrayShapingExprClass:4724case Expr::OMPIteratorExprClass:4725case Expr::CXXInheritedCtorInitExprClass:4726case Expr::CXXParenListInitExprClass:4727case Expr::PackIndexingExprClass:4728llvm_unreachable("unexpected statement kind");47294730case Expr::ConstantExprClass:4731E = cast<ConstantExpr>(E)->getSubExpr();4732goto recurse;47334734// FIXME: invent manglings for all these.4735case Expr::BlockExprClass:4736case Expr::ChooseExprClass:4737case Expr::CompoundLiteralExprClass:4738case Expr::ExtVectorElementExprClass:4739case Expr::GenericSelectionExprClass:4740case Expr::ObjCEncodeExprClass:4741case Expr::ObjCIsaExprClass:4742case Expr::ObjCIvarRefExprClass:4743case Expr::ObjCMessageExprClass:4744case Expr::ObjCPropertyRefExprClass:4745case Expr::ObjCProtocolExprClass:4746case Expr::ObjCSelectorExprClass:4747case Expr::ObjCStringLiteralClass:4748case Expr::ObjCBoxedExprClass:4749case Expr::ObjCArrayLiteralClass:4750case Expr::ObjCDictionaryLiteralClass:4751case Expr::ObjCSubscriptRefExprClass:4752case Expr::ObjCIndirectCopyRestoreExprClass:4753case Expr::ObjCAvailabilityCheckExprClass:4754case Expr::OffsetOfExprClass:4755case Expr::PredefinedExprClass:4756case Expr::ShuffleVectorExprClass:4757case Expr::ConvertVectorExprClass:4758case Expr::StmtExprClass:4759case Expr::ArrayTypeTraitExprClass:4760case Expr::ExpressionTraitExprClass:4761case Expr::VAArgExprClass:4762case Expr::CUDAKernelCallExprClass:4763case Expr::AsTypeExprClass:4764case Expr::PseudoObjectExprClass:4765case Expr::AtomicExprClass:4766case Expr::SourceLocExprClass:4767case Expr::EmbedExprClass:4768case Expr::BuiltinBitCastExprClass:4769{4770NotPrimaryExpr();4771if (!NullOut) {4772// As bad as this diagnostic is, it's better than crashing.4773DiagnosticsEngine &Diags = Context.getDiags();4774unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,4775"cannot yet mangle expression type %0");4776Diags.Report(E->getExprLoc(), DiagID)4777<< E->getStmtClassName() << E->getSourceRange();4778return;4779}4780break;4781}47824783case Expr::CXXUuidofExprClass: {4784NotPrimaryExpr();4785const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);4786// As of clang 12, uuidof uses the vendor extended expression4787// mangling. Previously, it used a special-cased nonstandard extension.4788if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {4789Out << "u8__uuidof";4790if (UE->isTypeOperand())4791mangleType(UE->getTypeOperand(Context.getASTContext()));4792else4793mangleTemplateArgExpr(UE->getExprOperand());4794Out << 'E';4795} else {4796if (UE->isTypeOperand()) {4797QualType UuidT = UE->getTypeOperand(Context.getASTContext());4798Out << "u8__uuidoft";4799mangleType(UuidT);4800} else {4801Expr *UuidExp = UE->getExprOperand();4802Out << "u8__uuidofz";4803mangleExpression(UuidExp);4804}4805}4806break;4807}48084809// Even gcc-4.5 doesn't mangle this.4810case Expr::BinaryConditionalOperatorClass: {4811NotPrimaryExpr();4812DiagnosticsEngine &Diags = Context.getDiags();4813unsigned DiagID =4814Diags.getCustomDiagID(DiagnosticsEngine::Error,4815"?: operator with omitted middle operand cannot be mangled");4816Diags.Report(E->getExprLoc(), DiagID)4817<< E->getStmtClassName() << E->getSourceRange();4818return;4819}48204821// These are used for internal purposes and cannot be meaningfully mangled.4822case Expr::OpaqueValueExprClass:4823llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");48244825case Expr::InitListExprClass: {4826NotPrimaryExpr();4827Out << "il";4828mangleInitListElements(cast<InitListExpr>(E));4829Out << "E";4830break;4831}48324833case Expr::DesignatedInitExprClass: {4834NotPrimaryExpr();4835auto *DIE = cast<DesignatedInitExpr>(E);4836for (const auto &Designator : DIE->designators()) {4837if (Designator.isFieldDesignator()) {4838Out << "di";4839mangleSourceName(Designator.getFieldName());4840} else if (Designator.isArrayDesignator()) {4841Out << "dx";4842mangleExpression(DIE->getArrayIndex(Designator));4843} else {4844assert(Designator.isArrayRangeDesignator() &&4845"unknown designator kind");4846Out << "dX";4847mangleExpression(DIE->getArrayRangeStart(Designator));4848mangleExpression(DIE->getArrayRangeEnd(Designator));4849}4850}4851mangleExpression(DIE->getInit());4852break;4853}48544855case Expr::CXXDefaultArgExprClass:4856E = cast<CXXDefaultArgExpr>(E)->getExpr();4857goto recurse;48584859case Expr::CXXDefaultInitExprClass:4860E = cast<CXXDefaultInitExpr>(E)->getExpr();4861goto recurse;48624863case Expr::CXXStdInitializerListExprClass:4864E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();4865goto recurse;48664867case Expr::SubstNonTypeTemplateParmExprClass: {4868// Mangle a substituted parameter the same way we mangle the template4869// argument.4870auto *SNTTPE = cast<SubstNonTypeTemplateParmExpr>(E);4871if (auto *CE = dyn_cast<ConstantExpr>(SNTTPE->getReplacement())) {4872// Pull out the constant value and mangle it as a template argument.4873QualType ParamType = SNTTPE->getParameterType(Context.getASTContext());4874assert(CE->hasAPValueResult() && "expected the NTTP to have an APValue");4875mangleValueInTemplateArg(ParamType, CE->getAPValueResult(), false,4876/*NeedExactType=*/true);4877break;4878}4879// The remaining cases all happen to be substituted with expressions that4880// mangle the same as a corresponding template argument anyway.4881E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();4882goto recurse;4883}48844885case Expr::UserDefinedLiteralClass:4886// We follow g++'s approach of mangling a UDL as a call to the literal4887// operator.4888case Expr::CXXMemberCallExprClass: // fallthrough4889case Expr::CallExprClass: {4890NotPrimaryExpr();4891const CallExpr *CE = cast<CallExpr>(E);48924893// <expression> ::= cp <simple-id> <expression>* E4894// We use this mangling only when the call would use ADL except4895// for being parenthesized. Per discussion with David4896// Vandervoorde, 2011.04.25.4897if (isParenthesizedADLCallee(CE)) {4898Out << "cp";4899// The callee here is a parenthesized UnresolvedLookupExpr with4900// no qualifier and should always get mangled as a <simple-id>4901// anyway.49024903// <expression> ::= cl <expression>* E4904} else {4905Out << "cl";4906}49074908unsigned CallArity = CE->getNumArgs();4909for (const Expr *Arg : CE->arguments())4910if (isa<PackExpansionExpr>(Arg))4911CallArity = UnknownArity;49124913mangleExpression(CE->getCallee(), CallArity);4914for (const Expr *Arg : CE->arguments())4915mangleExpression(Arg);4916Out << 'E';4917break;4918}49194920case Expr::CXXNewExprClass: {4921NotPrimaryExpr();4922const CXXNewExpr *New = cast<CXXNewExpr>(E);4923if (New->isGlobalNew()) Out << "gs";4924Out << (New->isArray() ? "na" : "nw");4925for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),4926E = New->placement_arg_end(); I != E; ++I)4927mangleExpression(*I);4928Out << '_';4929mangleType(New->getAllocatedType());4930if (New->hasInitializer()) {4931if (New->getInitializationStyle() == CXXNewInitializationStyle::Braces)4932Out << "il";4933else4934Out << "pi";4935const Expr *Init = New->getInitializer();4936if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {4937// Directly inline the initializers.4938for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),4939E = CCE->arg_end();4940I != E; ++I)4941mangleExpression(*I);4942} else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {4943for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)4944mangleExpression(PLE->getExpr(i));4945} else if (New->getInitializationStyle() ==4946CXXNewInitializationStyle::Braces &&4947isa<InitListExpr>(Init)) {4948// Only take InitListExprs apart for list-initialization.4949mangleInitListElements(cast<InitListExpr>(Init));4950} else4951mangleExpression(Init);4952}4953Out << 'E';4954break;4955}49564957case Expr::CXXPseudoDestructorExprClass: {4958NotPrimaryExpr();4959const auto *PDE = cast<CXXPseudoDestructorExpr>(E);4960if (const Expr *Base = PDE->getBase())4961mangleMemberExprBase(Base, PDE->isArrow());4962NestedNameSpecifier *Qualifier = PDE->getQualifier();4963if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {4964if (Qualifier) {4965mangleUnresolvedPrefix(Qualifier,4966/*recursive=*/true);4967mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());4968Out << 'E';4969} else {4970Out << "sr";4971if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))4972Out << 'E';4973}4974} else if (Qualifier) {4975mangleUnresolvedPrefix(Qualifier);4976}4977// <base-unresolved-name> ::= dn <destructor-name>4978Out << "dn";4979QualType DestroyedType = PDE->getDestroyedType();4980mangleUnresolvedTypeOrSimpleId(DestroyedType);4981break;4982}49834984case Expr::MemberExprClass: {4985NotPrimaryExpr();4986const MemberExpr *ME = cast<MemberExpr>(E);4987mangleMemberExpr(ME->getBase(), ME->isArrow(),4988ME->getQualifier(), nullptr,4989ME->getMemberDecl()->getDeclName(),4990ME->getTemplateArgs(), ME->getNumTemplateArgs(),4991Arity);4992break;4993}49944995case Expr::UnresolvedMemberExprClass: {4996NotPrimaryExpr();4997const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);4998mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),4999ME->isArrow(), ME->getQualifier(), nullptr,5000ME->getMemberName(),5001ME->getTemplateArgs(), ME->getNumTemplateArgs(),5002Arity);5003break;5004}50055006case Expr::CXXDependentScopeMemberExprClass: {5007NotPrimaryExpr();5008const CXXDependentScopeMemberExpr *ME5009= cast<CXXDependentScopeMemberExpr>(E);5010mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),5011ME->isArrow(), ME->getQualifier(),5012ME->getFirstQualifierFoundInScope(),5013ME->getMember(),5014ME->getTemplateArgs(), ME->getNumTemplateArgs(),5015Arity);5016break;5017}50185019case Expr::UnresolvedLookupExprClass: {5020NotPrimaryExpr();5021const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);5022mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),5023ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),5024Arity);5025break;5026}50275028case Expr::CXXUnresolvedConstructExprClass: {5029NotPrimaryExpr();5030const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);5031unsigned N = CE->getNumArgs();50325033if (CE->isListInitialization()) {5034assert(N == 1 && "unexpected form for list initialization");5035auto *IL = cast<InitListExpr>(CE->getArg(0));5036Out << "tl";5037mangleType(CE->getType());5038mangleInitListElements(IL);5039Out << "E";5040break;5041}50425043Out << "cv";5044mangleType(CE->getType());5045if (N != 1) Out << '_';5046for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));5047if (N != 1) Out << 'E';5048break;5049}50505051case Expr::CXXConstructExprClass: {5052// An implicit cast is silent, thus may contain <expr-primary>.5053const auto *CE = cast<CXXConstructExpr>(E);5054if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {5055assert(5056CE->getNumArgs() >= 1 &&5057(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&5058"implicit CXXConstructExpr must have one argument");5059E = cast<CXXConstructExpr>(E)->getArg(0);5060goto recurse;5061}5062NotPrimaryExpr();5063Out << "il";5064for (auto *E : CE->arguments())5065mangleExpression(E);5066Out << "E";5067break;5068}50695070case Expr::CXXTemporaryObjectExprClass: {5071NotPrimaryExpr();5072const auto *CE = cast<CXXTemporaryObjectExpr>(E);5073unsigned N = CE->getNumArgs();5074bool List = CE->isListInitialization();50755076if (List)5077Out << "tl";5078else5079Out << "cv";5080mangleType(CE->getType());5081if (!List && N != 1)5082Out << '_';5083if (CE->isStdInitListInitialization()) {5084// We implicitly created a std::initializer_list<T> for the first argument5085// of a constructor of type U in an expression of the form U{a, b, c}.5086// Strip all the semantic gunk off the initializer list.5087auto *SILE =5088cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());5089auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());5090mangleInitListElements(ILE);5091} else {5092for (auto *E : CE->arguments())5093mangleExpression(E);5094}5095if (List || N != 1)5096Out << 'E';5097break;5098}50995100case Expr::CXXScalarValueInitExprClass:5101NotPrimaryExpr();5102Out << "cv";5103mangleType(E->getType());5104Out << "_E";5105break;51065107case Expr::CXXNoexceptExprClass:5108NotPrimaryExpr();5109Out << "nx";5110mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());5111break;51125113case Expr::UnaryExprOrTypeTraitExprClass: {5114// Non-instantiation-dependent traits are an <expr-primary> integer literal.5115const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);51165117if (!SAE->isInstantiationDependent()) {5118// Itanium C++ ABI:5119// If the operand of a sizeof or alignof operator is not5120// instantiation-dependent it is encoded as an integer literal5121// reflecting the result of the operator.5122//5123// If the result of the operator is implicitly converted to a known5124// integer type, that type is used for the literal; otherwise, the type5125// of std::size_t or std::ptrdiff_t is used.5126//5127// FIXME: We still include the operand in the profile in this case. This5128// can lead to mangling collisions between function templates that we5129// consider to be different.5130QualType T = (ImplicitlyConvertedToType.isNull() ||5131!ImplicitlyConvertedToType->isIntegerType())? SAE->getType()5132: ImplicitlyConvertedToType;5133llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());5134mangleIntegerLiteral(T, V);5135break;5136}51375138NotPrimaryExpr(); // But otherwise, they are not.51395140auto MangleAlignofSizeofArg = [&] {5141if (SAE->isArgumentType()) {5142Out << 't';5143mangleType(SAE->getArgumentType());5144} else {5145Out << 'z';5146mangleExpression(SAE->getArgumentExpr());5147}5148};51495150switch(SAE->getKind()) {5151case UETT_SizeOf:5152Out << 's';5153MangleAlignofSizeofArg();5154break;5155case UETT_PreferredAlignOf:5156// As of clang 12, we mangle __alignof__ differently than alignof. (They5157// have acted differently since Clang 8, but were previously mangled the5158// same.)5159if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {5160Out << "u11__alignof__";5161if (SAE->isArgumentType())5162mangleType(SAE->getArgumentType());5163else5164mangleTemplateArgExpr(SAE->getArgumentExpr());5165Out << 'E';5166break;5167}5168[[fallthrough]];5169case UETT_AlignOf:5170Out << 'a';5171MangleAlignofSizeofArg();5172break;5173case UETT_DataSizeOf: {5174DiagnosticsEngine &Diags = Context.getDiags();5175unsigned DiagID =5176Diags.getCustomDiagID(DiagnosticsEngine::Error,5177"cannot yet mangle __datasizeof expression");5178Diags.Report(DiagID);5179return;5180}5181case UETT_PtrAuthTypeDiscriminator: {5182DiagnosticsEngine &Diags = Context.getDiags();5183unsigned DiagID = Diags.getCustomDiagID(5184DiagnosticsEngine::Error,5185"cannot yet mangle __builtin_ptrauth_type_discriminator expression");5186Diags.Report(E->getExprLoc(), DiagID);5187return;5188}5189case UETT_VecStep: {5190DiagnosticsEngine &Diags = Context.getDiags();5191unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,5192"cannot yet mangle vec_step expression");5193Diags.Report(DiagID);5194return;5195}5196case UETT_OpenMPRequiredSimdAlign: {5197DiagnosticsEngine &Diags = Context.getDiags();5198unsigned DiagID = Diags.getCustomDiagID(5199DiagnosticsEngine::Error,5200"cannot yet mangle __builtin_omp_required_simd_align expression");5201Diags.Report(DiagID);5202return;5203}5204case UETT_VectorElements: {5205DiagnosticsEngine &Diags = Context.getDiags();5206unsigned DiagID = Diags.getCustomDiagID(5207DiagnosticsEngine::Error,5208"cannot yet mangle __builtin_vectorelements expression");5209Diags.Report(DiagID);5210return;5211}5212}5213break;5214}52155216case Expr::TypeTraitExprClass: {5217// <expression> ::= u <source-name> <template-arg>* E # vendor extension5218const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);5219NotPrimaryExpr();5220Out << 'u';5221llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());5222Out << Spelling.size() << Spelling;5223for (TypeSourceInfo *TSI : TTE->getArgs()) {5224mangleType(TSI->getType());5225}5226Out << 'E';5227break;5228}52295230case Expr::CXXThrowExprClass: {5231NotPrimaryExpr();5232const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);5233// <expression> ::= tw <expression> # throw expression5234// ::= tr # rethrow5235if (TE->getSubExpr()) {5236Out << "tw";5237mangleExpression(TE->getSubExpr());5238} else {5239Out << "tr";5240}5241break;5242}52435244case Expr::CXXTypeidExprClass: {5245NotPrimaryExpr();5246const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);5247// <expression> ::= ti <type> # typeid (type)5248// ::= te <expression> # typeid (expression)5249if (TIE->isTypeOperand()) {5250Out << "ti";5251mangleType(TIE->getTypeOperand(Context.getASTContext()));5252} else {5253Out << "te";5254mangleExpression(TIE->getExprOperand());5255}5256break;5257}52585259case Expr::CXXDeleteExprClass: {5260NotPrimaryExpr();5261const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);5262// <expression> ::= [gs] dl <expression> # [::] delete expr5263// ::= [gs] da <expression> # [::] delete [] expr5264if (DE->isGlobalDelete()) Out << "gs";5265Out << (DE->isArrayForm() ? "da" : "dl");5266mangleExpression(DE->getArgument());5267break;5268}52695270case Expr::UnaryOperatorClass: {5271NotPrimaryExpr();5272const UnaryOperator *UO = cast<UnaryOperator>(E);5273mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),5274/*Arity=*/1);5275mangleExpression(UO->getSubExpr());5276break;5277}52785279case Expr::ArraySubscriptExprClass: {5280NotPrimaryExpr();5281const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);52825283// Array subscript is treated as a syntactically weird form of5284// binary operator.5285Out << "ix";5286mangleExpression(AE->getLHS());5287mangleExpression(AE->getRHS());5288break;5289}52905291case Expr::MatrixSubscriptExprClass: {5292NotPrimaryExpr();5293const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);5294Out << "ixix";5295mangleExpression(ME->getBase());5296mangleExpression(ME->getRowIdx());5297mangleExpression(ME->getColumnIdx());5298break;5299}53005301case Expr::CompoundAssignOperatorClass: // fallthrough5302case Expr::BinaryOperatorClass: {5303NotPrimaryExpr();5304const BinaryOperator *BO = cast<BinaryOperator>(E);5305if (BO->getOpcode() == BO_PtrMemD)5306Out << "ds";5307else5308mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),5309/*Arity=*/2);5310mangleExpression(BO->getLHS());5311mangleExpression(BO->getRHS());5312break;5313}53145315case Expr::CXXRewrittenBinaryOperatorClass: {5316NotPrimaryExpr();5317// The mangled form represents the original syntax.5318CXXRewrittenBinaryOperator::DecomposedForm Decomposed =5319cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();5320mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),5321/*Arity=*/2);5322mangleExpression(Decomposed.LHS);5323mangleExpression(Decomposed.RHS);5324break;5325}53265327case Expr::ConditionalOperatorClass: {5328NotPrimaryExpr();5329const ConditionalOperator *CO = cast<ConditionalOperator>(E);5330mangleOperatorName(OO_Conditional, /*Arity=*/3);5331mangleExpression(CO->getCond());5332mangleExpression(CO->getLHS(), Arity);5333mangleExpression(CO->getRHS(), Arity);5334break;5335}53365337case Expr::ImplicitCastExprClass: {5338ImplicitlyConvertedToType = E->getType();5339E = cast<ImplicitCastExpr>(E)->getSubExpr();5340goto recurse;5341}53425343case Expr::ObjCBridgedCastExprClass: {5344NotPrimaryExpr();5345// Mangle ownership casts as a vendor extended operator __bridge,5346// __bridge_transfer, or __bridge_retain.5347StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();5348Out << "v1U" << Kind.size() << Kind;5349mangleCastExpression(E, "cv");5350break;5351}53525353case Expr::CStyleCastExprClass:5354NotPrimaryExpr();5355mangleCastExpression(E, "cv");5356break;53575358case Expr::CXXFunctionalCastExprClass: {5359NotPrimaryExpr();5360auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();5361// FIXME: Add isImplicit to CXXConstructExpr.5362if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))5363if (CCE->getParenOrBraceRange().isInvalid())5364Sub = CCE->getArg(0)->IgnoreImplicit();5365if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))5366Sub = StdInitList->getSubExpr()->IgnoreImplicit();5367if (auto *IL = dyn_cast<InitListExpr>(Sub)) {5368Out << "tl";5369mangleType(E->getType());5370mangleInitListElements(IL);5371Out << "E";5372} else {5373mangleCastExpression(E, "cv");5374}5375break;5376}53775378case Expr::CXXStaticCastExprClass:5379NotPrimaryExpr();5380mangleCastExpression(E, "sc");5381break;5382case Expr::CXXDynamicCastExprClass:5383NotPrimaryExpr();5384mangleCastExpression(E, "dc");5385break;5386case Expr::CXXReinterpretCastExprClass:5387NotPrimaryExpr();5388mangleCastExpression(E, "rc");5389break;5390case Expr::CXXConstCastExprClass:5391NotPrimaryExpr();5392mangleCastExpression(E, "cc");5393break;5394case Expr::CXXAddrspaceCastExprClass:5395NotPrimaryExpr();5396mangleCastExpression(E, "ac");5397break;53985399case Expr::CXXOperatorCallExprClass: {5400NotPrimaryExpr();5401const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);5402unsigned NumArgs = CE->getNumArgs();5403// A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax5404// (the enclosing MemberExpr covers the syntactic portion).5405if (CE->getOperator() != OO_Arrow)5406mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);5407// Mangle the arguments.5408for (unsigned i = 0; i != NumArgs; ++i)5409mangleExpression(CE->getArg(i));5410break;5411}54125413case Expr::ParenExprClass:5414E = cast<ParenExpr>(E)->getSubExpr();5415goto recurse;54165417case Expr::ConceptSpecializationExprClass: {5418auto *CSE = cast<ConceptSpecializationExpr>(E);5419if (isCompatibleWith(LangOptions::ClangABI::Ver17)) {5420// Clang 17 and before mangled concept-ids as if they resolved to an5421// entity, meaning that references to enclosing template arguments don't5422// work.5423Out << "L_Z";5424mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());5425Out << 'E';5426break;5427}5428// Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.5429NotPrimaryExpr();5430mangleUnresolvedName(5431CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),5432CSE->getConceptNameInfo().getName(),5433CSE->getTemplateArgsAsWritten()->getTemplateArgs(),5434CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());5435break;5436}54375438case Expr::RequiresExprClass: {5439// Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.5440auto *RE = cast<RequiresExpr>(E);5441// This is a primary-expression in the C++ grammar, but does not have an5442// <expr-primary> mangling (starting with 'L').5443NotPrimaryExpr();5444if (RE->getLParenLoc().isValid()) {5445Out << "rQ";5446FunctionTypeDepthState saved = FunctionTypeDepth.push();5447if (RE->getLocalParameters().empty()) {5448Out << 'v';5449} else {5450for (ParmVarDecl *Param : RE->getLocalParameters()) {5451mangleType(Context.getASTContext().getSignatureParameterType(5452Param->getType()));5453}5454}5455Out << '_';54565457// The rest of the mangling is in the immediate scope of the parameters.5458FunctionTypeDepth.enterResultType();5459for (const concepts::Requirement *Req : RE->getRequirements())5460mangleRequirement(RE->getExprLoc(), Req);5461FunctionTypeDepth.pop(saved);5462Out << 'E';5463} else {5464Out << "rq";5465for (const concepts::Requirement *Req : RE->getRequirements())5466mangleRequirement(RE->getExprLoc(), Req);5467Out << 'E';5468}5469break;5470}54715472case Expr::DeclRefExprClass:5473// MangleDeclRefExpr helper handles primary-vs-nonprimary5474MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());5475break;54765477case Expr::SubstNonTypeTemplateParmPackExprClass:5478NotPrimaryExpr();5479// FIXME: not clear how to mangle this!5480// template <unsigned N...> class A {5481// template <class U...> void foo(U (&x)[N]...);5482// };5483Out << "_SUBSTPACK_";5484break;54855486case Expr::FunctionParmPackExprClass: {5487NotPrimaryExpr();5488// FIXME: not clear how to mangle this!5489const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);5490Out << "v110_SUBSTPACK";5491MangleDeclRefExpr(FPPE->getParameterPack());5492break;5493}54945495case Expr::DependentScopeDeclRefExprClass: {5496NotPrimaryExpr();5497const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);5498mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),5499DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),5500Arity);5501break;5502}55035504case Expr::CXXBindTemporaryExprClass:5505E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();5506goto recurse;55075508case Expr::ExprWithCleanupsClass:5509E = cast<ExprWithCleanups>(E)->getSubExpr();5510goto recurse;55115512case Expr::FloatingLiteralClass: {5513// <expr-primary>5514const FloatingLiteral *FL = cast<FloatingLiteral>(E);5515mangleFloatLiteral(FL->getType(), FL->getValue());5516break;5517}55185519case Expr::FixedPointLiteralClass:5520// Currently unimplemented -- might be <expr-primary> in future?5521mangleFixedPointLiteral();5522break;55235524case Expr::CharacterLiteralClass:5525// <expr-primary>5526Out << 'L';5527mangleType(E->getType());5528Out << cast<CharacterLiteral>(E)->getValue();5529Out << 'E';5530break;55315532// FIXME. __objc_yes/__objc_no are mangled same as true/false5533case Expr::ObjCBoolLiteralExprClass:5534// <expr-primary>5535Out << "Lb";5536Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');5537Out << 'E';5538break;55395540case Expr::CXXBoolLiteralExprClass:5541// <expr-primary>5542Out << "Lb";5543Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');5544Out << 'E';5545break;55465547case Expr::IntegerLiteralClass: {5548// <expr-primary>5549llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());5550if (E->getType()->isSignedIntegerType())5551Value.setIsSigned(true);5552mangleIntegerLiteral(E->getType(), Value);5553break;5554}55555556case Expr::ImaginaryLiteralClass: {5557// <expr-primary>5558const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);5559// Mangle as if a complex literal.5560// Proposal from David Vandevoorde, 2010.06.30.5561Out << 'L';5562mangleType(E->getType());5563if (const FloatingLiteral *Imag =5564dyn_cast<FloatingLiteral>(IE->getSubExpr())) {5565// Mangle a floating-point zero of the appropriate type.5566mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));5567Out << '_';5568mangleFloat(Imag->getValue());5569} else {5570Out << "0_";5571llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());5572if (IE->getSubExpr()->getType()->isSignedIntegerType())5573Value.setIsSigned(true);5574mangleNumber(Value);5575}5576Out << 'E';5577break;5578}55795580case Expr::StringLiteralClass: {5581// <expr-primary>5582// Revised proposal from David Vandervoorde, 2010.07.15.5583Out << 'L';5584assert(isa<ConstantArrayType>(E->getType()));5585mangleType(E->getType());5586Out << 'E';5587break;5588}55895590case Expr::GNUNullExprClass:5591// <expr-primary>5592// Mangle as if an integer literal 0.5593mangleIntegerLiteral(E->getType(), llvm::APSInt(32));5594break;55955596case Expr::CXXNullPtrLiteralExprClass: {5597// <expr-primary>5598Out << "LDnE";5599break;5600}56015602case Expr::LambdaExprClass: {5603// A lambda-expression can't appear in the signature of an5604// externally-visible declaration, so there's no standard mangling for5605// this, but mangling as a literal of the closure type seems reasonable.5606Out << "L";5607mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));5608Out << "E";5609break;5610}56115612case Expr::PackExpansionExprClass:5613NotPrimaryExpr();5614Out << "sp";5615mangleExpression(cast<PackExpansionExpr>(E)->getPattern());5616break;56175618case Expr::SizeOfPackExprClass: {5619NotPrimaryExpr();5620auto *SPE = cast<SizeOfPackExpr>(E);5621if (SPE->isPartiallySubstituted()) {5622Out << "sP";5623for (const auto &A : SPE->getPartialArguments())5624mangleTemplateArg(A, false);5625Out << "E";5626break;5627}56285629Out << "sZ";5630const NamedDecl *Pack = SPE->getPack();5631if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))5632mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());5633else if (const NonTypeTemplateParmDecl *NTTP5634= dyn_cast<NonTypeTemplateParmDecl>(Pack))5635mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());5636else if (const TemplateTemplateParmDecl *TempTP5637= dyn_cast<TemplateTemplateParmDecl>(Pack))5638mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());5639else5640mangleFunctionParam(cast<ParmVarDecl>(Pack));5641break;5642}56435644case Expr::MaterializeTemporaryExprClass:5645E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();5646goto recurse;56475648case Expr::CXXFoldExprClass: {5649NotPrimaryExpr();5650auto *FE = cast<CXXFoldExpr>(E);5651if (FE->isLeftFold())5652Out << (FE->getInit() ? "fL" : "fl");5653else5654Out << (FE->getInit() ? "fR" : "fr");56555656if (FE->getOperator() == BO_PtrMemD)5657Out << "ds";5658else5659mangleOperatorName(5660BinaryOperator::getOverloadedOperator(FE->getOperator()),5661/*Arity=*/2);56625663if (FE->getLHS())5664mangleExpression(FE->getLHS());5665if (FE->getRHS())5666mangleExpression(FE->getRHS());5667break;5668}56695670case Expr::CXXThisExprClass:5671NotPrimaryExpr();5672Out << "fpT";5673break;56745675case Expr::CoawaitExprClass:5676// FIXME: Propose a non-vendor mangling.5677NotPrimaryExpr();5678Out << "v18co_await";5679mangleExpression(cast<CoawaitExpr>(E)->getOperand());5680break;56815682case Expr::DependentCoawaitExprClass:5683// FIXME: Propose a non-vendor mangling.5684NotPrimaryExpr();5685Out << "v18co_await";5686mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());5687break;56885689case Expr::CoyieldExprClass:5690// FIXME: Propose a non-vendor mangling.5691NotPrimaryExpr();5692Out << "v18co_yield";5693mangleExpression(cast<CoawaitExpr>(E)->getOperand());5694break;5695case Expr::SYCLUniqueStableNameExprClass: {5696const auto *USN = cast<SYCLUniqueStableNameExpr>(E);5697NotPrimaryExpr();56985699Out << "u33__builtin_sycl_unique_stable_name";5700mangleType(USN->getTypeSourceInfo()->getType());57015702Out << "E";5703break;5704}5705}57065707if (AsTemplateArg && !IsPrimaryExpr)5708Out << 'E';5709}57105711/// Mangle an expression which refers to a parameter variable.5712///5713/// <expression> ::= <function-param>5714/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 05715/// <function-param> ::= fp <top-level CV-qualifiers>5716/// <parameter-2 non-negative number> _ # L == 0, I > 05717/// <function-param> ::= fL <L-1 non-negative number>5718/// p <top-level CV-qualifiers> _ # L > 0, I == 05719/// <function-param> ::= fL <L-1 non-negative number>5720/// p <top-level CV-qualifiers>5721/// <I-1 non-negative number> _ # L > 0, I > 05722///5723/// L is the nesting depth of the parameter, defined as 1 if the5724/// parameter comes from the innermost function prototype scope5725/// enclosing the current context, 2 if from the next enclosing5726/// function prototype scope, and so on, with one special case: if5727/// we've processed the full parameter clause for the innermost5728/// function type, then L is one less. This definition conveniently5729/// makes it irrelevant whether a function's result type was written5730/// trailing or leading, but is otherwise overly complicated; the5731/// numbering was first designed without considering references to5732/// parameter in locations other than return types, and then the5733/// mangling had to be generalized without changing the existing5734/// manglings.5735///5736/// I is the zero-based index of the parameter within its parameter5737/// declaration clause. Note that the original ABI document describes5738/// this using 1-based ordinals.5739void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {5740unsigned parmDepth = parm->getFunctionScopeDepth();5741unsigned parmIndex = parm->getFunctionScopeIndex();57425743// Compute 'L'.5744// parmDepth does not include the declaring function prototype.5745// FunctionTypeDepth does account for that.5746assert(parmDepth < FunctionTypeDepth.getDepth());5747unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;5748if (FunctionTypeDepth.isInResultType())5749nestingDepth--;57505751if (nestingDepth == 0) {5752Out << "fp";5753} else {5754Out << "fL" << (nestingDepth - 1) << 'p';5755}57565757// Top-level qualifiers. We don't have to worry about arrays here,5758// because parameters declared as arrays should already have been5759// transformed to have pointer type. FIXME: apparently these don't5760// get mangled if used as an rvalue of a known non-class type?5761assert(!parm->getType()->isArrayType()5762&& "parameter's type is still an array type?");57635764if (const DependentAddressSpaceType *DAST =5765dyn_cast<DependentAddressSpaceType>(parm->getType())) {5766mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);5767} else {5768mangleQualifiers(parm->getType().getQualifiers());5769}57705771// Parameter index.5772if (parmIndex != 0) {5773Out << (parmIndex - 1);5774}5775Out << '_';5776}57775778void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,5779const CXXRecordDecl *InheritedFrom) {5780// <ctor-dtor-name> ::= C1 # complete object constructor5781// ::= C2 # base object constructor5782// ::= CI1 <type> # complete inheriting constructor5783// ::= CI2 <type> # base inheriting constructor5784//5785// In addition, C5 is a comdat name with C1 and C2 in it.5786Out << 'C';5787if (InheritedFrom)5788Out << 'I';5789switch (T) {5790case Ctor_Complete:5791Out << '1';5792break;5793case Ctor_Base:5794Out << '2';5795break;5796case Ctor_Comdat:5797Out << '5';5798break;5799case Ctor_DefaultClosure:5800case Ctor_CopyingClosure:5801llvm_unreachable("closure constructors don't exist for the Itanium ABI!");5802}5803if (InheritedFrom)5804mangleName(InheritedFrom);5805}58065807void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {5808// <ctor-dtor-name> ::= D0 # deleting destructor5809// ::= D1 # complete object destructor5810// ::= D2 # base object destructor5811//5812// In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.5813switch (T) {5814case Dtor_Deleting:5815Out << "D0";5816break;5817case Dtor_Complete:5818Out << "D1";5819break;5820case Dtor_Base:5821Out << "D2";5822break;5823case Dtor_Comdat:5824Out << "D5";5825break;5826}5827}58285829// Helper to provide ancillary information on a template used to mangle its5830// arguments.5831struct CXXNameMangler::TemplateArgManglingInfo {5832const CXXNameMangler &Mangler;5833TemplateDecl *ResolvedTemplate = nullptr;5834bool SeenPackExpansionIntoNonPack = false;5835const NamedDecl *UnresolvedExpandedPack = nullptr;58365837TemplateArgManglingInfo(const CXXNameMangler &Mangler, TemplateName TN)5838: Mangler(Mangler) {5839if (TemplateDecl *TD = TN.getAsTemplateDecl())5840ResolvedTemplate = TD;5841}58425843/// Information about how to mangle a template argument.5844struct Info {5845/// Do we need to mangle the template argument with an exactly correct type?5846bool NeedExactType;5847/// If we need to prefix the mangling with a mangling of the template5848/// parameter, the corresponding parameter.5849const NamedDecl *TemplateParameterToMangle;5850};58515852/// Determine whether the resolved template might be overloaded on its5853/// template parameter list. If so, the mangling needs to include enough5854/// information to reconstruct the template parameter list.5855bool isOverloadable() {5856// Function templates are generally overloadable. As a special case, a5857// member function template of a generic lambda is not overloadable.5858if (auto *FTD = dyn_cast_or_null<FunctionTemplateDecl>(ResolvedTemplate)) {5859auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());5860if (!RD || !RD->isGenericLambda())5861return true;5862}58635864// All other templates are not overloadable. Partial specializations would5865// be, but we never mangle them.5866return false;5867}58685869/// Determine whether we need to prefix this <template-arg> mangling with a5870/// <template-param-decl>. This happens if the natural template parameter for5871/// the argument mangling is not the same as the actual template parameter.5872bool needToMangleTemplateParam(const NamedDecl *Param,5873const TemplateArgument &Arg) {5874// For a template type parameter, the natural parameter is 'typename T'.5875// The actual parameter might be constrained.5876if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))5877return TTP->hasTypeConstraint();58785879if (Arg.getKind() == TemplateArgument::Pack) {5880// For an empty pack, the natural parameter is `typename...`.5881if (Arg.pack_size() == 0)5882return true;58835884// For any other pack, we use the first argument to determine the natural5885// template parameter.5886return needToMangleTemplateParam(Param, *Arg.pack_begin());5887}58885889// For a non-type template parameter, the natural parameter is `T V` (for a5890// prvalue argument) or `T &V` (for a glvalue argument), where `T` is the5891// type of the argument, which we require to exactly match. If the actual5892// parameter has a deduced or instantiation-dependent type, it is not5893// equivalent to the natural parameter.5894if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))5895return NTTP->getType()->isInstantiationDependentType() ||5896NTTP->getType()->getContainedDeducedType();58975898// For a template template parameter, the template-head might differ from5899// that of the template.5900auto *TTP = cast<TemplateTemplateParmDecl>(Param);5901TemplateName ArgTemplateName = Arg.getAsTemplateOrTemplatePattern();5902const TemplateDecl *ArgTemplate = ArgTemplateName.getAsTemplateDecl();5903if (!ArgTemplate)5904return true;59055906// Mangle the template parameter list of the parameter and argument to see5907// if they are the same. We can't use Profile for this, because it can't5908// model the depth difference between parameter and argument and might not5909// necessarily have the same definition of "identical" that we use here --5910// that is, same mangling.5911auto MangleTemplateParamListToString =5912[&](SmallVectorImpl<char> &Buffer, const TemplateParameterList *Params,5913unsigned DepthOffset) {5914llvm::raw_svector_ostream Stream(Buffer);5915CXXNameMangler(Mangler.Context, Stream,5916WithTemplateDepthOffset{DepthOffset})5917.mangleTemplateParameterList(Params);5918};5919llvm::SmallString<128> ParamTemplateHead, ArgTemplateHead;5920MangleTemplateParamListToString(ParamTemplateHead,5921TTP->getTemplateParameters(), 0);5922// Add the depth of the parameter's template parameter list to all5923// parameters appearing in the argument to make the indexes line up5924// properly.5925MangleTemplateParamListToString(ArgTemplateHead,5926ArgTemplate->getTemplateParameters(),5927TTP->getTemplateParameters()->getDepth());5928return ParamTemplateHead != ArgTemplateHead;5929}59305931/// Determine information about how this template argument should be mangled.5932/// This should be called exactly once for each parameter / argument pair, in5933/// order.5934Info getArgInfo(unsigned ParamIdx, const TemplateArgument &Arg) {5935// We need correct types when the template-name is unresolved or when it5936// names a template that is able to be overloaded.5937if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)5938return {true, nullptr};59395940// Move to the next parameter.5941const NamedDecl *Param = UnresolvedExpandedPack;5942if (!Param) {5943assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&5944"no parameter for argument");5945Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);59465947// If we reach a parameter pack whose argument isn't in pack form, that5948// means Sema couldn't or didn't figure out which arguments belonged to5949// it, because it contains a pack expansion or because Sema bailed out of5950// computing parameter / argument correspondence before this point. Track5951// the pack as the corresponding parameter for all further template5952// arguments until we hit a pack expansion, at which point we don't know5953// the correspondence between parameters and arguments at all.5954if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {5955UnresolvedExpandedPack = Param;5956}5957}59585959// If we encounter a pack argument that is expanded into a non-pack5960// parameter, we can no longer track parameter / argument correspondence,5961// and need to use exact types from this point onwards.5962if (Arg.isPackExpansion() &&5963(!Param->isParameterPack() || UnresolvedExpandedPack)) {5964SeenPackExpansionIntoNonPack = true;5965return {true, nullptr};5966}59675968// We need exact types for arguments of a template that might be overloaded5969// on template parameter type.5970if (isOverloadable())5971return {true, needToMangleTemplateParam(Param, Arg) ? Param : nullptr};59725973// Otherwise, we only need a correct type if the parameter has a deduced5974// type.5975//5976// Note: for an expanded parameter pack, getType() returns the type prior5977// to expansion. We could ask for the expanded type with getExpansionType(),5978// but it doesn't matter because substitution and expansion don't affect5979// whether a deduced type appears in the type.5980auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);5981bool NeedExactType = NTTP && NTTP->getType()->getContainedDeducedType();5982return {NeedExactType, nullptr};5983}59845985/// Determine if we should mangle a requires-clause after the template5986/// argument list. If so, returns the expression to mangle.5987const Expr *getTrailingRequiresClauseToMangle() {5988if (!isOverloadable())5989return nullptr;5990return ResolvedTemplate->getTemplateParameters()->getRequiresClause();5991}5992};59935994void CXXNameMangler::mangleTemplateArgs(TemplateName TN,5995const TemplateArgumentLoc *TemplateArgs,5996unsigned NumTemplateArgs) {5997// <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E5998Out << 'I';5999TemplateArgManglingInfo Info(*this, TN);6000for (unsigned i = 0; i != NumTemplateArgs; ++i) {6001mangleTemplateArg(Info, i, TemplateArgs[i].getArgument());6002}6003mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());6004Out << 'E';6005}60066007void CXXNameMangler::mangleTemplateArgs(TemplateName TN,6008const TemplateArgumentList &AL) {6009// <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E6010Out << 'I';6011TemplateArgManglingInfo Info(*this, TN);6012for (unsigned i = 0, e = AL.size(); i != e; ++i) {6013mangleTemplateArg(Info, i, AL[i]);6014}6015mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());6016Out << 'E';6017}60186019void CXXNameMangler::mangleTemplateArgs(TemplateName TN,6020ArrayRef<TemplateArgument> Args) {6021// <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E6022Out << 'I';6023TemplateArgManglingInfo Info(*this, TN);6024for (unsigned i = 0; i != Args.size(); ++i) {6025mangleTemplateArg(Info, i, Args[i]);6026}6027mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());6028Out << 'E';6029}60306031void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo &Info,6032unsigned Index, TemplateArgument A) {6033TemplateArgManglingInfo::Info ArgInfo = Info.getArgInfo(Index, A);60346035// Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.6036if (ArgInfo.TemplateParameterToMangle &&6037!isCompatibleWith(LangOptions::ClangABI::Ver17)) {6038// The template parameter is mangled if the mangling would otherwise be6039// ambiguous.6040//6041// <template-arg> ::= <template-param-decl> <template-arg>6042//6043// Clang 17 and before did not do this.6044mangleTemplateParamDecl(ArgInfo.TemplateParameterToMangle);6045}60466047mangleTemplateArg(A, ArgInfo.NeedExactType);6048}60496050void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {6051// <template-arg> ::= <type> # type or template6052// ::= X <expression> E # expression6053// ::= <expr-primary> # simple expressions6054// ::= J <template-arg>* E # argument pack6055if (!A.isInstantiationDependent() || A.isDependent())6056A = Context.getASTContext().getCanonicalTemplateArgument(A);60576058switch (A.getKind()) {6059case TemplateArgument::Null:6060llvm_unreachable("Cannot mangle NULL template argument");60616062case TemplateArgument::Type:6063mangleType(A.getAsType());6064break;6065case TemplateArgument::Template:6066// This is mangled as <type>.6067mangleType(A.getAsTemplate());6068break;6069case TemplateArgument::TemplateExpansion:6070// <type> ::= Dp <type> # pack expansion (C++0x)6071Out << "Dp";6072mangleType(A.getAsTemplateOrTemplatePattern());6073break;6074case TemplateArgument::Expression:6075mangleTemplateArgExpr(A.getAsExpr());6076break;6077case TemplateArgument::Integral:6078mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());6079break;6080case TemplateArgument::Declaration: {6081// <expr-primary> ::= L <mangled-name> E # external name6082ValueDecl *D = A.getAsDecl();60836084// Template parameter objects are modeled by reproducing a source form6085// produced as if by aggregate initialization.6086if (A.getParamTypeForDecl()->isRecordType()) {6087auto *TPO = cast<TemplateParamObjectDecl>(D);6088mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),6089TPO->getValue(), /*TopLevel=*/true,6090NeedExactType);6091break;6092}60936094ASTContext &Ctx = Context.getASTContext();6095APValue Value;6096if (D->isCXXInstanceMember())6097// Simple pointer-to-member with no conversion.6098Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});6099else if (D->getType()->isArrayType() &&6100Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),6101A.getParamTypeForDecl()) &&6102!isCompatibleWith(LangOptions::ClangABI::Ver11))6103// Build a value corresponding to this implicit array-to-pointer decay.6104Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),6105{APValue::LValuePathEntry::ArrayIndex(0)},6106/*OnePastTheEnd=*/false);6107else6108// Regular pointer or reference to a declaration.6109Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),6110ArrayRef<APValue::LValuePathEntry>(),6111/*OnePastTheEnd=*/false);6112mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,6113NeedExactType);6114break;6115}6116case TemplateArgument::NullPtr: {6117mangleNullPointer(A.getNullPtrType());6118break;6119}6120case TemplateArgument::StructuralValue:6121mangleValueInTemplateArg(A.getStructuralValueType(),6122A.getAsStructuralValue(),6123/*TopLevel=*/true, NeedExactType);6124break;6125case TemplateArgument::Pack: {6126// <template-arg> ::= J <template-arg>* E6127Out << 'J';6128for (const auto &P : A.pack_elements())6129mangleTemplateArg(P, NeedExactType);6130Out << 'E';6131}6132}6133}61346135void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {6136if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {6137mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);6138return;6139}61406141// Prior to Clang 12, we didn't omit the X .. E around <expr-primary>6142// correctly in cases where the template argument was6143// constructed from an expression rather than an already-evaluated6144// literal. In such a case, we would then e.g. emit 'XLi0EE' instead of6145// 'Li0E'.6146//6147// We did special-case DeclRefExpr to attempt to DTRT for that one6148// expression-kind, but while doing so, unfortunately handled ParmVarDecl6149// (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of6150// the proper 'Xfp_E'.6151E = E->IgnoreParenImpCasts();6152if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {6153const ValueDecl *D = DRE->getDecl();6154if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {6155Out << 'L';6156mangle(D);6157Out << 'E';6158return;6159}6160}6161Out << 'X';6162mangleExpression(E);6163Out << 'E';6164}61656166/// Determine whether a given value is equivalent to zero-initialization for6167/// the purpose of discarding a trailing portion of a 'tl' mangling.6168///6169/// Note that this is not in general equivalent to determining whether the6170/// value has an all-zeroes bit pattern.6171static bool isZeroInitialized(QualType T, const APValue &V) {6172// FIXME: mangleValueInTemplateArg has quadratic time complexity in6173// pathological cases due to using this, but it's a little awkward6174// to do this in linear time in general.6175switch (V.getKind()) {6176case APValue::None:6177case APValue::Indeterminate:6178case APValue::AddrLabelDiff:6179return false;61806181case APValue::Struct: {6182const CXXRecordDecl *RD = T->getAsCXXRecordDecl();6183assert(RD && "unexpected type for record value");6184unsigned I = 0;6185for (const CXXBaseSpecifier &BS : RD->bases()) {6186if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))6187return false;6188++I;6189}6190I = 0;6191for (const FieldDecl *FD : RD->fields()) {6192if (!FD->isUnnamedBitField() &&6193!isZeroInitialized(FD->getType(), V.getStructField(I)))6194return false;6195++I;6196}6197return true;6198}61996200case APValue::Union: {6201const CXXRecordDecl *RD = T->getAsCXXRecordDecl();6202assert(RD && "unexpected type for union value");6203// Zero-initialization zeroes the first non-unnamed-bitfield field, if any.6204for (const FieldDecl *FD : RD->fields()) {6205if (!FD->isUnnamedBitField())6206return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&6207isZeroInitialized(FD->getType(), V.getUnionValue());6208}6209// If there are no fields (other than unnamed bitfields), the value is6210// necessarily zero-initialized.6211return true;6212}62136214case APValue::Array: {6215QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);6216for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)6217if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))6218return false;6219return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());6220}62216222case APValue::Vector: {6223const VectorType *VT = T->castAs<VectorType>();6224for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)6225if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))6226return false;6227return true;6228}62296230case APValue::Int:6231return !V.getInt();62326233case APValue::Float:6234return V.getFloat().isPosZero();62356236case APValue::FixedPoint:6237return !V.getFixedPoint().getValue();62386239case APValue::ComplexFloat:6240return V.getComplexFloatReal().isPosZero() &&6241V.getComplexFloatImag().isPosZero();62426243case APValue::ComplexInt:6244return !V.getComplexIntReal() && !V.getComplexIntImag();62456246case APValue::LValue:6247return V.isNullPointer();62486249case APValue::MemberPointer:6250return !V.getMemberPointerDecl();6251}62526253llvm_unreachable("Unhandled APValue::ValueKind enum");6254}62556256static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {6257QualType T = LV.getLValueBase().getType();6258for (APValue::LValuePathEntry E : LV.getLValuePath()) {6259if (const ArrayType *AT = Ctx.getAsArrayType(T))6260T = AT->getElementType();6261else if (const FieldDecl *FD =6262dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))6263T = FD->getType();6264else6265T = Ctx.getRecordType(6266cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));6267}6268return T;6269}62706271static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,6272DiagnosticsEngine &Diags,6273const FieldDecl *FD) {6274// According to:6275// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous6276// For the purposes of mangling, the name of an anonymous union is considered6277// to be the name of the first named data member found by a pre-order,6278// depth-first, declaration-order walk of the data members of the anonymous6279// union.62806281if (FD->getIdentifier())6282return FD->getIdentifier();62836284// The only cases where the identifer of a FieldDecl would be blank is if the6285// field represents an anonymous record type or if it is an unnamed bitfield.6286// There is no type to descend into in the case of a bitfield, so we can just6287// return nullptr in that case.6288if (FD->isBitField())6289return nullptr;6290const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();62916292// Consider only the fields in declaration order, searched depth-first. We6293// don't care about the active member of the union, as all we are doing is6294// looking for a valid name. We also don't check bases, due to guidance from6295// the Itanium ABI folks.6296for (const FieldDecl *RDField : RD->fields()) {6297if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))6298return II;6299}63006301// According to the Itanium ABI: If there is no such data member (i.e., if all6302// of the data members in the union are unnamed), then there is no way for a6303// program to refer to the anonymous union, and there is therefore no need to6304// mangle its name. However, we should diagnose this anyway.6305unsigned DiagID = Diags.getCustomDiagID(6306DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");6307Diags.Report(UnionLoc, DiagID);63086309return nullptr;6310}63116312void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,6313bool TopLevel,6314bool NeedExactType) {6315// Ignore all top-level cv-qualifiers, to match GCC.6316Qualifiers Quals;6317T = getASTContext().getUnqualifiedArrayType(T, Quals);63186319// A top-level expression that's not a primary expression is wrapped in X...E.6320bool IsPrimaryExpr = true;6321auto NotPrimaryExpr = [&] {6322if (TopLevel && IsPrimaryExpr)6323Out << 'X';6324IsPrimaryExpr = false;6325};63266327// Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.6328switch (V.getKind()) {6329case APValue::None:6330case APValue::Indeterminate:6331Out << 'L';6332mangleType(T);6333Out << 'E';6334break;63356336case APValue::AddrLabelDiff:6337llvm_unreachable("unexpected value kind in template argument");63386339case APValue::Struct: {6340const CXXRecordDecl *RD = T->getAsCXXRecordDecl();6341assert(RD && "unexpected type for record value");63426343// Drop trailing zero-initialized elements.6344llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());6345while (6346!Fields.empty() &&6347(Fields.back()->isUnnamedBitField() ||6348isZeroInitialized(Fields.back()->getType(),6349V.getStructField(Fields.back()->getFieldIndex())))) {6350Fields.pop_back();6351}6352llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());6353if (Fields.empty()) {6354while (!Bases.empty() &&6355isZeroInitialized(Bases.back().getType(),6356V.getStructBase(Bases.size() - 1)))6357Bases = Bases.drop_back();6358}63596360// <expression> ::= tl <type> <braced-expression>* E6361NotPrimaryExpr();6362Out << "tl";6363mangleType(T);6364for (unsigned I = 0, N = Bases.size(); I != N; ++I)6365mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);6366for (unsigned I = 0, N = Fields.size(); I != N; ++I) {6367if (Fields[I]->isUnnamedBitField())6368continue;6369mangleValueInTemplateArg(Fields[I]->getType(),6370V.getStructField(Fields[I]->getFieldIndex()),6371false);6372}6373Out << 'E';6374break;6375}63766377case APValue::Union: {6378assert(T->getAsCXXRecordDecl() && "unexpected type for union value");6379const FieldDecl *FD = V.getUnionField();63806381if (!FD) {6382Out << 'L';6383mangleType(T);6384Out << 'E';6385break;6386}63876388// <braced-expression> ::= di <field source-name> <braced-expression>6389NotPrimaryExpr();6390Out << "tl";6391mangleType(T);6392if (!isZeroInitialized(T, V)) {6393Out << "di";6394IdentifierInfo *II = (getUnionInitName(6395T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));6396if (II)6397mangleSourceName(II);6398mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);6399}6400Out << 'E';6401break;6402}64036404case APValue::Array: {6405QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);64066407NotPrimaryExpr();6408Out << "tl";6409mangleType(T);64106411// Drop trailing zero-initialized elements.6412unsigned N = V.getArraySize();6413if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {6414N = V.getArrayInitializedElts();6415while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))6416--N;6417}64186419for (unsigned I = 0; I != N; ++I) {6420const APValue &Elem = I < V.getArrayInitializedElts()6421? V.getArrayInitializedElt(I)6422: V.getArrayFiller();6423mangleValueInTemplateArg(ElemT, Elem, false);6424}6425Out << 'E';6426break;6427}64286429case APValue::Vector: {6430const VectorType *VT = T->castAs<VectorType>();64316432NotPrimaryExpr();6433Out << "tl";6434mangleType(T);6435unsigned N = V.getVectorLength();6436while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))6437--N;6438for (unsigned I = 0; I != N; ++I)6439mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);6440Out << 'E';6441break;6442}64436444case APValue::Int:6445mangleIntegerLiteral(T, V.getInt());6446break;64476448case APValue::Float:6449mangleFloatLiteral(T, V.getFloat());6450break;64516452case APValue::FixedPoint:6453mangleFixedPointLiteral();6454break;64556456case APValue::ComplexFloat: {6457const ComplexType *CT = T->castAs<ComplexType>();6458NotPrimaryExpr();6459Out << "tl";6460mangleType(T);6461if (!V.getComplexFloatReal().isPosZero() ||6462!V.getComplexFloatImag().isPosZero())6463mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());6464if (!V.getComplexFloatImag().isPosZero())6465mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());6466Out << 'E';6467break;6468}64696470case APValue::ComplexInt: {6471const ComplexType *CT = T->castAs<ComplexType>();6472NotPrimaryExpr();6473Out << "tl";6474mangleType(T);6475if (V.getComplexIntReal().getBoolValue() ||6476V.getComplexIntImag().getBoolValue())6477mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());6478if (V.getComplexIntImag().getBoolValue())6479mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());6480Out << 'E';6481break;6482}64836484case APValue::LValue: {6485// Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.6486assert((T->isPointerType() || T->isReferenceType()) &&6487"unexpected type for LValue template arg");64886489if (V.isNullPointer()) {6490mangleNullPointer(T);6491break;6492}64936494APValue::LValueBase B = V.getLValueBase();6495if (!B) {6496// Non-standard mangling for integer cast to a pointer; this can only6497// occur as an extension.6498CharUnits Offset = V.getLValueOffset();6499if (Offset.isZero()) {6500// This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as6501// a cast, because L <type> 0 E means something else.6502NotPrimaryExpr();6503Out << "rc";6504mangleType(T);6505Out << "Li0E";6506if (TopLevel)6507Out << 'E';6508} else {6509Out << "L";6510mangleType(T);6511Out << Offset.getQuantity() << 'E';6512}6513break;6514}65156516ASTContext &Ctx = Context.getASTContext();65176518enum { Base, Offset, Path } Kind;6519if (!V.hasLValuePath()) {6520// Mangle as (T*)((char*)&base + N).6521if (T->isReferenceType()) {6522NotPrimaryExpr();6523Out << "decvP";6524mangleType(T->getPointeeType());6525} else {6526NotPrimaryExpr();6527Out << "cv";6528mangleType(T);6529}6530Out << "plcvPcad";6531Kind = Offset;6532} else {6533// Clang 11 and before mangled an array subject to array-to-pointer decay6534// as if it were the declaration itself.6535bool IsArrayToPointerDecayMangledAsDecl = false;6536if (TopLevel && Ctx.getLangOpts().getClangABICompat() <=6537LangOptions::ClangABI::Ver11) {6538QualType BType = B.getType();6539IsArrayToPointerDecayMangledAsDecl =6540BType->isArrayType() && V.getLValuePath().size() == 1 &&6541V.getLValuePath()[0].getAsArrayIndex() == 0 &&6542Ctx.hasSimilarType(T, Ctx.getDecayedType(BType));6543}65446545if ((!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) &&6546!IsArrayToPointerDecayMangledAsDecl) {6547NotPrimaryExpr();6548// A final conversion to the template parameter's type is usually6549// folded into the 'so' mangling, but we can't do that for 'void*'6550// parameters without introducing collisions.6551if (NeedExactType && T->isVoidPointerType()) {6552Out << "cv";6553mangleType(T);6554}6555if (T->isPointerType())6556Out << "ad";6557Out << "so";6558mangleType(T->isVoidPointerType()6559? getLValueType(Ctx, V).getUnqualifiedType()6560: T->getPointeeType());6561Kind = Path;6562} else {6563if (NeedExactType &&6564!Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&6565!isCompatibleWith(LangOptions::ClangABI::Ver11)) {6566NotPrimaryExpr();6567Out << "cv";6568mangleType(T);6569}6570if (T->isPointerType()) {6571NotPrimaryExpr();6572Out << "ad";6573}6574Kind = Base;6575}6576}65776578QualType TypeSoFar = B.getType();6579if (auto *VD = B.dyn_cast<const ValueDecl*>()) {6580Out << 'L';6581mangle(VD);6582Out << 'E';6583} else if (auto *E = B.dyn_cast<const Expr*>()) {6584NotPrimaryExpr();6585mangleExpression(E);6586} else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {6587NotPrimaryExpr();6588Out << "ti";6589mangleType(QualType(TI.getType(), 0));6590} else {6591// We should never see dynamic allocations here.6592llvm_unreachable("unexpected lvalue base kind in template argument");6593}65946595switch (Kind) {6596case Base:6597break;65986599case Offset:6600Out << 'L';6601mangleType(Ctx.getPointerDiffType());6602mangleNumber(V.getLValueOffset().getQuantity());6603Out << 'E';6604break;66056606case Path:6607// <expression> ::= so <referent type> <expr> [<offset number>]6608// <union-selector>* [p] E6609if (!V.getLValueOffset().isZero())6610mangleNumber(V.getLValueOffset().getQuantity());66116612// We model a past-the-end array pointer as array indexing with index N,6613// not with the "past the end" flag. Compensate for that.6614bool OnePastTheEnd = V.isLValueOnePastTheEnd();66156616for (APValue::LValuePathEntry E : V.getLValuePath()) {6617if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {6618if (auto *CAT = dyn_cast<ConstantArrayType>(AT))6619OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();6620TypeSoFar = AT->getElementType();6621} else {6622const Decl *D = E.getAsBaseOrMember().getPointer();6623if (auto *FD = dyn_cast<FieldDecl>(D)) {6624// <union-selector> ::= _ <number>6625if (FD->getParent()->isUnion()) {6626Out << '_';6627if (FD->getFieldIndex())6628Out << (FD->getFieldIndex() - 1);6629}6630TypeSoFar = FD->getType();6631} else {6632TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));6633}6634}6635}66366637if (OnePastTheEnd)6638Out << 'p';6639Out << 'E';6640break;6641}66426643break;6644}66456646case APValue::MemberPointer:6647// Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.6648if (!V.getMemberPointerDecl()) {6649mangleNullPointer(T);6650break;6651}66526653ASTContext &Ctx = Context.getASTContext();66546655NotPrimaryExpr();6656if (!V.getMemberPointerPath().empty()) {6657Out << "mc";6658mangleType(T);6659} else if (NeedExactType &&6660!Ctx.hasSameType(6661T->castAs<MemberPointerType>()->getPointeeType(),6662V.getMemberPointerDecl()->getType()) &&6663!isCompatibleWith(LangOptions::ClangABI::Ver11)) {6664Out << "cv";6665mangleType(T);6666}6667Out << "adL";6668mangle(V.getMemberPointerDecl());6669Out << 'E';6670if (!V.getMemberPointerPath().empty()) {6671CharUnits Offset =6672Context.getASTContext().getMemberPointerPathAdjustment(V);6673if (!Offset.isZero())6674mangleNumber(Offset.getQuantity());6675Out << 'E';6676}6677break;6678}66796680if (TopLevel && !IsPrimaryExpr)6681Out << 'E';6682}66836684void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {6685// <template-param> ::= T_ # first template parameter6686// ::= T <parameter-2 non-negative number> _6687// ::= TL <L-1 non-negative number> __6688// ::= TL <L-1 non-negative number> _6689// <parameter-2 non-negative number> _6690//6691// The latter two manglings are from a proposal here:6692// https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-5281221176693Out << 'T';6694Depth += TemplateDepthOffset;6695if (Depth != 0)6696Out << 'L' << (Depth - 1) << '_';6697if (Index != 0)6698Out << (Index - 1);6699Out << '_';6700}67016702void CXXNameMangler::mangleSeqID(unsigned SeqID) {6703if (SeqID == 0) {6704// Nothing.6705} else if (SeqID == 1) {6706Out << '0';6707} else {6708SeqID--;67096710// <seq-id> is encoded in base-36, using digits and upper case letters.6711char Buffer[7]; // log(2**32) / log(36) ~= 76712MutableArrayRef<char> BufferRef(Buffer);6713MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();67146715for (; SeqID != 0; SeqID /= 36) {6716unsigned C = SeqID % 36;6717*I++ = (C < 10 ? '0' + C : 'A' + C - 10);6718}67196720Out.write(I.base(), I - BufferRef.rbegin());6721}6722Out << '_';6723}67246725void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {6726bool result = mangleSubstitution(tname);6727assert(result && "no existing substitution for template name");6728(void) result;6729}67306731// <substitution> ::= S <seq-id> _6732// ::= S_6733bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {6734// Try one of the standard substitutions first.6735if (mangleStandardSubstitution(ND))6736return true;67376738ND = cast<NamedDecl>(ND->getCanonicalDecl());6739return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));6740}67416742bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {6743assert(NNS->getKind() == NestedNameSpecifier::Identifier &&6744"mangleSubstitution(NestedNameSpecifier *) is only used for "6745"identifier nested name specifiers.");6746NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);6747return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS));6748}67496750/// Determine whether the given type has any qualifiers that are relevant for6751/// substitutions.6752static bool hasMangledSubstitutionQualifiers(QualType T) {6753Qualifiers Qs = T.getQualifiers();6754return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();6755}67566757bool CXXNameMangler::mangleSubstitution(QualType T) {6758if (!hasMangledSubstitutionQualifiers(T)) {6759if (const RecordType *RT = T->getAs<RecordType>())6760return mangleSubstitution(RT->getDecl());6761}67626763uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());67646765return mangleSubstitution(TypePtr);6766}67676768bool CXXNameMangler::mangleSubstitution(TemplateName Template) {6769if (TemplateDecl *TD = Template.getAsTemplateDecl())6770return mangleSubstitution(TD);67716772Template = Context.getASTContext().getCanonicalTemplateName(Template);6773return mangleSubstitution(6774reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));6775}67766777bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {6778llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);6779if (I == Substitutions.end())6780return false;67816782unsigned SeqID = I->second;6783Out << 'S';6784mangleSeqID(SeqID);67856786return true;6787}67886789/// Returns whether S is a template specialization of std::Name with a single6790/// argument of type A.6791bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,6792QualType A) {6793if (S.isNull())6794return false;67956796const RecordType *RT = S->getAs<RecordType>();6797if (!RT)6798return false;67996800const ClassTemplateSpecializationDecl *SD =6801dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());6802if (!SD || !SD->getIdentifier()->isStr(Name))6803return false;68046805if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))6806return false;68076808const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();6809if (TemplateArgs.size() != 1)6810return false;68116812if (TemplateArgs[0].getAsType() != A)6813return false;68146815if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())6816return false;68176818return true;6819}68206821/// Returns whether SD is a template specialization std::Name<char,6822/// std::char_traits<char> [, std::allocator<char>]>6823/// HasAllocator controls whether the 3rd template argument is needed.6824bool CXXNameMangler::isStdCharSpecialization(6825const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,6826bool HasAllocator) {6827if (!SD->getIdentifier()->isStr(Name))6828return false;68296830const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();6831if (TemplateArgs.size() != (HasAllocator ? 3 : 2))6832return false;68336834QualType A = TemplateArgs[0].getAsType();6835if (A.isNull())6836return false;6837// Plain 'char' is named Char_S or Char_U depending on the target ABI.6838if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&6839!A->isSpecificBuiltinType(BuiltinType::Char_U))6840return false;68416842if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))6843return false;68446845if (HasAllocator &&6846!isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))6847return false;68486849if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())6850return false;68516852return true;6853}68546855bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {6856// <substitution> ::= St # ::std::6857if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {6858if (isStd(NS)) {6859Out << "St";6860return true;6861}6862return false;6863}68646865if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {6866if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))6867return false;68686869if (TD->getOwningModuleForLinkage())6870return false;68716872// <substitution> ::= Sa # ::std::allocator6873if (TD->getIdentifier()->isStr("allocator")) {6874Out << "Sa";6875return true;6876}68776878// <<substitution> ::= Sb # ::std::basic_string6879if (TD->getIdentifier()->isStr("basic_string")) {6880Out << "Sb";6881return true;6882}6883return false;6884}68856886if (const ClassTemplateSpecializationDecl *SD =6887dyn_cast<ClassTemplateSpecializationDecl>(ND)) {6888if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))6889return false;68906891if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())6892return false;68936894// <substitution> ::= Ss # ::std::basic_string<char,6895// ::std::char_traits<char>,6896// ::std::allocator<char> >6897if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {6898Out << "Ss";6899return true;6900}69016902// <substitution> ::= Si # ::std::basic_istream<char,6903// ::std::char_traits<char> >6904if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {6905Out << "Si";6906return true;6907}69086909// <substitution> ::= So # ::std::basic_ostream<char,6910// ::std::char_traits<char> >6911if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {6912Out << "So";6913return true;6914}69156916// <substitution> ::= Sd # ::std::basic_iostream<char,6917// ::std::char_traits<char> >6918if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {6919Out << "Sd";6920return true;6921}6922return false;6923}69246925return false;6926}69276928void CXXNameMangler::addSubstitution(QualType T) {6929if (!hasMangledSubstitutionQualifiers(T)) {6930if (const RecordType *RT = T->getAs<RecordType>()) {6931addSubstitution(RT->getDecl());6932return;6933}6934}69356936uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());6937addSubstitution(TypePtr);6938}69396940void CXXNameMangler::addSubstitution(TemplateName Template) {6941if (TemplateDecl *TD = Template.getAsTemplateDecl())6942return addSubstitution(TD);69436944Template = Context.getASTContext().getCanonicalTemplateName(Template);6945addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));6946}69476948void CXXNameMangler::addSubstitution(uintptr_t Ptr) {6949assert(!Substitutions.count(Ptr) && "Substitution already exists!");6950Substitutions[Ptr] = SeqID++;6951}69526953void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {6954assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");6955if (Other->SeqID > SeqID) {6956Substitutions.swap(Other->Substitutions);6957SeqID = Other->SeqID;6958}6959}69606961CXXNameMangler::AbiTagList6962CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {6963// When derived abi tags are disabled there is no need to make any list.6964if (DisableDerivedAbiTags)6965return AbiTagList();69666967llvm::raw_null_ostream NullOutStream;6968CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);6969TrackReturnTypeTags.disableDerivedAbiTags();69706971const FunctionProtoType *Proto =6972cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());6973FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();6974TrackReturnTypeTags.FunctionTypeDepth.enterResultType();6975TrackReturnTypeTags.mangleType(Proto->getReturnType());6976TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();6977TrackReturnTypeTags.FunctionTypeDepth.pop(saved);69786979return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();6980}69816982CXXNameMangler::AbiTagList6983CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {6984// When derived abi tags are disabled there is no need to make any list.6985if (DisableDerivedAbiTags)6986return AbiTagList();69876988llvm::raw_null_ostream NullOutStream;6989CXXNameMangler TrackVariableType(*this, NullOutStream);6990TrackVariableType.disableDerivedAbiTags();69916992TrackVariableType.mangleType(VD->getType());69936994return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();6995}69966997bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,6998const VarDecl *VD) {6999llvm::raw_null_ostream NullOutStream;7000CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);7001TrackAbiTags.mangle(VD);7002return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();7003}70047005//70067007/// Mangles the name of the declaration D and emits that name to the given7008/// output stream.7009///7010/// If the declaration D requires a mangled name, this routine will emit that7011/// mangled name to \p os and return true. Otherwise, \p os will be unchanged7012/// and this routine will return false. In this case, the caller should just7013/// emit the identifier of the declaration (\c D->getIdentifier()) as its7014/// name.7015void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,7016raw_ostream &Out) {7017const NamedDecl *D = cast<NamedDecl>(GD.getDecl());7018assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&7019"Invalid mangleName() call, argument is not a variable or function!");70207021PrettyStackTraceDecl CrashInfo(D, SourceLocation(),7022getASTContext().getSourceManager(),7023"Mangling declaration");70247025if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {7026auto Type = GD.getCtorType();7027CXXNameMangler Mangler(*this, Out, CD, Type);7028return Mangler.mangle(GlobalDecl(CD, Type));7029}70307031if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {7032auto Type = GD.getDtorType();7033CXXNameMangler Mangler(*this, Out, DD, Type);7034return Mangler.mangle(GlobalDecl(DD, Type));7035}70367037CXXNameMangler Mangler(*this, Out, D);7038Mangler.mangle(GD);7039}70407041void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,7042raw_ostream &Out) {7043CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);7044Mangler.mangle(GlobalDecl(D, Ctor_Comdat));7045}70467047void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,7048raw_ostream &Out) {7049CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);7050Mangler.mangle(GlobalDecl(D, Dtor_Comdat));7051}70527053/// Mangles the pointer authentication override attribute for classes7054/// that have explicit overrides for the vtable authentication schema.7055///7056/// The override is mangled as a parameterized vendor extension as follows7057///7058/// <type> ::= U "__vtptrauth" I7059/// <key>7060/// <addressDiscriminated>7061/// <extraDiscriminator>7062/// E7063///7064/// The extra discriminator encodes the explicit value derived from the7065/// override schema, e.g. if the override has specified type based7066/// discrimination the encoded value will be the discriminator derived from the7067/// type name.7068static void mangleOverrideDiscrimination(CXXNameMangler &Mangler,7069ASTContext &Context,7070const ThunkInfo &Thunk) {7071auto &LangOpts = Context.getLangOpts();7072const CXXRecordDecl *ThisRD = Thunk.ThisType->getPointeeCXXRecordDecl();7073const CXXRecordDecl *PtrauthClassRD =7074Context.baseForVTableAuthentication(ThisRD);7075unsigned TypedDiscriminator =7076Context.getPointerAuthVTablePointerDiscriminator(ThisRD);7077Mangler.mangleVendorQualifier("__vtptrauth");7078auto &ManglerStream = Mangler.getStream();7079ManglerStream << "I";7080if (const auto *ExplicitAuth =7081PtrauthClassRD->getAttr<VTablePointerAuthenticationAttr>()) {7082ManglerStream << "Lj" << ExplicitAuth->getKey();70837084if (ExplicitAuth->getAddressDiscrimination() ==7085VTablePointerAuthenticationAttr::DefaultAddressDiscrimination)7086ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;7087else7088ManglerStream << "Lb"7089<< (ExplicitAuth->getAddressDiscrimination() ==7090VTablePointerAuthenticationAttr::AddressDiscrimination);70917092switch (ExplicitAuth->getExtraDiscrimination()) {7093case VTablePointerAuthenticationAttr::DefaultExtraDiscrimination: {7094if (LangOpts.PointerAuthVTPtrTypeDiscrimination)7095ManglerStream << "Lj" << TypedDiscriminator;7096else7097ManglerStream << "Lj" << 0;7098break;7099}7100case VTablePointerAuthenticationAttr::TypeDiscrimination:7101ManglerStream << "Lj" << TypedDiscriminator;7102break;7103case VTablePointerAuthenticationAttr::CustomDiscrimination:7104ManglerStream << "Lj" << ExplicitAuth->getCustomDiscriminationValue();7105break;7106case VTablePointerAuthenticationAttr::NoExtraDiscrimination:7107ManglerStream << "Lj" << 0;7108break;7109}7110} else {7111ManglerStream << "Lj"7112<< (unsigned)VTablePointerAuthenticationAttr::DefaultKey;7113ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;7114if (LangOpts.PointerAuthVTPtrTypeDiscrimination)7115ManglerStream << "Lj" << TypedDiscriminator;7116else7117ManglerStream << "Lj" << 0;7118}7119ManglerStream << "E";7120}71217122void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,7123const ThunkInfo &Thunk,7124bool ElideOverrideInfo,7125raw_ostream &Out) {7126// <special-name> ::= T <call-offset> <base encoding>7127// # base is the nominal target function of thunk7128// <special-name> ::= Tc <call-offset> <call-offset> <base encoding>7129// # base is the nominal target function of thunk7130// # first call-offset is 'this' adjustment7131// # second call-offset is result adjustment71327133assert(!isa<CXXDestructorDecl>(MD) &&7134"Use mangleCXXDtor for destructor decls!");7135CXXNameMangler Mangler(*this, Out);7136Mangler.getStream() << "_ZT";7137if (!Thunk.Return.isEmpty())7138Mangler.getStream() << 'c';71397140// Mangle the 'this' pointer adjustment.7141Mangler.mangleCallOffset(Thunk.This.NonVirtual,7142Thunk.This.Virtual.Itanium.VCallOffsetOffset);71437144// Mangle the return pointer adjustment if there is one.7145if (!Thunk.Return.isEmpty())7146Mangler.mangleCallOffset(Thunk.Return.NonVirtual,7147Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);71487149Mangler.mangleFunctionEncoding(MD);7150if (!ElideOverrideInfo)7151mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);7152}71537154void ItaniumMangleContextImpl::mangleCXXDtorThunk(const CXXDestructorDecl *DD,7155CXXDtorType Type,7156const ThunkInfo &Thunk,7157bool ElideOverrideInfo,7158raw_ostream &Out) {7159// <special-name> ::= T <call-offset> <base encoding>7160// # base is the nominal target function of thunk7161CXXNameMangler Mangler(*this, Out, DD, Type);7162Mangler.getStream() << "_ZT";71637164auto &ThisAdjustment = Thunk.This;7165// Mangle the 'this' pointer adjustment.7166Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,7167ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);71687169Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));7170if (!ElideOverrideInfo)7171mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);7172}71737174/// Returns the mangled name for a guard variable for the passed in VarDecl.7175void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,7176raw_ostream &Out) {7177// <special-name> ::= GV <object name> # Guard variable for one-time7178// # initialization7179CXXNameMangler Mangler(*this, Out);7180// GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to7181// be a bug that is fixed in trunk.7182Mangler.getStream() << "_ZGV";7183Mangler.mangleName(D);7184}71857186void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,7187raw_ostream &Out) {7188// These symbols are internal in the Itanium ABI, so the names don't matter.7189// Clang has traditionally used this symbol and allowed LLVM to adjust it to7190// avoid duplicate symbols.7191Out << "__cxx_global_var_init";7192}71937194void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,7195raw_ostream &Out) {7196// Prefix the mangling of D with __dtor_.7197CXXNameMangler Mangler(*this, Out);7198Mangler.getStream() << "__dtor_";7199if (shouldMangleDeclName(D))7200Mangler.mangle(D);7201else7202Mangler.getStream() << D->getName();7203}72047205void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,7206raw_ostream &Out) {7207// Clang generates these internal-linkage functions as part of its7208// implementation of the XL ABI.7209CXXNameMangler Mangler(*this, Out);7210Mangler.getStream() << "__finalize_";7211if (shouldMangleDeclName(D))7212Mangler.mangle(D);7213else7214Mangler.getStream() << D->getName();7215}72167217void ItaniumMangleContextImpl::mangleSEHFilterExpression(7218GlobalDecl EnclosingDecl, raw_ostream &Out) {7219CXXNameMangler Mangler(*this, Out);7220Mangler.getStream() << "__filt_";7221auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());7222if (shouldMangleDeclName(EnclosingFD))7223Mangler.mangle(EnclosingDecl);7224else7225Mangler.getStream() << EnclosingFD->getName();7226}72277228void ItaniumMangleContextImpl::mangleSEHFinallyBlock(7229GlobalDecl EnclosingDecl, raw_ostream &Out) {7230CXXNameMangler Mangler(*this, Out);7231Mangler.getStream() << "__fin_";7232auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());7233if (shouldMangleDeclName(EnclosingFD))7234Mangler.mangle(EnclosingDecl);7235else7236Mangler.getStream() << EnclosingFD->getName();7237}72387239void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,7240raw_ostream &Out) {7241// <special-name> ::= TH <object name>7242CXXNameMangler Mangler(*this, Out);7243Mangler.getStream() << "_ZTH";7244Mangler.mangleName(D);7245}72467247void7248ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,7249raw_ostream &Out) {7250// <special-name> ::= TW <object name>7251CXXNameMangler Mangler(*this, Out);7252Mangler.getStream() << "_ZTW";7253Mangler.mangleName(D);7254}72557256void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,7257unsigned ManglingNumber,7258raw_ostream &Out) {7259// We match the GCC mangling here.7260// <special-name> ::= GR <object name>7261CXXNameMangler Mangler(*this, Out);7262Mangler.getStream() << "_ZGR";7263Mangler.mangleName(D);7264assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");7265Mangler.mangleSeqID(ManglingNumber - 1);7266}72677268void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,7269raw_ostream &Out) {7270// <special-name> ::= TV <type> # virtual table7271CXXNameMangler Mangler(*this, Out);7272Mangler.getStream() << "_ZTV";7273Mangler.mangleNameOrStandardSubstitution(RD);7274}72757276void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,7277raw_ostream &Out) {7278// <special-name> ::= TT <type> # VTT structure7279CXXNameMangler Mangler(*this, Out);7280Mangler.getStream() << "_ZTT";7281Mangler.mangleNameOrStandardSubstitution(RD);7282}72837284void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,7285int64_t Offset,7286const CXXRecordDecl *Type,7287raw_ostream &Out) {7288// <special-name> ::= TC <type> <offset number> _ <base type>7289CXXNameMangler Mangler(*this, Out);7290Mangler.getStream() << "_ZTC";7291Mangler.mangleNameOrStandardSubstitution(RD);7292Mangler.getStream() << Offset;7293Mangler.getStream() << '_';7294Mangler.mangleNameOrStandardSubstitution(Type);7295}72967297void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {7298// <special-name> ::= TI <type> # typeinfo structure7299assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");7300CXXNameMangler Mangler(*this, Out);7301Mangler.getStream() << "_ZTI";7302Mangler.mangleType(Ty);7303}73047305void ItaniumMangleContextImpl::mangleCXXRTTIName(7306QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {7307// <special-name> ::= TS <type> # typeinfo name (null terminated byte string)7308CXXNameMangler Mangler(*this, Out, NormalizeIntegers);7309Mangler.getStream() << "_ZTS";7310Mangler.mangleType(Ty);7311}73127313void ItaniumMangleContextImpl::mangleCanonicalTypeName(7314QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {7315mangleCXXRTTIName(Ty, Out, NormalizeIntegers);7316}73177318void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {7319llvm_unreachable("Can't mangle string literals");7320}73217322void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,7323raw_ostream &Out) {7324CXXNameMangler Mangler(*this, Out);7325Mangler.mangleLambdaSig(Lambda);7326}73277328void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,7329raw_ostream &Out) {7330// <special-name> ::= GI <module-name> # module initializer function7331CXXNameMangler Mangler(*this, Out);7332Mangler.getStream() << "_ZGI";7333Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());7334if (M->isModulePartition()) {7335// The partition needs including, as partitions can have them too.7336auto Partition = M->Name.find(':');7337Mangler.mangleModuleNamePrefix(7338StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),7339/*IsPartition*/ true);7340}7341}73427343ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,7344DiagnosticsEngine &Diags,7345bool IsAux) {7346return new ItaniumMangleContextImpl(7347Context, Diags,7348[](ASTContext &, const NamedDecl *) -> std::optional<unsigned> {7349return std::nullopt;7350},7351IsAux);7352}73537354ItaniumMangleContext *7355ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,7356DiscriminatorOverrideTy DiscriminatorOverride,7357bool IsAux) {7358return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,7359IsAux);7360}736173627363