#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprConcepts.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/ABI.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Thunk.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace {
static bool isLocalContainerContext(const DeclContext *DC) {
return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
}
static const FunctionDecl *getStructor(const FunctionDecl *fn) {
if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
return ftd->getTemplatedDecl();
return fn;
}
static const NamedDecl *getStructor(const NamedDecl *decl) {
const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
return (fn ? getStructor(fn) : decl);
}
static bool isLambda(const NamedDecl *ND) {
const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
if (!Record)
return false;
return Record->isLambda();
}
static const unsigned UnknownArity = ~0U;
class ItaniumMangleContextImpl : public ItaniumMangleContext {
typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
NamespaceDecl *StdNamespace = nullptr;
bool NeedsUniqueInternalLinkageNames = false;
public:
explicit ItaniumMangleContextImpl(
ASTContext &Context, DiagnosticsEngine &Diags,
DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
: ItaniumMangleContext(Context, Diags, IsAux),
DiscriminatorOverride(DiscriminatorOverride) {}
bool shouldMangleCXXName(const NamedDecl *D) override;
bool shouldMangleStringLiteral(const StringLiteral *) override {
return false;
}
bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
void needsUniqueInternalLinkageNames() override {
NeedsUniqueInternalLinkageNames = true;
}
void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
raw_ostream &) override;
void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
const ThisAdjustment &ThisAdjustment,
raw_ostream &) override;
void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
raw_ostream &) override;
void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
const CXXRecordDecl *Type, raw_ostream &) override;
void mangleCXXRTTI(QualType T, raw_ostream &) override;
void mangleCXXRTTIName(QualType T, raw_ostream &) override;
void mangleTypeName(QualType T, raw_ostream &) override;
void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
void mangleDynamicAtExitDestructor(const VarDecl *D,
raw_ostream &Out) override;
void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
raw_ostream &Out) override;
void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
raw_ostream &Out) override;
void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
void mangleItaniumThreadLocalWrapper(const VarDecl *D,
raw_ostream &) override;
void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
if (isLambda(ND))
return false;
if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
return false;
}
if (ND->isExternallyVisible()) {
unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
if (discriminator == 1)
return false;
disc = discriminator - 2;
return true;
}
unsigned &discriminator = Uniquifier[ND];
if (!discriminator) {
const DeclContext *DC = getEffectiveDeclContext(ND);
discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
}
if (discriminator == 1)
return false;
disc = discriminator-2;
return true;
}
std::string getLambdaString(const CXXRecordDecl *Lambda) override {
assert(Lambda->isLambda() && "RD must be a lambda!");
std::string Name("<lambda");
Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
unsigned LambdaId;
const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
const FunctionDecl *Func =
Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
if (Func) {
unsigned DefaultArgNo =
Func->getNumParams() - Parm->getFunctionScopeIndex();
Name += llvm::utostr(DefaultArgNo);
Name += "_";
}
if (LambdaManglingNumber)
LambdaId = LambdaManglingNumber;
else
LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
Name += llvm::utostr(LambdaId);
Name += '>';
return Name;
}
DiscriminatorOverrideTy getDiscriminatorOverride() const override {
return DiscriminatorOverride;
}
NamespaceDecl *getStdNamespace();
const DeclContext *getEffectiveDeclContext(const Decl *D);
const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
return getEffectiveDeclContext(cast<Decl>(DC));
}
bool isInternalLinkageDecl(const NamedDecl *ND);
const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
};
class CXXNameMangler {
ItaniumMangleContextImpl &Context;
raw_ostream &Out;
bool NullOut = false;
bool DisableDerivedAbiTags = false;
const NamedDecl *Structor;
unsigned StructorType = 0;
unsigned SeqID = 0;
class FunctionTypeDepthState {
unsigned Bits;
enum { InResultTypeMask = 1 };
public:
FunctionTypeDepthState() : Bits(0) {}
unsigned getDepth() const {
return Bits >> 1;
}
bool isInResultType() const {
return Bits & InResultTypeMask;
}
FunctionTypeDepthState push() {
FunctionTypeDepthState tmp = *this;
Bits = (Bits & ~InResultTypeMask) + 2;
return tmp;
}
void enterResultType() {
Bits |= InResultTypeMask;
}
void leaveResultType() {
Bits &= ~InResultTypeMask;
}
void pop(FunctionTypeDepthState saved) {
assert(getDepth() == saved.getDepth() + 1);
Bits = saved.Bits;
}
} FunctionTypeDepth;
typedef SmallVector<StringRef, 4> AbiTagList;
class AbiTagState final {
public:
explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
Parent = LinkHead;
LinkHead = this;
}
AbiTagState(const AbiTagState &) = delete;
AbiTagState &operator=(const AbiTagState &) = delete;
~AbiTagState() { pop(); }
void write(raw_ostream &Out, const NamedDecl *ND,
const AbiTagList *AdditionalAbiTags) {
ND = cast<NamedDecl>(ND->getCanonicalDecl());
if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
assert(
!AdditionalAbiTags &&
"only function and variables need a list of additional abi tags");
if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
AbiTag->tags().end());
}
return;
}
}
AbiTagList TagList;
if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
AbiTag->tags().end());
TagList.insert(TagList.end(), AbiTag->tags().begin(),
AbiTag->tags().end());
}
if (AdditionalAbiTags) {
UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
AdditionalAbiTags->end());
TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
AdditionalAbiTags->end());
}
llvm::sort(TagList);
TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
writeSortedUniqueAbiTags(Out, TagList);
}
const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
void setUsedAbiTags(const AbiTagList &AbiTags) {
UsedAbiTags = AbiTags;
}
const AbiTagList &getEmittedAbiTags() const {
return EmittedAbiTags;
}
const AbiTagList &getSortedUniqueUsedAbiTags() {
llvm::sort(UsedAbiTags);
UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
UsedAbiTags.end());
return UsedAbiTags;
}
private:
AbiTagList UsedAbiTags;
AbiTagList EmittedAbiTags;
AbiTagState *&LinkHead;
AbiTagState *Parent = nullptr;
void pop() {
assert(LinkHead == this &&
"abi tag link head must point to us on destruction");
if (Parent) {
Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
UsedAbiTags.begin(), UsedAbiTags.end());
Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
EmittedAbiTags.begin(),
EmittedAbiTags.end());
}
LinkHead = Parent;
}
void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
for (const auto &Tag : AbiTags) {
EmittedAbiTags.push_back(Tag);
Out << "B";
Out << Tag.size();
Out << Tag;
}
}
};
AbiTagState *AbiTags = nullptr;
AbiTagState AbiTagsRoot;
llvm::DenseMap<uintptr_t, unsigned> Substitutions;
llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
ASTContext &getASTContext() const { return Context.getASTContext(); }
bool isStd(const NamespaceDecl *NS);
bool isStdNamespace(const DeclContext *DC);
const RecordDecl *GetLocalClassDecl(const Decl *D);
const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
llvm::StringRef Name, bool HasAllocator);
public:
CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
const NamedDecl *D = nullptr, bool NullOut_ = false)
: Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
AbiTagsRoot(AbiTags) {
assert(!D || (!isa<CXXDestructorDecl>(D) &&
!isa<CXXConstructorDecl>(D)));
}
CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
const CXXConstructorDecl *D, CXXCtorType Type)
: Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
AbiTagsRoot(AbiTags) {}
CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
const CXXDestructorDecl *D, CXXDtorType Type)
: Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
AbiTagsRoot(AbiTags) {}
CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
: Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
StructorType(Outer.StructorType), SeqID(Outer.SeqID),
FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
Substitutions(Outer.Substitutions),
ModuleSubstitutions(Outer.ModuleSubstitutions) {}
CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
: CXXNameMangler(Outer, (raw_ostream &)Out_) {
NullOut = true;
}
raw_ostream &getStream() { return Out; }
void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
void mangle(GlobalDecl GD);
void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
void mangleNumber(const llvm::APSInt &I);
void mangleNumber(int64_t Number);
void mangleFloat(const llvm::APFloat &F);
void mangleFunctionEncoding(GlobalDecl GD);
void mangleSeqID(unsigned SeqID);
void mangleName(GlobalDecl GD);
void mangleType(QualType T);
void mangleNameOrStandardSubstitution(const NamedDecl *ND);
void mangleLambdaSig(const CXXRecordDecl *Lambda);
void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
private:
bool mangleSubstitution(const NamedDecl *ND);
bool mangleSubstitution(NestedNameSpecifier *NNS);
bool mangleSubstitution(QualType T);
bool mangleSubstitution(TemplateName Template);
bool mangleSubstitution(uintptr_t Ptr);
void mangleExistingSubstitution(TemplateName name);
bool mangleStandardSubstitution(const NamedDecl *ND);
void addSubstitution(const NamedDecl *ND) {
ND = cast<NamedDecl>(ND->getCanonicalDecl());
addSubstitution(reinterpret_cast<uintptr_t>(ND));
}
void addSubstitution(NestedNameSpecifier *NNS) {
NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
addSubstitution(reinterpret_cast<uintptr_t>(NNS));
}
void addSubstitution(QualType T);
void addSubstitution(TemplateName Template);
void addSubstitution(uintptr_t Ptr);
void extendSubstitutions(CXXNameMangler* Other);
void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
bool recursive = false);
void mangleUnresolvedName(NestedNameSpecifier *qualifier,
DeclarationName name,
const TemplateArgumentLoc *TemplateArgs,
unsigned NumTemplateArgs,
unsigned KnownArity = UnknownArity);
void mangleFunctionEncodingBareType(const FunctionDecl *FD);
void mangleNameWithAbiTags(GlobalDecl GD,
const AbiTagList *AdditionalAbiTags);
void mangleModuleName(const NamedDecl *ND);
void mangleTemplateName(const TemplateDecl *TD,
const TemplateArgument *TemplateArgs,
unsigned NumTemplateArgs);
void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
const AbiTagList *AdditionalAbiTags) {
mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
UnknownArity, AdditionalAbiTags);
}
void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
const DeclContext *DC, unsigned KnownArity,
const AbiTagList *AdditionalAbiTags);
void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
const AbiTagList *AdditionalAbiTags);
void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
const AbiTagList *AdditionalAbiTags);
void mangleSourceName(const IdentifierInfo *II);
void mangleRegCallName(const IdentifierInfo *II);
void mangleDeviceStubName(const IdentifierInfo *II);
void mangleSourceNameWithAbiTags(
const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
void mangleLocalName(GlobalDecl GD,
const AbiTagList *AdditionalAbiTags);
void mangleBlockForPrefix(const BlockDecl *Block);
void mangleUnqualifiedBlock(const BlockDecl *Block);
void mangleTemplateParamDecl(const NamedDecl *Decl);
void mangleLambda(const CXXRecordDecl *Lambda);
void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
const AbiTagList *AdditionalAbiTags,
bool NoFunction=false);
void mangleNestedName(const TemplateDecl *TD,
const TemplateArgument *TemplateArgs,
unsigned NumTemplateArgs);
void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
const NamedDecl *PrefixND,
const AbiTagList *AdditionalAbiTags);
void manglePrefix(NestedNameSpecifier *qualifier);
void manglePrefix(const DeclContext *DC, bool NoFunction=false);
void manglePrefix(QualType type);
void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
void mangleTemplatePrefix(TemplateName Template);
const NamedDecl *getClosurePrefix(const Decl *ND);
void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
StringRef Prefix = "");
void mangleOperatorName(DeclarationName Name, unsigned Arity);
void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
void mangleVendorQualifier(StringRef qualifier);
void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
void mangleRefQualifier(RefQualifierKind RefQualifier);
void mangleObjCMethodName(const ObjCMethodDecl *MD);
#define ABSTRACT_TYPE(CLASS, PARENT)
#define NON_CANONICAL_TYPE(CLASS, PARENT)
#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
#include "clang/AST/TypeNodes.inc"
void mangleType(const TagType*);
void mangleType(TemplateName);
static StringRef getCallingConvQualifierName(CallingConv CC);
void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
void mangleExtFunctionInfo(const FunctionType *T);
void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
const FunctionDecl *FD = nullptr);
void mangleNeonVectorType(const VectorType *T);
void mangleNeonVectorType(const DependentVectorType *T);
void mangleAArch64NeonVectorType(const VectorType *T);
void mangleAArch64NeonVectorType(const DependentVectorType *T);
void mangleAArch64FixedSveVectorType(const VectorType *T);
void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
void mangleFixedPointLiteral();
void mangleNullPointer(QualType T);
void mangleMemberExprBase(const Expr *base, bool isArrow);
void mangleMemberExpr(const Expr *base, bool isArrow,
NestedNameSpecifier *qualifier,
NamedDecl *firstQualifierLookup,
DeclarationName name,
const TemplateArgumentLoc *TemplateArgs,
unsigned NumTemplateArgs,
unsigned knownArity);
void mangleCastExpression(const Expr *E, StringRef CastEncoding);
void mangleInitListElements(const InitListExpr *InitList);
void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
bool AsTemplateArg = false);
void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
void mangleCXXDtorType(CXXDtorType T);
void mangleTemplateArgs(TemplateName TN,
const TemplateArgumentLoc *TemplateArgs,
unsigned NumTemplateArgs);
void mangleTemplateArgs(TemplateName TN, const TemplateArgument *TemplateArgs,
unsigned NumTemplateArgs);
void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
void mangleTemplateArgExpr(const Expr *E);
void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
bool NeedExactType = false);
void mangleTemplateParameter(unsigned Depth, unsigned Index);
void mangleFunctionParam(const ParmVarDecl *parm);
void writeAbiTags(const NamedDecl *ND,
const AbiTagList *AdditionalAbiTags);
AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
AbiTagList makeVariableTypeTags(const VarDecl *VD);
};
}
NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
if (!StdNamespace) {
StdNamespace = NamespaceDecl::Create(
getASTContext(), getASTContext().getTranslationUnitDecl(),
false, SourceLocation(), SourceLocation(),
&getASTContext().Idents.get("std"),
nullptr);
StdNamespace->setImplicit();
}
return StdNamespace;
}
const DeclContext *
ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
if (RD->isLambda())
if (ParmVarDecl *ContextParam =
dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
return ContextParam->getDeclContext();
}
if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
if (ParmVarDecl *ContextParam =
dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
return ContextParam->getDeclContext();
}
if (D == getASTContext().getVaListTagDecl()) {
const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
if (T.isARM() || T.isThumb() || T.isAArch64())
return getStdNamespace();
}
const DeclContext *DC = D->getDeclContext();
if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
isa<OMPDeclareMapperDecl>(DC)) {
return getEffectiveDeclContext(cast<Decl>(DC));
}
if (const auto *VD = dyn_cast<VarDecl>(D))
if (VD->isExternC())
return getASTContext().getTranslationUnitDecl();
if (const auto *FD = dyn_cast<FunctionDecl>(D))
if (FD->isExternC())
return getASTContext().getTranslationUnitDecl();
return DC->getRedeclContext();
}
bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
if (ND && ND->getFormalLinkage() == InternalLinkage &&
!ND->isExternallyVisible() &&
getEffectiveDeclContext(ND)->isFileContext() &&
!ND->isInAnonymousNamespace())
return true;
return false;
}
bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
const NamedDecl *ND) {
if (!NeedsUniqueInternalLinkageNames || !ND)
return false;
const auto *FD = dyn_cast<FunctionDecl>(ND);
if (!FD)
return false;
if (!FD->getType()->getAs<FunctionProtoType>())
return false;
if (isInternalLinkageDecl(ND))
return true;
return false;
}
bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
LanguageLinkage L = FD->getLanguageLinkage();
if (FD->hasAttr<OverloadableAttr>())
return true;
if (FD->isMain())
return false;
if (FD->isMSVCRTEntryPoint())
return false;
if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
return true;
if (L == CLanguageLinkage)
return false;
}
if (!getASTContext().getLangOpts().CPlusPlus)
return false;
if (const auto *VD = dyn_cast<VarDecl>(D)) {
if (isa<DecompositionDecl>(VD))
return true;
if (VD->isExternC())
return false;
const DeclContext *DC = getEffectiveDeclContext(D);
if (DC->isFunctionOrMethod() && D->hasLinkage())
while (!DC->isFileContext())
DC = getEffectiveParentContext(DC);
if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
!CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
!isa<VarTemplateSpecializationDecl>(VD) &&
!VD->getOwningModuleForLinkage())
return false;
}
return true;
}
void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
const AbiTagList *AdditionalAbiTags) {
assert(AbiTags && "require AbiTagState");
AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
}
void CXXNameMangler::mangleSourceNameWithAbiTags(
const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
mangleSourceName(ND->getIdentifier());
writeAbiTags(ND, AdditionalAbiTags);
}
void CXXNameMangler::mangle(GlobalDecl GD) {
Out << "_Z";
if (isa<FunctionDecl>(GD.getDecl()))
mangleFunctionEncoding(GD);
else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
BindingDecl>(GD.getDecl()))
mangleName(GD);
else if (const IndirectFieldDecl *IFD =
dyn_cast<IndirectFieldDecl>(GD.getDecl()))
mangleName(IFD->getAnonField());
else
llvm_unreachable("unexpected kind of global decl");
}
void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
if (!Context.shouldMangleDeclName(FD)) {
mangleName(GD);
return;
}
AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
if (ReturnTypeAbiTags.empty()) {
mangleName(GD);
mangleFunctionEncodingBareType(FD);
return;
}
SmallString<256> FunctionEncodingBuf;
llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
FunctionEncodingMangler.disableDerivedAbiTags();
FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
size_t EncodingPositionStart = FunctionEncodingStream.str().size();
FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
const AbiTagList &UsedAbiTags =
FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
AdditionalAbiTags.erase(
std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
UsedAbiTags.begin(), UsedAbiTags.end(),
AdditionalAbiTags.begin()),
AdditionalAbiTags.end());
mangleNameWithAbiTags(FD, &AdditionalAbiTags);
Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
extendSubstitutions(&FunctionEncodingMangler);
}
void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
if (FD->hasAttr<EnableIfAttr>()) {
FunctionTypeDepthState Saved = FunctionTypeDepth.push();
Out << "Ua9enable_ifI";
for (AttrVec::const_iterator I = FD->getAttrs().begin(),
E = FD->getAttrs().end();
I != E; ++I) {
EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
if (!EIA)
continue;
if (Context.getASTContext().getLangOpts().getClangABICompat() >
LangOptions::ClangABI::Ver11) {
mangleTemplateArgExpr(EIA->getCond());
} else {
Out << 'X';
mangleExpression(EIA->getCond());
Out << 'E';
}
}
Out << 'E';
FunctionTypeDepth.pop(Saved);
}
if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
if (auto Inherited = CD->getInheritedConstructor())
FD = Inherited.getConstructor();
bool MangleReturnType = false;
if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
isa<CXXConversionDecl>(FD)))
MangleReturnType = true;
FD = PrimaryTemplate->getTemplatedDecl();
}
mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
MangleReturnType, FD);
}
bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
return false;
const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
return II && II->isStr("std");
}
bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
if (!DC->isNamespace())
return false;
return isStd(cast<NamespaceDecl>(DC));
}
static const GlobalDecl
isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
TemplateArgs = FD->getTemplateSpecializationArgs();
return GD.getWithDecl(TD);
}
}
if (const ClassTemplateSpecializationDecl *Spec =
dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
TemplateArgs = &Spec->getTemplateArgs();
return GD.getWithDecl(Spec->getSpecializedTemplate());
}
if (const VarTemplateSpecializationDecl *Spec =
dyn_cast<VarTemplateSpecializationDecl>(ND)) {
TemplateArgs = &Spec->getTemplateArgs();
return GD.getWithDecl(Spec->getSpecializedTemplate());
}
return GlobalDecl();
}
static TemplateName asTemplateName(GlobalDecl GD) {
const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
return TemplateName(const_cast<TemplateDecl*>(TD));
}
void CXXNameMangler::mangleName(GlobalDecl GD) {
const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
if (VariableTypeAbiTags.empty()) {
mangleNameWithAbiTags(VD, nullptr);
return;
}
llvm::raw_null_ostream NullOutStream;
CXXNameMangler VariableNameMangler(*this, NullOutStream);
VariableNameMangler.disableDerivedAbiTags();
VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
const AbiTagList &UsedAbiTags =
VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
AdditionalAbiTags.erase(
std::set_difference(VariableTypeAbiTags.begin(),
VariableTypeAbiTags.end(), UsedAbiTags.begin(),
UsedAbiTags.end(), AdditionalAbiTags.begin()),
AdditionalAbiTags.end());
mangleNameWithAbiTags(VD, &AdditionalAbiTags);
} else {
mangleNameWithAbiTags(GD, nullptr);
}
}
const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
const DeclContext *DC = Context.getEffectiveDeclContext(D);
while (!DC->isNamespace() && !DC->isTranslationUnit()) {
if (isLocalContainerContext(DC))
return dyn_cast<RecordDecl>(D);
D = cast<Decl>(DC);
DC = Context.getEffectiveDeclContext(D);
}
return nullptr;
}
void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
const AbiTagList *AdditionalAbiTags) {
const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
const DeclContext *DC = Context.getEffectiveDeclContext(ND);
if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
while (!DC->isNamespace() && !DC->isTranslationUnit())
DC = Context.getEffectiveParentContext(DC);
else if (GetLocalClassDecl(ND)) {
mangleLocalName(GD, AdditionalAbiTags);
return;
}
assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");
if (isLocalContainerContext(DC)) {
mangleLocalName(GD, AdditionalAbiTags);
return;
}
if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
return;
}
if (DC->isTranslationUnit() || isStdNamespace(DC)) {
const TemplateArgumentList *TemplateArgs = nullptr;
if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
return;
}
mangleUnscopedName(GD, DC, AdditionalAbiTags);
return;
}
mangleNestedName(GD, DC, AdditionalAbiTags);
}
void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
if (ND->isExternallyVisible())
if (Module *M = ND->getOwningModuleForLinkage())
mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
}
void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
auto It = ModuleSubstitutions.find(Name);
if (It != ModuleSubstitutions.end()) {
Out << 'S';
mangleSeqID(It->second);
return;
}
auto Parts = Name.rsplit('.');
if (Parts.second.empty())
Parts.second = Parts.first;
else {
mangleModuleNamePrefix(Parts.first, IsPartition);
IsPartition = false;
}
Out << 'W';
if (IsPartition)
Out << 'P';
Out << Parts.second.size() << Parts.second;
ModuleSubstitutions.insert({Name, SeqID++});
}
void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
const TemplateArgument *TemplateArgs,
unsigned NumTemplateArgs) {
const DeclContext *DC = Context.getEffectiveDeclContext(TD);
if (DC->isTranslationUnit() || isStdNamespace(DC)) {
mangleUnscopedTemplateName(TD, DC, nullptr);
mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs);
} else {
mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
}
}
void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
const AbiTagList *AdditionalAbiTags) {
assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");
if (isStdNamespace(DC))
Out << "St";
mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
}
void CXXNameMangler::mangleUnscopedTemplateName(
GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
if (mangleSubstitution(ND))
return;
if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
assert(!AdditionalAbiTags &&
"template template param cannot have abi tags");
mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
} else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
mangleUnscopedName(GD, DC, AdditionalAbiTags);
} else {
mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
AdditionalAbiTags);
}
addSubstitution(ND);
}
void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
llvm::APInt valueBits = f.bitcastToAPInt();
unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
assert(numCharacters != 0);
SmallVector<char, 20> buffer(numCharacters);
for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
hexDigit >>= (digitBitIndex % 64);
hexDigit &= 0xF;
static const char charForHex[16] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
buffer[stringIndex] = charForHex[hexDigit];
}
Out.write(buffer.data(), numCharacters);
}
void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
Out << 'L';
mangleType(T);
mangleFloat(V);
Out << 'E';
}
void CXXNameMangler::mangleFixedPointLiteral() {
DiagnosticsEngine &Diags = Context.getDiags();
unsigned DiagID = Diags.getCustomDiagID(
DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
Diags.Report(DiagID);
}
void CXXNameMangler::mangleNullPointer(QualType T) {
Out << 'L';
mangleType(T);
Out << "0E";
}
void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
if (Value.isSigned() && Value.isNegative()) {
Out << 'n';
Value.abs().print(Out, false);
} else {
Value.print(Out, false);
}
}
void CXXNameMangler::mangleNumber(int64_t Number) {
if (Number < 0) {
Out << 'n';
Number = -Number;
}
Out << Number;
}
void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
if (!Virtual) {
Out << 'h';
mangleNumber(NonVirtual);
Out << '_';
return;
}
Out << 'v';
mangleNumber(NonVirtual);
Out << '_';
mangleNumber(Virtual);
Out << '_';
}
void CXXNameMangler::manglePrefix(QualType type) {
if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
if (!mangleSubstitution(QualType(TST, 0))) {
mangleTemplatePrefix(TST->getTemplateName());
mangleTemplateArgs(TST->getTemplateName(), TST->getArgs(),
TST->getNumArgs());
addSubstitution(QualType(TST, 0));
}
} else if (const auto *DTST =
type->getAs<DependentTemplateSpecializationType>()) {
if (!mangleSubstitution(QualType(DTST, 0))) {
TemplateName Template = getASTContext().getDependentTemplateName(
DTST->getQualifier(), DTST->getIdentifier());
mangleTemplatePrefix(Template);
mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
addSubstitution(QualType(DTST, 0));
}
} else {
mangleType(type);
}
}
void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
bool recursive) {
switch (qualifier->getKind()) {
case NestedNameSpecifier::Global:
Out << "gs";
if (recursive)
Out << "sr";
return;
case NestedNameSpecifier::Super:
llvm_unreachable("Can't mangle __super specifier");
case NestedNameSpecifier::Namespace:
if (qualifier->getPrefix())
mangleUnresolvedPrefix(qualifier->getPrefix(),
true);
else
Out << "sr";
mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
break;
case NestedNameSpecifier::NamespaceAlias:
if (qualifier->getPrefix())
mangleUnresolvedPrefix(qualifier->getPrefix(),
true);
else
Out << "sr";
mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
break;
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::TypeSpecWithTemplate: {
const Type *type = qualifier->getAsType();
if (qualifier->getPrefix()) {
mangleUnresolvedPrefix(qualifier->getPrefix(),
true);
} else {
Out << "sr";
}
if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
return;
break;
}
case NestedNameSpecifier::Identifier:
if (qualifier->getPrefix())
mangleUnresolvedPrefix(qualifier->getPrefix(),
true);
else
Out << "sr";
mangleSourceName(qualifier->getAsIdentifier());
break;
}
if (!recursive)
Out << 'E';
}
void CXXNameMangler::mangleUnresolvedName(
NestedNameSpecifier *qualifier, DeclarationName name,
const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
unsigned knownArity) {
if (qualifier) mangleUnresolvedPrefix(qualifier);
switch (name.getNameKind()) {
case DeclarationName::Identifier:
mangleSourceName(name.getAsIdentifierInfo());
break;
case DeclarationName::CXXDestructorName:
Out << "dn";
mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
break;
case DeclarationName::CXXConversionFunctionName:
case DeclarationName::CXXLiteralOperatorName:
case DeclarationName::CXXOperatorName:
Out << "on";
mangleOperatorName(name, knownArity);
break;
case DeclarationName::CXXConstructorName:
llvm_unreachable("Can't mangle a constructor name!");
case DeclarationName::CXXUsingDirective:
llvm_unreachable("Can't mangle a using directive name!");
case DeclarationName::CXXDeductionGuideName:
llvm_unreachable("Can't mangle a deduction guide name!");
case DeclarationName::ObjCMultiArgSelector:
case DeclarationName::ObjCOneArgSelector:
case DeclarationName::ObjCZeroArgSelector:
llvm_unreachable("Can't mangle Objective-C selector names here!");
}
if (TemplateArgs)
mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
}
void CXXNameMangler::mangleUnqualifiedName(
GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
if (ND && DC && DC->isFileContext())
mangleModuleName(ND);
unsigned Arity = KnownArity;
switch (Name.getNameKind()) {
case DeclarationName::Identifier: {
const IdentifierInfo *II = Name.getAsIdentifierInfo();
if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Out << "DC";
for (auto *BD : DD->bindings())
mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
Out << 'E';
writeAbiTags(ND, AdditionalAbiTags);
break;
}
if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
llvm::raw_svector_ostream GUIDOS(GUID);
Context.mangleMSGuidDecl(GD, GUIDOS);
Out << GUID.size() << GUID;
break;
}
if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
Out << "TA";
mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
TPO->getValue(), true);
break;
}
if (II) {
if (Context.isInternalLinkageDecl(ND))
Out << 'L';
auto *FD = dyn_cast<FunctionDecl>(ND);
bool IsRegCall = FD &&
FD->getType()->castAs<FunctionType>()->getCallConv() ==
clang::CC_X86RegCall;
bool IsDeviceStub =
FD && FD->hasAttr<CUDAGlobalAttr>() &&
GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
if (IsDeviceStub)
mangleDeviceStubName(II);
else if (IsRegCall)
mangleRegCallName(II);
else
mangleSourceName(II);
writeAbiTags(ND, AdditionalAbiTags);
break;
}
assert(ND && "mangling empty name without declaration");
if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
if (NS->isAnonymousNamespace()) {
Out << "12_GLOBAL__N_1";
break;
}
}
if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
assert(RD->isAnonymousStructOrUnion()
&& "Expected anonymous struct or union!");
const FieldDecl *FD = RD->findFirstNamedDataMember();
if (!FD) break;
assert(FD->getIdentifier() && "Data member name isn't an identifier!");
mangleSourceName(FD->getIdentifier());
break;
}
if (isa<ObjCContainerDecl>(ND))
break;
const TagDecl *TD = cast<TagDecl>(ND);
if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
assert(TD->getDeclContext() == D->getDeclContext() &&
"Typedef should not be in another decl context!");
assert(D->getDeclName().getAsIdentifierInfo() &&
"Typedef was not named!");
mangleSourceName(D->getDeclName().getAsIdentifierInfo());
assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
writeAbiTags(TD, nullptr);
break;
}
if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
llvm::Optional<unsigned> DeviceNumber =
Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
if (Record->isLambda() &&
((DeviceNumber && *DeviceNumber > 0) ||
(!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
assert(!AdditionalAbiTags &&
"Lambda type cannot have additional abi tags");
mangleLambda(Record);
break;
}
}
if (TD->isExternallyVisible()) {
unsigned UnnamedMangle =
getASTContext().getManglingNumber(TD, Context.isAux());
Out << "Ut";
if (UnnamedMangle > 1)
Out << UnnamedMangle - 2;
Out << '_';
writeAbiTags(TD, AdditionalAbiTags);
break;
}
unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
SmallString<8> Str;
Str += "$_";
Str += llvm::utostr(AnonStructId);
Out << Str.size();
Out << Str;
break;
}
case DeclarationName::ObjCZeroArgSelector:
case DeclarationName::ObjCOneArgSelector:
case DeclarationName::ObjCMultiArgSelector:
llvm_unreachable("Can't mangle Objective-C selector names here!");
case DeclarationName::CXXConstructorName: {
const CXXRecordDecl *InheritedFrom = nullptr;
TemplateName InheritedTemplateName;
const TemplateArgumentList *InheritedTemplateArgs = nullptr;
if (auto Inherited =
cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
InheritedFrom = Inherited.getConstructor()->getParent();
InheritedTemplateName =
TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
InheritedTemplateArgs =
Inherited.getConstructor()->getTemplateSpecializationArgs();
}
if (ND == Structor)
mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
else
mangleCXXCtorType(Ctor_Complete, InheritedFrom);
if (InheritedTemplateArgs)
mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
writeAbiTags(ND, AdditionalAbiTags);
break;
}
case DeclarationName::CXXDestructorName:
if (ND == Structor)
mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
else
mangleCXXDtorType(Dtor_Complete);
writeAbiTags(ND, AdditionalAbiTags);
break;
case DeclarationName::CXXOperatorName:
if (ND && Arity == UnknownArity) {
Arity = cast<FunctionDecl>(ND)->getNumParams();
if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
if (!MD->isStatic())
Arity++;
}
LLVM_FALLTHROUGH;
case DeclarationName::CXXConversionFunctionName:
case DeclarationName::CXXLiteralOperatorName:
mangleOperatorName(Name, Arity);
writeAbiTags(ND, AdditionalAbiTags);
break;
case DeclarationName::CXXDeductionGuideName:
llvm_unreachable("Can't mangle a deduction guide name!");
case DeclarationName::CXXUsingDirective:
llvm_unreachable("Can't mangle a using directive name!");
}
}
void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
<< II->getName();
}
void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
<< II->getName();
}
void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
Out << II->getLength() << II->getName();
}
void CXXNameMangler::mangleNestedName(GlobalDecl GD,
const DeclContext *DC,
const AbiTagList *AdditionalAbiTags,
bool NoFunction) {
const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
Out << 'N';
if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
Qualifiers MethodQuals = Method->getMethodQualifiers();
MethodQuals.removeRestrict();
mangleQualifiers(MethodQuals);
mangleRefQualifier(Method->getRefQualifier());
}
const TemplateArgumentList *TemplateArgs = nullptr;
if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
mangleTemplatePrefix(TD, NoFunction);
mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
} else {
manglePrefix(DC, NoFunction);
mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
}
Out << 'E';
}
void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
const TemplateArgument *TemplateArgs,
unsigned NumTemplateArgs) {
Out << 'N';
mangleTemplatePrefix(TD);
mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs);
Out << 'E';
}
void CXXNameMangler::mangleNestedNameWithClosurePrefix(
GlobalDecl GD, const NamedDecl *PrefixND,
const AbiTagList *AdditionalAbiTags) {
Out << 'N';
mangleClosurePrefix(PrefixND);
mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
Out << 'E';
}
static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
GlobalDecl GD;
if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
GD = GlobalDecl(CD, Ctor_Complete);
else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
GD = GlobalDecl(DD, Dtor_Complete);
else
GD = GlobalDecl(cast<FunctionDecl>(DC));
return GD;
}
void CXXNameMangler::mangleLocalName(GlobalDecl GD,
const AbiTagList *AdditionalAbiTags) {
const Decl *D = GD.getDecl();
assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
const RecordDecl *RD = GetLocalClassDecl(D);
const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
Out << 'Z';
{
AbiTagState LocalAbiTags(AbiTags);
if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
mangleObjCMethodName(MD);
else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
mangleBlockForPrefix(BD);
else
mangleFunctionEncoding(getParentOfLocalEntity(DC));
LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
}
Out << 'E';
if (RD) {
const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
if (CXXRD && CXXRD->isLambda()) {
if (const ParmVarDecl *Parm
= dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
if (const FunctionDecl *Func
= dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
Out << 'd';
unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
if (Num > 1)
mangleNumber(Num - 2);
Out << '_';
}
}
}
if (D == RD) {
mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
} else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
if (const NamedDecl *PrefixND = getClosurePrefix(BD))
mangleClosurePrefix(PrefixND, true );
else
manglePrefix(Context.getEffectiveDeclContext(BD), true );
assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
mangleUnqualifiedBlock(BD);
} else {
const NamedDecl *ND = cast<NamedDecl>(D);
mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
AdditionalAbiTags, true );
}
} else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
if (const ParmVarDecl *Parm
= dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
if (const FunctionDecl *Func
= dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
Out << 'd';
unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
if (Num > 1)
mangleNumber(Num - 2);
Out << '_';
}
}
assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
mangleUnqualifiedBlock(BD);
} else {
mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
}
if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
unsigned disc;
if (Context.getNextDiscriminator(ND, disc)) {
if (disc < 10)
Out << '_' << disc;
else
Out << "__" << disc << '_';
}
}
}
void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
if (GetLocalClassDecl(Block)) {
mangleLocalName(Block, nullptr);
return;
}
const DeclContext *DC = Context.getEffectiveDeclContext(Block);
if (isLocalContainerContext(DC)) {
mangleLocalName(Block, nullptr);
return;
}
if (const NamedDecl *PrefixND = getClosurePrefix(Block))
mangleClosurePrefix(PrefixND);
else
manglePrefix(DC);
mangleUnqualifiedBlock(Block);
}
void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
if (Decl *Context = Block->getBlockManglingContextDecl()) {
if (getASTContext().getLangOpts().getClangABICompat() <=
LangOptions::ClangABI::Ver12 &&
(isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
Context->getDeclContext()->isRecord()) {
const auto *ND = cast<NamedDecl>(Context);
if (ND->getIdentifier()) {
mangleSourceNameWithAbiTags(ND);
Out << 'M';
}
}
}
unsigned Number = Block->getBlockManglingNumber();
if (!Number)
Number = Context.getBlockId(Block, false);
else {
--Number;
}
Out << "Ub";
if (Number > 0)
Out << Number - 1;
Out << '_';
}
void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
if (Ty->isParameterPack())
Out << "Tp";
Out << "Ty";
} else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
if (Tn->isExpandedParameterPack()) {
for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
Out << "Tn";
mangleType(Tn->getExpansionType(I));
}
} else {
QualType T = Tn->getType();
if (Tn->isParameterPack()) {
Out << "Tp";
if (auto *PackExpansion = T->getAs<PackExpansionType>())
T = PackExpansion->getPattern();
}
Out << "Tn";
mangleType(T);
}
} else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
if (Tt->isExpandedParameterPack()) {
for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
++I) {
Out << "Tt";
for (auto *Param : *Tt->getExpansionTemplateParameters(I))
mangleTemplateParamDecl(Param);
Out << "E";
}
} else {
if (Tt->isParameterPack())
Out << "Tp";
Out << "Tt";
for (auto *Param : *Tt->getTemplateParameters())
mangleTemplateParamDecl(Param);
Out << "E";
}
}
}
void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
if (Decl *Context = Lambda->getLambdaContextDecl()) {
if (getASTContext().getLangOpts().getClangABICompat() <=
LangOptions::ClangABI::Ver12 &&
(isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
!isa<ParmVarDecl>(Context)) {
if (const IdentifierInfo *Name
= cast<NamedDecl>(Context)->getIdentifier()) {
mangleSourceName(Name);
const TemplateArgumentList *TemplateArgs = nullptr;
if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
Out << 'M';
}
}
}
Out << "Ul";
mangleLambdaSig(Lambda);
Out << "E";
llvm::Optional<unsigned> DeviceNumber =
Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
unsigned Number =
DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
assert(Number > 0 && "Lambda should be mangled as an unnamed class");
if (Number > 1)
mangleNumber(Number - 2);
Out << '_';
}
void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
mangleTemplateParamDecl(D);
auto *Proto =
Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();
mangleBareFunctionType(Proto, false,
Lambda->getLambdaStaticInvoker());
}
void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
switch (qualifier->getKind()) {
case NestedNameSpecifier::Global:
return;
case NestedNameSpecifier::Super:
llvm_unreachable("Can't mangle __super specifier");
case NestedNameSpecifier::Namespace:
mangleName(qualifier->getAsNamespace());
return;
case NestedNameSpecifier::NamespaceAlias:
mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
return;
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::TypeSpecWithTemplate:
manglePrefix(QualType(qualifier->getAsType(), 0));
return;
case NestedNameSpecifier::Identifier:
bool Clang14Compat = getASTContext().getLangOpts().getClangABICompat() <=
LangOptions::ClangABI::Ver14;
if (!Clang14Compat && mangleSubstitution(qualifier))
return;
assert(qualifier->getPrefix());
manglePrefix(qualifier->getPrefix());
mangleSourceName(qualifier->getAsIdentifier());
if (!Clang14Compat)
addSubstitution(qualifier);
return;
}
llvm_unreachable("unexpected nested name specifier");
}
void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
if (DC->isTranslationUnit())
return;
if (NoFunction && isLocalContainerContext(DC))
return;
assert(!isLocalContainerContext(DC));
const NamedDecl *ND = cast<NamedDecl>(DC);
if (mangleSubstitution(ND))
return;
const TemplateArgumentList *TemplateArgs = nullptr;
if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
mangleTemplatePrefix(TD);
mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
} else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
mangleClosurePrefix(PrefixND, NoFunction);
mangleUnqualifiedName(ND, nullptr, nullptr);
} else {
const DeclContext *DC = Context.getEffectiveDeclContext(ND);
manglePrefix(DC, NoFunction);
mangleUnqualifiedName(ND, DC, nullptr);
}
addSubstitution(ND);
}
void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
if (TemplateDecl *TD = Template.getAsTemplateDecl())
return mangleTemplatePrefix(TD);
DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
assert(Dependent && "unexpected template name kind");
bool Clang11Compat = getASTContext().getLangOpts().getClangABICompat() <=
LangOptions::ClangABI::Ver11;
if (!Clang11Compat && mangleSubstitution(Template))
return;
if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
manglePrefix(Qualifier);
if (Clang11Compat && mangleSubstitution(Template))
return;
if (const IdentifierInfo *Id = Dependent->getIdentifier())
mangleSourceName(Id);
else
mangleOperatorName(Dependent->getOperator(), UnknownArity);
addSubstitution(Template);
}
void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
bool NoFunction) {
const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
if (mangleSubstitution(ND))
return;
if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
} else {
const DeclContext *DC = Context.getEffectiveDeclContext(ND);
manglePrefix(DC, NoFunction);
if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
mangleUnqualifiedName(GD, DC, nullptr);
else
mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
nullptr);
}
addSubstitution(ND);
}
const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
if (getASTContext().getLangOpts().getClangABICompat() <=
LangOptions::ClangABI::Ver12)
return nullptr;
const NamedDecl *Context = nullptr;
if (auto *Block = dyn_cast<BlockDecl>(ND)) {
Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
} else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
if (RD->isLambda())
Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
}
if (!Context)
return nullptr;
if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
isa<FieldDecl>(Context))
return Context;
return nullptr;
}
void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
if (mangleSubstitution(ND))
return;
const TemplateArgumentList *TemplateArgs = nullptr;
if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
mangleTemplatePrefix(TD, NoFunction);
mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
} else {
const auto *DC = Context.getEffectiveDeclContext(ND);
manglePrefix(DC, NoFunction);
mangleUnqualifiedName(ND, DC, nullptr);
}
Out << 'M';
addSubstitution(ND);
}
void CXXNameMangler::mangleType(TemplateName TN) {
if (mangleSubstitution(TN))
return;
TemplateDecl *TD = nullptr;
switch (TN.getKind()) {
case TemplateName::QualifiedTemplate:
case TemplateName::UsingTemplate:
case TemplateName::Template:
TD = TN.getAsTemplateDecl();
goto HaveDecl;
HaveDecl:
if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
else
mangleName(TD);
break;
case TemplateName::OverloadedTemplate:
case TemplateName::AssumedTemplate:
llvm_unreachable("can't mangle an overloaded template name as a <type>");
case TemplateName::DependentTemplate: {
const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
assert(Dependent->isIdentifier());
mangleUnresolvedPrefix(Dependent->getQualifier());
mangleSourceName(Dependent->getIdentifier());
break;
}
case TemplateName::SubstTemplateTemplateParm: {
SubstTemplateTemplateParmStorage *subst
= TN.getAsSubstTemplateTemplateParm();
mangleType(subst->getReplacement());
return;
}
case TemplateName::SubstTemplateTemplateParmPack: {
Out << "_SUBSTPACK_";
break;
}
}
addSubstitution(TN);
}
bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
StringRef Prefix) {
switch (Ty->getTypeClass()) {
case Type::Builtin:
case Type::Complex:
case Type::Adjusted:
case Type::Decayed:
case Type::Pointer:
case Type::BlockPointer:
case Type::LValueReference:
case Type::RValueReference:
case Type::MemberPointer:
case Type::ConstantArray:
case Type::IncompleteArray:
case Type::VariableArray:
case Type::DependentSizedArray:
case Type::DependentAddressSpace:
case Type::DependentVector:
case Type::DependentSizedExtVector:
case Type::Vector:
case Type::ExtVector:
case Type::ConstantMatrix:
case Type::DependentSizedMatrix:
case Type::FunctionProto:
case Type::FunctionNoProto:
case Type::Paren:
case Type::Attributed:
case Type::BTFTagAttributed:
case Type::Auto:
case Type::DeducedTemplateSpecialization:
case Type::PackExpansion:
case Type::ObjCObject:
case Type::ObjCInterface:
case Type::ObjCObjectPointer:
case Type::ObjCTypeParam:
case Type::Atomic:
case Type::Pipe:
case Type::MacroQualified:
case Type::BitInt:
case Type::DependentBitInt:
llvm_unreachable("type is illegal as a nested name specifier");
case Type::SubstTemplateTypeParmPack:
Out << "_SUBSTPACK_";
break;
case Type::TypeOfExpr:
case Type::TypeOf:
case Type::Decltype:
case Type::TemplateTypeParm:
case Type::UnaryTransform:
case Type::SubstTemplateTypeParm:
unresolvedType:
Out << Prefix;
mangleType(Ty);
return true;
case Type::Typedef:
mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
break;
case Type::UnresolvedUsing:
mangleSourceNameWithAbiTags(
cast<UnresolvedUsingType>(Ty)->getDecl());
break;
case Type::Enum:
case Type::Record:
mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
break;
case Type::TemplateSpecialization: {
const TemplateSpecializationType *TST =
cast<TemplateSpecializationType>(Ty);
TemplateName TN = TST->getTemplateName();
switch (TN.getKind()) {
case TemplateName::Template:
case TemplateName::QualifiedTemplate: {
TemplateDecl *TD = TN.getAsTemplateDecl();
assert(TD && "no template for template specialization type");
if (isa<TemplateTemplateParmDecl>(TD))
goto unresolvedType;
mangleSourceNameWithAbiTags(TD);
break;
}
case TemplateName::OverloadedTemplate:
case TemplateName::AssumedTemplate:
case TemplateName::DependentTemplate:
llvm_unreachable("invalid base for a template specialization type");
case TemplateName::SubstTemplateTemplateParm: {
SubstTemplateTemplateParmStorage *subst =
TN.getAsSubstTemplateTemplateParm();
mangleExistingSubstitution(subst->getReplacement());
break;
}
case TemplateName::SubstTemplateTemplateParmPack: {
Out << "_SUBSTPACK_";
break;
}
case TemplateName::UsingTemplate: {
TemplateDecl *TD = TN.getAsTemplateDecl();
assert(TD && !isa<TemplateTemplateParmDecl>(TD));
mangleSourceNameWithAbiTags(TD);
break;
}
}
mangleTemplateArgs(TemplateName(), TST->getArgs(), TST->getNumArgs());
break;
}
case Type::InjectedClassName:
mangleSourceNameWithAbiTags(
cast<InjectedClassNameType>(Ty)->getDecl());
break;
case Type::DependentName:
mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
break;
case Type::DependentTemplateSpecialization: {
const DependentTemplateSpecializationType *DTST =
cast<DependentTemplateSpecializationType>(Ty);
TemplateName Template = getASTContext().getDependentTemplateName(
DTST->getQualifier(), DTST->getIdentifier());
mangleSourceName(DTST->getIdentifier());
mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
break;
}
case Type::Using:
return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
Prefix);
case Type::Elaborated:
return mangleUnresolvedTypeOrSimpleId(
cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
}
return false;
}
void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
switch (Name.getNameKind()) {
case DeclarationName::CXXConstructorName:
case DeclarationName::CXXDestructorName:
case DeclarationName::CXXDeductionGuideName:
case DeclarationName::CXXUsingDirective:
case DeclarationName::Identifier:
case DeclarationName::ObjCMultiArgSelector:
case DeclarationName::ObjCOneArgSelector:
case DeclarationName::ObjCZeroArgSelector:
llvm_unreachable("Not an operator name");
case DeclarationName::CXXConversionFunctionName:
Out << "cv";
mangleType(Name.getCXXNameType());
break;
case DeclarationName::CXXLiteralOperatorName:
Out << "li";
mangleSourceName(Name.getCXXLiteralIdentifier());
return;
case DeclarationName::CXXOperatorName:
mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
break;
}
}
void
CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
switch (OO) {
case OO_New: Out << "nw"; break;
case OO_Array_New: Out << "na"; break;
case OO_Delete: Out << "dl"; break;
case OO_Array_Delete: Out << "da"; break;
case OO_Plus:
Out << (Arity == 1? "ps" : "pl"); break;
case OO_Minus:
Out << (Arity == 1? "ng" : "mi"); break;
case OO_Amp:
Out << (Arity == 1? "ad" : "an"); break;
case OO_Star:
Out << (Arity == 1? "de" : "ml"); break;
case OO_Tilde: Out << "co"; break;
case OO_Slash: Out << "dv"; break;
case OO_Percent: Out << "rm"; break;
case OO_Pipe: Out << "or"; break;
case OO_Caret: Out << "eo"; break;
case OO_Equal: Out << "aS"; break;
case OO_PlusEqual: Out << "pL"; break;
case OO_MinusEqual: Out << "mI"; break;
case OO_StarEqual: Out << "mL"; break;
case OO_SlashEqual: Out << "dV"; break;
case OO_PercentEqual: Out << "rM"; break;
case OO_AmpEqual: Out << "aN"; break;
case OO_PipeEqual: Out << "oR"; break;
case OO_CaretEqual: Out << "eO"; break;
case OO_LessLess: Out << "ls"; break;
case OO_GreaterGreater: Out << "rs"; break;
case OO_LessLessEqual: Out << "lS"; break;
case OO_GreaterGreaterEqual: Out << "rS"; break;
case OO_EqualEqual: Out << "eq"; break;
case OO_ExclaimEqual: Out << "ne"; break;
case OO_Less: Out << "lt"; break;
case OO_Greater: Out << "gt"; break;
case OO_LessEqual: Out << "le"; break;
case OO_GreaterEqual: Out << "ge"; break;
case OO_Exclaim: Out << "nt"; break;
case OO_AmpAmp: Out << "aa"; break;
case OO_PipePipe: Out << "oo"; break;
case OO_PlusPlus: Out << "pp"; break;
case OO_MinusMinus: Out << "mm"; break;
case OO_Comma: Out << "cm"; break;
case OO_ArrowStar: Out << "pm"; break;
case OO_Arrow: Out << "pt"; break;
case OO_Call: Out << "cl"; break;
case OO_Subscript: Out << "ix"; break;
case OO_Conditional: Out << "qu"; break;
case OO_Coawait: Out << "aw"; break;
case OO_Spaceship: Out << "ss"; break;
case OO_None:
case NUM_OVERLOADED_OPERATORS:
llvm_unreachable("Not an overloaded operator");
}
}
void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
if (DAST) {
Out << "U2ASI";
mangleExpression(DAST->getAddrSpaceExpr());
Out << "E";
}
if (Quals.hasAddressSpace()) {
SmallString<64> ASString;
LangAS AS = Quals.getAddressSpace();
if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
if (TargetAS != 0 ||
Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
ASString = "AS" + llvm::utostr(TargetAS);
} else {
switch (AS) {
default: llvm_unreachable("Not a language specific address space");
case LangAS::opencl_global:
ASString = "CLglobal";
break;
case LangAS::opencl_global_device:
ASString = "CLdevice";
break;
case LangAS::opencl_global_host:
ASString = "CLhost";
break;
case LangAS::opencl_local:
ASString = "CLlocal";
break;
case LangAS::opencl_constant:
ASString = "CLconstant";
break;
case LangAS::opencl_private:
ASString = "CLprivate";
break;
case LangAS::opencl_generic:
ASString = "CLgeneric";
break;
case LangAS::sycl_global:
ASString = "SYglobal";
break;
case LangAS::sycl_global_device:
ASString = "SYdevice";
break;
case LangAS::sycl_global_host:
ASString = "SYhost";
break;
case LangAS::sycl_local:
ASString = "SYlocal";
break;
case LangAS::sycl_private:
ASString = "SYprivate";
break;
case LangAS::cuda_device:
ASString = "CUdevice";
break;
case LangAS::cuda_constant:
ASString = "CUconstant";
break;
case LangAS::cuda_shared:
ASString = "CUshared";
break;
case LangAS::ptr32_sptr:
ASString = "ptr32_sptr";
break;
case LangAS::ptr32_uptr:
ASString = "ptr32_uptr";
break;
case LangAS::ptr64:
ASString = "ptr64";
break;
}
}
if (!ASString.empty())
mangleVendorQualifier(ASString);
}
if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
mangleVendorQualifier("__weak");
if (Quals.hasUnaligned())
mangleVendorQualifier("__unaligned");
switch (Quals.getObjCLifetime()) {
case Qualifiers::OCL_None:
break;
case Qualifiers::OCL_Weak:
break;
case Qualifiers::OCL_Strong:
mangleVendorQualifier("__strong");
break;
case Qualifiers::OCL_Autoreleasing:
mangleVendorQualifier("__autoreleasing");
break;
case Qualifiers::OCL_ExplicitNone:
break;
}
if (Quals.hasRestrict())
Out << 'r';
if (Quals.hasVolatile())
Out << 'V';
if (Quals.hasConst())
Out << 'K';
}
void CXXNameMangler::mangleVendorQualifier(StringRef name) {
Out << 'U' << name.size() << name;
}
void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
switch (RefQualifier) {
case RQ_None:
break;
case RQ_LValue:
Out << 'R';
break;
case RQ_RValue:
Out << 'O';
break;
}
}
void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
Context.mangleObjCMethodNameAsSourceName(MD, Out);
}
static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
ASTContext &Ctx) {
if (Quals)
return true;
if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
return true;
if (Ty->isOpenCLSpecificType())
return true;
if (Ty->isBuiltinType())
return false;
if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
isa<AutoType>(Ty))
return false;
if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
if (DeducedTST->getDeducedType().isNull())
return false;
return true;
}
void CXXNameMangler::mangleType(QualType T) {
if (!T->isInstantiationDependentType() || T->isDependentType())
T = T.getCanonicalType();
else {
do {
if (const TemplateSpecializationType *TST
= dyn_cast<TemplateSpecializationType>(T))
if (!TST->isTypeAlias())
break;
QualType Desugared
= T.getSingleStepDesugaredType(Context.getASTContext());
if (Desugared == T)
break;
T = Desugared;
} while (true);
}
SplitQualType split = T.split();
Qualifiers quals = split.Quals;
const Type *ty = split.Ty;
bool isSubstitutable =
isTypeSubstitutable(quals, ty, Context.getASTContext());
if (isSubstitutable && mangleSubstitution(T))
return;
if (quals && isa<ArrayType>(T)) {
ty = Context.getASTContext().getAsArrayType(T);
quals = Qualifiers();
}
if (quals || ty->isDependentAddressSpaceType()) {
if (const DependentAddressSpaceType *DAST =
dyn_cast<DependentAddressSpaceType>(ty)) {
SplitQualType splitDAST = DAST->getPointeeType().split();
mangleQualifiers(splitDAST.Quals, DAST);
mangleType(QualType(splitDAST.Ty, 0));
} else {
mangleQualifiers(quals);
mangleType(QualType(ty, 0));
}
} else {
switch (ty->getTypeClass()) {
#define ABSTRACT_TYPE(CLASS, PARENT)
#define NON_CANONICAL_TYPE(CLASS, PARENT) \
case Type::CLASS: \
llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
return;
#define TYPE(CLASS, PARENT) \
case Type::CLASS: \
mangleType(static_cast<const CLASS##Type*>(ty)); \
break;
#include "clang/AST/TypeNodes.inc"
}
}
if (isSubstitutable)
addSubstitution(T);
}
void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
if (!mangleStandardSubstitution(ND))
mangleName(ND);
}
void CXXNameMangler::mangleType(const BuiltinType *T) {
std::string type_name;
switch (T->getKind()) {
case BuiltinType::Void:
Out << 'v';
break;
case BuiltinType::Bool:
Out << 'b';
break;
case BuiltinType::Char_U:
case BuiltinType::Char_S:
Out << 'c';
break;
case BuiltinType::UChar:
Out << 'h';
break;
case BuiltinType::UShort:
Out << 't';
break;
case BuiltinType::UInt:
Out << 'j';
break;
case BuiltinType::ULong:
Out << 'm';
break;
case BuiltinType::ULongLong:
Out << 'y';
break;
case BuiltinType::UInt128:
Out << 'o';
break;
case BuiltinType::SChar:
Out << 'a';
break;
case BuiltinType::WChar_S:
case BuiltinType::WChar_U:
Out << 'w';
break;
case BuiltinType::Char8:
Out << "Du";
break;
case BuiltinType::Char16:
Out << "Ds";
break;
case BuiltinType::Char32:
Out << "Di";
break;
case BuiltinType::Short:
Out << 's';
break;
case BuiltinType::Int:
Out << 'i';
break;
case BuiltinType::Long:
Out << 'l';
break;
case BuiltinType::LongLong:
Out << 'x';
break;
case BuiltinType::Int128:
Out << 'n';
break;
case BuiltinType::Float16:
Out << "DF16_";
break;
case BuiltinType::ShortAccum:
case BuiltinType::Accum:
case BuiltinType::LongAccum:
case BuiltinType::UShortAccum:
case BuiltinType::UAccum:
case BuiltinType::ULongAccum:
case BuiltinType::ShortFract:
case BuiltinType::Fract:
case BuiltinType::LongFract:
case BuiltinType::UShortFract:
case BuiltinType::UFract:
case BuiltinType::ULongFract:
case BuiltinType::SatShortAccum:
case BuiltinType::SatAccum:
case BuiltinType::SatLongAccum:
case BuiltinType::SatUShortAccum:
case BuiltinType::SatUAccum:
case BuiltinType::SatULongAccum:
case BuiltinType::SatShortFract:
case BuiltinType::SatFract:
case BuiltinType::SatLongFract:
case BuiltinType::SatUShortFract:
case BuiltinType::SatUFract:
case BuiltinType::SatULongFract:
llvm_unreachable("Fixed point types are disabled for c++");
case BuiltinType::Half:
Out << "Dh";
break;
case BuiltinType::Float:
Out << 'f';
break;
case BuiltinType::Double:
Out << 'd';
break;
case BuiltinType::LongDouble: {
const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
getASTContext().getLangOpts().OpenMPIsDevice
? getASTContext().getAuxTargetInfo()
: &getASTContext().getTargetInfo();
Out << TI->getLongDoubleMangling();
break;
}
case BuiltinType::Float128: {
const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
getASTContext().getLangOpts().OpenMPIsDevice
? getASTContext().getAuxTargetInfo()
: &getASTContext().getTargetInfo();
Out << TI->getFloat128Mangling();
break;
}
case BuiltinType::BFloat16: {
const TargetInfo *TI = &getASTContext().getTargetInfo();
Out << TI->getBFloat16Mangling();
break;
}
case BuiltinType::Ibm128: {
const TargetInfo *TI = &getASTContext().getTargetInfo();
Out << TI->getIbm128Mangling();
break;
}
case BuiltinType::NullPtr:
Out << "Dn";
break;
#define BUILTIN_TYPE(Id, SingletonId)
#define PLACEHOLDER_TYPE(Id, SingletonId) \
case BuiltinType::Id:
#include "clang/AST/BuiltinTypes.def"
case BuiltinType::Dependent:
if (!NullOut)
llvm_unreachable("mangling a placeholder type");
break;
case BuiltinType::ObjCId:
Out << "11objc_object";
break;
case BuiltinType::ObjCClass:
Out << "10objc_class";
break;
case BuiltinType::ObjCSel:
Out << "13objc_selector";
break;
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
case BuiltinType::Id: \
type_name = "ocl_" #ImgType "_" #Suffix; \
Out << type_name.size() << type_name; \
break;
#include "clang/Basic/OpenCLImageTypes.def"
case BuiltinType::OCLSampler:
Out << "11ocl_sampler";
break;
case BuiltinType::OCLEvent:
Out << "9ocl_event";
break;
case BuiltinType::OCLClkEvent:
Out << "12ocl_clkevent";
break;
case BuiltinType::OCLQueue:
Out << "9ocl_queue";
break;
case BuiltinType::OCLReserveID:
Out << "13ocl_reserveid";
break;
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
case BuiltinType::Id: \
type_name = "ocl_" #ExtType; \
Out << type_name.size() << type_name; \
break;
#include "clang/Basic/OpenCLExtensionTypes.def"
#define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \
ElBits, IsSigned, IsFP, IsBF) \
case BuiltinType::Id: \
type_name = MangledName; \
Out << (type_name == InternalName ? "u" : "") << type_name.size() \
<< type_name; \
break;
#define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
case BuiltinType::Id: \
type_name = MangledName; \
Out << (type_name == InternalName ? "u" : "") << type_name.size() \
<< type_name; \
break;
#include "clang/Basic/AArch64SVEACLETypes.def"
#define PPC_VECTOR_TYPE(Name, Id, Size) \
case BuiltinType::Id: \
type_name = #Name; \
Out << 'u' << type_name.size() << type_name; \
break;
#include "clang/Basic/PPCTypes.def"
#define RVV_TYPE(Name, Id, SingletonId) \
case BuiltinType::Id: \
type_name = Name; \
Out << 'u' << type_name.size() << type_name; \
break;
#include "clang/Basic/RISCVVTypes.def"
}
}
StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
switch (CC) {
case CC_C:
return "";
case CC_X86VectorCall:
case CC_X86Pascal:
case CC_X86RegCall:
case CC_AAPCS:
case CC_AAPCS_VFP:
case CC_AArch64VectorCall:
case CC_AArch64SVEPCS:
case CC_AMDGPUKernelCall:
case CC_IntelOclBicc:
case CC_SpirFunction:
case CC_OpenCLKernel:
case CC_PreserveMost:
case CC_PreserveAll:
return "";
case CC_X86ThisCall:
return "";
case CC_X86StdCall:
return "stdcall";
case CC_X86FastCall:
return "fastcall";
case CC_X86_64SysV:
return "sysv_abi";
case CC_Win64:
return "ms_abi";
case CC_Swift:
return "swiftcall";
case CC_SwiftAsync:
return "swiftasynccall";
}
llvm_unreachable("bad calling convention");
}
void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
if (T->getExtInfo() == FunctionType::ExtInfo())
return;
StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
if (!CCQualifier.empty())
mangleVendorQualifier(CCQualifier);
}
void
CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
switch (PI.getABI()) {
case ParameterABI::Ordinary:
break;
case ParameterABI::SwiftContext:
case ParameterABI::SwiftAsyncContext:
case ParameterABI::SwiftErrorResult:
case ParameterABI::SwiftIndirectResult:
mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
break;
}
if (PI.isConsumed())
mangleVendorQualifier("ns_consumed");
if (PI.isNoEscape())
mangleVendorQualifier("noescape");
}
void CXXNameMangler::mangleType(const FunctionProtoType *T) {
mangleExtFunctionInfo(T);
mangleQualifiers(T->getMethodQuals());
if (T->hasInstantiationDependentExceptionSpec()) {
if (isComputedNoexcept(T->getExceptionSpecType())) {
Out << "DO";
mangleExpression(T->getNoexceptExpr());
Out << "E";
} else {
assert(T->getExceptionSpecType() == EST_Dynamic);
Out << "Dw";
for (auto ExceptTy : T->exceptions())
mangleType(ExceptTy);
Out << "E";
}
} else if (T->isNothrow()) {
Out << "Do";
}
Out << 'F';
mangleBareFunctionType(T, true);
mangleRefQualifier(T->getRefQualifier());
Out << 'E';
}
void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Out << 'F';
FunctionTypeDepthState saved = FunctionTypeDepth.push();
FunctionTypeDepth.enterResultType();
mangleType(T->getReturnType());
FunctionTypeDepth.leaveResultType();
FunctionTypeDepth.pop(saved);
Out << 'E';
}
void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
bool MangleReturnType,
const FunctionDecl *FD) {
FunctionTypeDepthState saved = FunctionTypeDepth.push();
if (MangleReturnType) {
FunctionTypeDepth.enterResultType();
if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
mangleVendorQualifier("ns_returns_retained");
QualType ReturnTy = Proto->getReturnType();
if (ReturnTy.getObjCLifetime()) {
auto SplitReturnTy = ReturnTy.split();
SplitReturnTy.Quals.removeObjCLifetime();
ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
}
mangleType(ReturnTy);
FunctionTypeDepth.leaveResultType();
}
if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Out << 'v';
FunctionTypeDepth.pop(saved);
return;
}
assert(!FD || FD->getNumParams() == Proto->getNumParams());
for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
if (Proto->hasExtParameterInfos() && FD == nullptr) {
mangleExtParameterInfo(Proto->getExtParameterInfo(I));
}
QualType ParamTy = Proto->getParamType(I);
mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
if (FD) {
if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
assert(Attr->getType() <= 9 && Attr->getType() >= 0);
if (Attr->isDynamic())
Out << "U25pass_dynamic_object_size" << Attr->getType();
else
Out << "U17pass_object_size" << Attr->getType();
}
}
}
FunctionTypeDepth.pop(saved);
if (Proto->isVariadic())
Out << 'z';
}
void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
mangleName(T->getDecl());
}
void CXXNameMangler::mangleType(const EnumType *T) {
mangleType(static_cast<const TagType*>(T));
}
void CXXNameMangler::mangleType(const RecordType *T) {
mangleType(static_cast<const TagType*>(T));
}
void CXXNameMangler::mangleType(const TagType *T) {
mangleName(T->getDecl());
}
void CXXNameMangler::mangleType(const ConstantArrayType *T) {
Out << 'A' << T->getSize() << '_';
mangleType(T->getElementType());
}
void CXXNameMangler::mangleType(const VariableArrayType *T) {
Out << 'A';
if (T->getSizeExpr())
mangleExpression(T->getSizeExpr());
Out << '_';
mangleType(T->getElementType());
}
void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
Out << 'A';
if (T->getSizeExpr())
mangleExpression(T->getSizeExpr());
Out << '_';
mangleType(T->getElementType());
}
void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
Out << "A_";
mangleType(T->getElementType());
}
void CXXNameMangler::mangleType(const MemberPointerType *T) {
Out << 'M';
mangleType(QualType(T->getClass(), 0));
QualType PointeeType = T->getPointeeType();
if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
mangleType(FPT);
++SeqID;
} else
mangleType(PointeeType);
}
void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
mangleTemplateParameter(T->getDepth(), T->getIndex());
}
void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
Out << "_SUBSTPACK_";
}
void CXXNameMangler::mangleType(const PointerType *T) {
Out << 'P';
mangleType(T->getPointeeType());
}
void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
Out << 'P';
mangleType(T->getPointeeType());
}
void CXXNameMangler::mangleType(const LValueReferenceType *T) {
Out << 'R';
mangleType(T->getPointeeType());
}
void CXXNameMangler::mangleType(const RValueReferenceType *T) {
Out << 'O';
mangleType(T->getPointeeType());
}
void CXXNameMangler::mangleType(const ComplexType *T) {
Out << 'C';
mangleType(T->getElementType());
}
void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
QualType EltType = T->getElementType();
assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
const char *EltName = nullptr;
if (T->getVectorKind() == VectorType::NeonPolyVector) {
switch (cast<BuiltinType>(EltType)->getKind()) {
case BuiltinType::SChar:
case BuiltinType::UChar:
EltName = "poly8_t";
break;
case BuiltinType::Short:
case BuiltinType::UShort:
EltName = "poly16_t";
break;
case BuiltinType::LongLong:
case BuiltinType::ULongLong:
EltName = "poly64_t";
break;
default: llvm_unreachable("unexpected Neon polynomial vector element type");
}
} else {
switch (cast<BuiltinType>(EltType)->getKind()) {
case BuiltinType::SChar: EltName = "int8_t"; break;
case BuiltinType::UChar: EltName = "uint8_t"; break;
case BuiltinType::Short: EltName = "int16_t"; break;
case BuiltinType::UShort: EltName = "uint16_t"; break;
case BuiltinType::Int: EltName = "int32_t"; break;
case BuiltinType::UInt: EltName = "uint32_t"; break;
case BuiltinType::LongLong: EltName = "int64_t"; break;
case BuiltinType::ULongLong: EltName = "uint64_t"; break;
case BuiltinType::Double: EltName = "float64_t"; break;
case BuiltinType::Float: EltName = "float32_t"; break;
case BuiltinType::Half: EltName = "float16_t"; break;
case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
default:
llvm_unreachable("unexpected Neon vector element type");
}
}
const char *BaseName = nullptr;
unsigned BitSize = (T->getNumElements() *
getASTContext().getTypeSize(EltType));
if (BitSize == 64)
BaseName = "__simd64_";
else {
assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
BaseName = "__simd128_";
}
Out << strlen(BaseName) + strlen(EltName);
Out << BaseName << EltName;
}
void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
DiagnosticsEngine &Diags = Context.getDiags();
unsigned DiagID = Diags.getCustomDiagID(
DiagnosticsEngine::Error,
"cannot mangle this dependent neon vector type yet");
Diags.Report(T->getAttributeLoc(), DiagID);
}
static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
switch (EltType->getKind()) {
case BuiltinType::SChar:
return "Int8";
case BuiltinType::Short:
return "Int16";
case BuiltinType::Int:
return "Int32";
case BuiltinType::Long:
case BuiltinType::LongLong:
return "Int64";
case BuiltinType::UChar:
return "Uint8";
case BuiltinType::UShort:
return "Uint16";
case BuiltinType::UInt:
return "Uint32";
case BuiltinType::ULong:
case BuiltinType::ULongLong:
return "Uint64";
case BuiltinType::Half:
return "Float16";
case BuiltinType::Float:
return "Float32";
case BuiltinType::Double:
return "Float64";
case BuiltinType::BFloat16:
return "Bfloat16";
default:
llvm_unreachable("Unexpected vector element base type");
}
}
void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
QualType EltType = T->getElementType();
assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
unsigned BitSize =
(T->getNumElements() * getASTContext().getTypeSize(EltType));
(void)BitSize;
assert((BitSize == 64 || BitSize == 128) &&
"Neon vector type not 64 or 128 bits");
StringRef EltName;
if (T->getVectorKind() == VectorType::NeonPolyVector) {
switch (cast<BuiltinType>(EltType)->getKind()) {
case BuiltinType::UChar:
EltName = "Poly8";
break;
case BuiltinType::UShort:
EltName = "Poly16";
break;
case BuiltinType::ULong:
case BuiltinType::ULongLong:
EltName = "Poly64";
break;
default:
llvm_unreachable("unexpected Neon polynomial vector element type");
}
} else
EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
std::string TypeName =
("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Out << TypeName.length() << TypeName;
}
void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
DiagnosticsEngine &Diags = Context.getDiags();
unsigned DiagID = Diags.getCustomDiagID(
DiagnosticsEngine::Error,
"cannot mangle this dependent neon vector type yet");
Diags.Report(T->getAttributeLoc(), DiagID);
}
void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
assert((T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) &&
"expected fixed-length SVE vector!");
QualType EltType = T->getElementType();
assert(EltType->isBuiltinType() &&
"expected builtin type for fixed-length SVE vector!");
StringRef TypeName;
switch (cast<BuiltinType>(EltType)->getKind()) {
case BuiltinType::SChar:
TypeName = "__SVInt8_t";
break;
case BuiltinType::UChar: {
if (T->getVectorKind() == VectorType::SveFixedLengthDataVector)
TypeName = "__SVUint8_t";
else
TypeName = "__SVBool_t";
break;
}
case BuiltinType::Short:
TypeName = "__SVInt16_t";
break;
case BuiltinType::UShort:
TypeName = "__SVUint16_t";
break;
case BuiltinType::Int:
TypeName = "__SVInt32_t";
break;
case BuiltinType::UInt:
TypeName = "__SVUint32_t";
break;
case BuiltinType::Long:
TypeName = "__SVInt64_t";
break;
case BuiltinType::ULong:
TypeName = "__SVUint64_t";
break;
case BuiltinType::Half:
TypeName = "__SVFloat16_t";
break;
case BuiltinType::Float:
TypeName = "__SVFloat32_t";
break;
case BuiltinType::Double:
TypeName = "__SVFloat64_t";
break;
case BuiltinType::BFloat16:
TypeName = "__SVBfloat16_t";
break;
default:
llvm_unreachable("unexpected element type for fixed-length SVE vector!");
}
unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
VecSizeInBits *= 8;
Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
<< VecSizeInBits << "EE";
}
void CXXNameMangler::mangleAArch64FixedSveVectorType(
const DependentVectorType *T) {
DiagnosticsEngine &Diags = Context.getDiags();
unsigned DiagID = Diags.getCustomDiagID(
DiagnosticsEngine::Error,
"cannot mangle this dependent fixed-length SVE vector type yet");
Diags.Report(T->getAttributeLoc(), DiagID);
}
void CXXNameMangler::mangleType(const VectorType *T) {
if ((T->getVectorKind() == VectorType::NeonVector ||
T->getVectorKind() == VectorType::NeonPolyVector)) {
llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
llvm::Triple::ArchType Arch =
getASTContext().getTargetInfo().getTriple().getArch();
if ((Arch == llvm::Triple::aarch64 ||
Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
mangleAArch64NeonVectorType(T);
else
mangleNeonVectorType(T);
return;
} else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
mangleAArch64FixedSveVectorType(T);
return;
}
Out << "Dv" << T->getNumElements() << '_';
if (T->getVectorKind() == VectorType::AltiVecPixel)
Out << 'p';
else if (T->getVectorKind() == VectorType::AltiVecBool)
Out << 'b';
else
mangleType(T->getElementType());
}
void CXXNameMangler::mangleType(const DependentVectorType *T) {
if ((T->getVectorKind() == VectorType::NeonVector ||
T->getVectorKind() == VectorType::NeonPolyVector)) {
llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
llvm::Triple::ArchType Arch =
getASTContext().getTargetInfo().getTriple().getArch();
if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
!Target.isOSDarwin())
mangleAArch64NeonVectorType(T);
else
mangleNeonVectorType(T);
return;
} else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
mangleAArch64FixedSveVectorType(T);
return;
}
Out << "Dv";
mangleExpression(T->getSizeExpr());
Out << '_';
if (T->getVectorKind() == VectorType::AltiVecPixel)
Out << 'p';
else if (T->getVectorKind() == VectorType::AltiVecBool)
Out << 'b';
else
mangleType(T->getElementType());
}
void CXXNameMangler::mangleType(const ExtVectorType *T) {
mangleType(static_cast<const VectorType*>(T));
}
void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
Out << "Dv";
mangleExpression(T->getSizeExpr());
Out << '_';
mangleType(T->getElementType());
}
void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
StringRef VendorQualifier = "matrix_type";
Out << "u" << VendorQualifier.size() << VendorQualifier;
Out << "I";
auto &ASTCtx = getASTContext();
unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
llvm::APSInt Rows(BitWidth);
Rows = T->getNumRows();
mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
llvm::APSInt Columns(BitWidth);
Columns = T->getNumColumns();
mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
mangleType(T->getElementType());
Out << "E";
}
void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
StringRef VendorQualifier = "matrix_type";
Out << "u" << VendorQualifier.size() << VendorQualifier;
Out << "I";
mangleTemplateArgExpr(T->getRowExpr());
mangleTemplateArgExpr(T->getColumnExpr());
mangleType(T->getElementType());
Out << "E";
}
void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
SplitQualType split = T->getPointeeType().split();
mangleQualifiers(split.Quals, T);
mangleType(QualType(split.Ty, 0));
}
void CXXNameMangler::mangleType(const PackExpansionType *T) {
Out << "Dp";
mangleType(T->getPattern());
}
void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
mangleSourceName(T->getDecl()->getIdentifier());
}
void CXXNameMangler::mangleType(const ObjCObjectType *T) {
if (T->isKindOfType())
Out << "U8__kindof";
if (!T->qual_empty()) {
SmallString<64> QualStr;
llvm::raw_svector_ostream QualOS(QualStr);
QualOS << "objcproto";
for (const auto *I : T->quals()) {
StringRef name = I->getName();
QualOS << name.size() << name;
}
Out << 'U' << QualStr.size() << QualStr;
}
mangleType(T->getBaseType());
if (T->isSpecialized()) {
Out << 'I';
for (auto typeArg : T->getTypeArgs())
mangleType(typeArg);
Out << 'E';
}
}
void CXXNameMangler::mangleType(const BlockPointerType *T) {
Out << "U13block_pointer";
mangleType(T->getPointeeType());
}
void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
mangleType(T->getInjectedSpecializationType());
}
void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
} else {
if (mangleSubstitution(QualType(T, 0)))
return;
mangleTemplatePrefix(T->getTemplateName());
mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs());
addSubstitution(QualType(T, 0));
}
}
void CXXNameMangler::mangleType(const DependentNameType *T) {
switch (T->getKeyword()) {
case ETK_None:
case ETK_Typename:
break;
case ETK_Struct:
case ETK_Class:
case ETK_Interface:
Out << "Ts";
break;
case ETK_Union:
Out << "Tu";
break;
case ETK_Enum:
Out << "Te";
break;
}
Out << 'N';
manglePrefix(T->getQualifier());
mangleSourceName(T->getIdentifier());
Out << 'E';
}
void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
Out << 'N';
TemplateName Prefix =
getASTContext().getDependentTemplateName(T->getQualifier(),
T->getIdentifier());
mangleTemplatePrefix(Prefix);
mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs());
Out << 'E';
}
void CXXNameMangler::mangleType(const TypeOfType *T) {
Out << "u6typeof";
}
void CXXNameMangler::mangleType(const TypeOfExprType *T) {
Out << "u6typeof";
}
void CXXNameMangler::mangleType(const DecltypeType *T) {
Expr *E = T->getUnderlyingExpr();
if (isa<DeclRefExpr>(E) ||
isa<MemberExpr>(E) ||
isa<UnresolvedLookupExpr>(E) ||
isa<DependentScopeDeclRefExpr>(E) ||
isa<CXXDependentScopeMemberExpr>(E) ||
isa<UnresolvedMemberExpr>(E))
Out << "Dt";
else
Out << "DT";
mangleExpression(E);
Out << 'E';
}
void CXXNameMangler::mangleType(const UnaryTransformType *T) {
if (T->isDependentType()) {
Out << 'U';
switch (T->getUTTKind()) {
case UnaryTransformType::EnumUnderlyingType:
Out << "3eut";
break;
}
}
mangleType(T->getBaseType());
}
void CXXNameMangler::mangleType(const AutoType *T) {
assert(T->getDeducedType().isNull() &&
"Deduced AutoType shouldn't be handled here!");
assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
"shouldn't need to mangle __auto_type!");
Out << (T->isDecltypeAuto() ? "Dc" : "Da");
}
void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
QualType Deduced = T->getDeducedType();
if (!Deduced.isNull())
return mangleType(Deduced);
TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
assert(TD && "shouldn't form deduced TST unless we know we have a template");
if (mangleSubstitution(TD))
return;
mangleName(GlobalDecl(TD));
addSubstitution(TD);
}
void CXXNameMangler::mangleType(const AtomicType *T) {
Out << "U7_Atomic";
mangleType(T->getValueType());
}
void CXXNameMangler::mangleType(const PipeType *T) {
Out << "8ocl_pipe";
}
void CXXNameMangler::mangleType(const BitIntType *T) {
Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
}
void CXXNameMangler::mangleType(const DependentBitIntType *T) {
Out << "D" << (T->isUnsigned() ? "U" : "B");
mangleExpression(T->getNumBitsExpr());
Out << "_";
}
void CXXNameMangler::mangleIntegerLiteral(QualType T,
const llvm::APSInt &Value) {
Out << 'L';
mangleType(T);
if (T->isBooleanType()) {
Out << (Value.getBoolValue() ? '1' : '0');
} else {
mangleNumber(Value);
}
Out << 'E';
}
void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
while (const auto *RT = Base->getType()->getAs<RecordType>()) {
if (!RT->getDecl()->isAnonymousStructOrUnion())
break;
const auto *ME = dyn_cast<MemberExpr>(Base);
if (!ME)
break;
Base = ME->getBase();
IsArrow = ME->isArrow();
}
if (Base->isImplicitCXXThis()) {
Out << "dtdefpT";
} else {
Out << (IsArrow ? "pt" : "dt");
mangleExpression(Base);
}
}
void CXXNameMangler::mangleMemberExpr(const Expr *base,
bool isArrow,
NestedNameSpecifier *qualifier,
NamedDecl *firstQualifierLookup,
DeclarationName member,
const TemplateArgumentLoc *TemplateArgs,
unsigned NumTemplateArgs,
unsigned arity) {
if (base)
mangleMemberExprBase(base, isArrow);
mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
}
static bool isParenthesizedADLCallee(const CallExpr *call) {
const Expr *callee = call->getCallee();
const Expr *fn = callee->IgnoreParens();
if (callee == fn) return false;
const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
if (!lookup) return false;
assert(!lookup->requiresADL());
if (lookup->getQualifier()) return false;
if (lookup->getNumDecls() > 0 &&
(*lookup->decls_begin())->isCXXClassMember())
return false;
return true;
}
void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
Out << CastEncoding;
mangleType(ECE->getType());
mangleExpression(ECE->getSubExpr());
}
void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
if (auto *Syntactic = InitList->getSyntacticForm())
InitList = Syntactic;
for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
mangleExpression(InitList->getInit(i));
}
void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
bool AsTemplateArg) {
QualType ImplicitlyConvertedToType;
bool IsPrimaryExpr = true;
auto NotPrimaryExpr = [&] {
if (AsTemplateArg && IsPrimaryExpr)
Out << 'X';
IsPrimaryExpr = false;
};
auto MangleDeclRefExpr = [&](const NamedDecl *D) {
switch (D->getKind()) {
default:
Out << 'L';
mangle(D);
Out << 'E';
break;
case Decl::ParmVar:
NotPrimaryExpr();
mangleFunctionParam(cast<ParmVarDecl>(D));
break;
case Decl::EnumConstant: {
const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
mangleIntegerLiteral(ED->getType(), ED->getInitVal());
break;
}
case Decl::NonTypeTemplateParm:
NotPrimaryExpr();
const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
mangleTemplateParameter(PD->getDepth(), PD->getIndex());
break;
}
};
recurse:
switch (E->getStmtClass()) {
case Expr::NoStmtClass:
#define ABSTRACT_STMT(Type)
#define EXPR(Type, Base)
#define STMT(Type, Base) \
case Expr::Type##Class:
#include "clang/AST/StmtNodes.inc"
case Expr::AddrLabelExprClass:
case Expr::DesignatedInitUpdateExprClass:
case Expr::ImplicitValueInitExprClass:
case Expr::ArrayInitLoopExprClass:
case Expr::ArrayInitIndexExprClass:
case Expr::NoInitExprClass:
case Expr::ParenListExprClass:
case Expr::MSPropertyRefExprClass:
case Expr::MSPropertySubscriptExprClass:
case Expr::TypoExprClass: case Expr::RecoveryExprClass:
case Expr::OMPArraySectionExprClass:
case Expr::OMPArrayShapingExprClass:
case Expr::OMPIteratorExprClass:
case Expr::CXXInheritedCtorInitExprClass:
llvm_unreachable("unexpected statement kind");
case Expr::ConstantExprClass:
E = cast<ConstantExpr>(E)->getSubExpr();
goto recurse;
case Expr::BlockExprClass:
case Expr::ChooseExprClass:
case Expr::CompoundLiteralExprClass:
case Expr::ExtVectorElementExprClass:
case Expr::GenericSelectionExprClass:
case Expr::ObjCEncodeExprClass:
case Expr::ObjCIsaExprClass:
case Expr::ObjCIvarRefExprClass:
case Expr::ObjCMessageExprClass:
case Expr::ObjCPropertyRefExprClass:
case Expr::ObjCProtocolExprClass:
case Expr::ObjCSelectorExprClass:
case Expr::ObjCStringLiteralClass:
case Expr::ObjCBoxedExprClass:
case Expr::ObjCArrayLiteralClass:
case Expr::ObjCDictionaryLiteralClass:
case Expr::ObjCSubscriptRefExprClass:
case Expr::ObjCIndirectCopyRestoreExprClass:
case Expr::ObjCAvailabilityCheckExprClass:
case Expr::OffsetOfExprClass:
case Expr::PredefinedExprClass:
case Expr::ShuffleVectorExprClass:
case Expr::ConvertVectorExprClass:
case Expr::StmtExprClass:
case Expr::TypeTraitExprClass:
case Expr::RequiresExprClass:
case Expr::ArrayTypeTraitExprClass:
case Expr::ExpressionTraitExprClass:
case Expr::VAArgExprClass:
case Expr::CUDAKernelCallExprClass:
case Expr::AsTypeExprClass:
case Expr::PseudoObjectExprClass:
case Expr::AtomicExprClass:
case Expr::SourceLocExprClass:
case Expr::BuiltinBitCastExprClass:
{
NotPrimaryExpr();
if (!NullOut) {
DiagnosticsEngine &Diags = Context.getDiags();
unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
"cannot yet mangle expression type %0");
Diags.Report(E->getExprLoc(), DiagID)
<< E->getStmtClassName() << E->getSourceRange();
return;
}
break;
}
case Expr::CXXUuidofExprClass: {
NotPrimaryExpr();
const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
if (Context.getASTContext().getLangOpts().getClangABICompat() >
LangOptions::ClangABI::Ver11) {
Out << "u8__uuidof";
if (UE->isTypeOperand())
mangleType(UE->getTypeOperand(Context.getASTContext()));
else
mangleTemplateArgExpr(UE->getExprOperand());
Out << 'E';
} else {
if (UE->isTypeOperand()) {
QualType UuidT = UE->getTypeOperand(Context.getASTContext());
Out << "u8__uuidoft";
mangleType(UuidT);
} else {
Expr *UuidExp = UE->getExprOperand();
Out << "u8__uuidofz";
mangleExpression(UuidExp);
}
}
break;
}
case Expr::BinaryConditionalOperatorClass: {
NotPrimaryExpr();
DiagnosticsEngine &Diags = Context.getDiags();
unsigned DiagID =
Diags.getCustomDiagID(DiagnosticsEngine::Error,
"?: operator with omitted middle operand cannot be mangled");
Diags.Report(E->getExprLoc(), DiagID)
<< E->getStmtClassName() << E->getSourceRange();
return;
}
case Expr::OpaqueValueExprClass:
llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
case Expr::InitListExprClass: {
NotPrimaryExpr();
Out << "il";
mangleInitListElements(cast<InitListExpr>(E));
Out << "E";
break;
}
case Expr::DesignatedInitExprClass: {
NotPrimaryExpr();
auto *DIE = cast<DesignatedInitExpr>(E);
for (const auto &Designator : DIE->designators()) {
if (Designator.isFieldDesignator()) {
Out << "di";
mangleSourceName(Designator.getFieldName());
} else if (Designator.isArrayDesignator()) {
Out << "dx";
mangleExpression(DIE->getArrayIndex(Designator));
} else {
assert(Designator.isArrayRangeDesignator() &&
"unknown designator kind");
Out << "dX";
mangleExpression(DIE->getArrayRangeStart(Designator));
mangleExpression(DIE->getArrayRangeEnd(Designator));
}
}
mangleExpression(DIE->getInit());
break;
}
case Expr::CXXDefaultArgExprClass:
E = cast<CXXDefaultArgExpr>(E)->getExpr();
goto recurse;
case Expr::CXXDefaultInitExprClass:
E = cast<CXXDefaultInitExpr>(E)->getExpr();
goto recurse;
case Expr::CXXStdInitializerListExprClass:
E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
goto recurse;
case Expr::SubstNonTypeTemplateParmExprClass:
E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
goto recurse;
case Expr::UserDefinedLiteralClass:
case Expr::CXXMemberCallExprClass: case Expr::CallExprClass: {
NotPrimaryExpr();
const CallExpr *CE = cast<CallExpr>(E);
if (isParenthesizedADLCallee(CE)) {
Out << "cp";
} else {
Out << "cl";
}
unsigned CallArity = CE->getNumArgs();
for (const Expr *Arg : CE->arguments())
if (isa<PackExpansionExpr>(Arg))
CallArity = UnknownArity;
mangleExpression(CE->getCallee(), CallArity);
for (const Expr *Arg : CE->arguments())
mangleExpression(Arg);
Out << 'E';
break;
}
case Expr::CXXNewExprClass: {
NotPrimaryExpr();
const CXXNewExpr *New = cast<CXXNewExpr>(E);
if (New->isGlobalNew()) Out << "gs";
Out << (New->isArray() ? "na" : "nw");
for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
E = New->placement_arg_end(); I != E; ++I)
mangleExpression(*I);
Out << '_';
mangleType(New->getAllocatedType());
if (New->hasInitializer()) {
if (New->getInitializationStyle() == CXXNewExpr::ListInit)
Out << "il";
else
Out << "pi";
const Expr *Init = New->getInitializer();
if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
E = CCE->arg_end();
I != E; ++I)
mangleExpression(*I);
} else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
mangleExpression(PLE->getExpr(i));
} else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
isa<InitListExpr>(Init)) {
mangleInitListElements(cast<InitListExpr>(Init));
} else
mangleExpression(Init);
}
Out << 'E';
break;
}
case Expr::CXXPseudoDestructorExprClass: {
NotPrimaryExpr();
const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
if (const Expr *Base = PDE->getBase())
mangleMemberExprBase(Base, PDE->isArrow());
NestedNameSpecifier *Qualifier = PDE->getQualifier();
if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
if (Qualifier) {
mangleUnresolvedPrefix(Qualifier,
true);
mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
Out << 'E';
} else {
Out << "sr";
if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
Out << 'E';
}
} else if (Qualifier) {
mangleUnresolvedPrefix(Qualifier);
}
Out << "dn";
QualType DestroyedType = PDE->getDestroyedType();
mangleUnresolvedTypeOrSimpleId(DestroyedType);
break;
}
case Expr::MemberExprClass: {
NotPrimaryExpr();
const MemberExpr *ME = cast<MemberExpr>(E);
mangleMemberExpr(ME->getBase(), ME->isArrow(),
ME->getQualifier(), nullptr,
ME->getMemberDecl()->getDeclName(),
ME->getTemplateArgs(), ME->getNumTemplateArgs(),
Arity);
break;
}
case Expr::UnresolvedMemberExprClass: {
NotPrimaryExpr();
const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
ME->isArrow(), ME->getQualifier(), nullptr,
ME->getMemberName(),
ME->getTemplateArgs(), ME->getNumTemplateArgs(),
Arity);
break;
}
case Expr::CXXDependentScopeMemberExprClass: {
NotPrimaryExpr();
const CXXDependentScopeMemberExpr *ME
= cast<CXXDependentScopeMemberExpr>(E);
mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
ME->isArrow(), ME->getQualifier(),
ME->getFirstQualifierFoundInScope(),
ME->getMember(),
ME->getTemplateArgs(), ME->getNumTemplateArgs(),
Arity);
break;
}
case Expr::UnresolvedLookupExprClass: {
NotPrimaryExpr();
const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
Arity);
break;
}
case Expr::CXXUnresolvedConstructExprClass: {
NotPrimaryExpr();
const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
unsigned N = CE->getNumArgs();
if (CE->isListInitialization()) {
assert(N == 1 && "unexpected form for list initialization");
auto *IL = cast<InitListExpr>(CE->getArg(0));
Out << "tl";
mangleType(CE->getType());
mangleInitListElements(IL);
Out << "E";
break;
}
Out << "cv";
mangleType(CE->getType());
if (N != 1) Out << '_';
for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
if (N != 1) Out << 'E';
break;
}
case Expr::CXXConstructExprClass: {
const auto *CE = cast<CXXConstructExpr>(E);
if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
assert(
CE->getNumArgs() >= 1 &&
(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
"implicit CXXConstructExpr must have one argument");
E = cast<CXXConstructExpr>(E)->getArg(0);
goto recurse;
}
NotPrimaryExpr();
Out << "il";
for (auto *E : CE->arguments())
mangleExpression(E);
Out << "E";
break;
}
case Expr::CXXTemporaryObjectExprClass: {
NotPrimaryExpr();
const auto *CE = cast<CXXTemporaryObjectExpr>(E);
unsigned N = CE->getNumArgs();
bool List = CE->isListInitialization();
if (List)
Out << "tl";
else
Out << "cv";
mangleType(CE->getType());
if (!List && N != 1)
Out << '_';
if (CE->isStdInitListInitialization()) {
auto *SILE =
cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
mangleInitListElements(ILE);
} else {
for (auto *E : CE->arguments())
mangleExpression(E);
}
if (List || N != 1)
Out << 'E';
break;
}
case Expr::CXXScalarValueInitExprClass:
NotPrimaryExpr();
Out << "cv";
mangleType(E->getType());
Out << "_E";
break;
case Expr::CXXNoexceptExprClass:
NotPrimaryExpr();
Out << "nx";
mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
break;
case Expr::UnaryExprOrTypeTraitExprClass: {
const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
if (!SAE->isInstantiationDependent()) {
QualType T = (ImplicitlyConvertedToType.isNull() ||
!ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
: ImplicitlyConvertedToType;
llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
mangleIntegerLiteral(T, V);
break;
}
NotPrimaryExpr();
auto MangleAlignofSizeofArg = [&] {
if (SAE->isArgumentType()) {
Out << 't';
mangleType(SAE->getArgumentType());
} else {
Out << 'z';
mangleExpression(SAE->getArgumentExpr());
}
};
switch(SAE->getKind()) {
case UETT_SizeOf:
Out << 's';
MangleAlignofSizeofArg();
break;
case UETT_PreferredAlignOf:
if (Context.getASTContext().getLangOpts().getClangABICompat() >
LangOptions::ClangABI::Ver11) {
Out << "u11__alignof__";
if (SAE->isArgumentType())
mangleType(SAE->getArgumentType());
else
mangleTemplateArgExpr(SAE->getArgumentExpr());
Out << 'E';
break;
}
LLVM_FALLTHROUGH;
case UETT_AlignOf:
Out << 'a';
MangleAlignofSizeofArg();
break;
case UETT_VecStep: {
DiagnosticsEngine &Diags = Context.getDiags();
unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
"cannot yet mangle vec_step expression");
Diags.Report(DiagID);
return;
}
case UETT_OpenMPRequiredSimdAlign: {
DiagnosticsEngine &Diags = Context.getDiags();
unsigned DiagID = Diags.getCustomDiagID(
DiagnosticsEngine::Error,
"cannot yet mangle __builtin_omp_required_simd_align expression");
Diags.Report(DiagID);
return;
}
}
break;
}
case Expr::CXXThrowExprClass: {
NotPrimaryExpr();
const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
if (TE->getSubExpr()) {
Out << "tw";
mangleExpression(TE->getSubExpr());
} else {
Out << "tr";
}
break;
}
case Expr::CXXTypeidExprClass: {
NotPrimaryExpr();
const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
if (TIE->isTypeOperand()) {
Out << "ti";
mangleType(TIE->getTypeOperand(Context.getASTContext()));
} else {
Out << "te";
mangleExpression(TIE->getExprOperand());
}
break;
}
case Expr::CXXDeleteExprClass: {
NotPrimaryExpr();
const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
if (DE->isGlobalDelete()) Out << "gs";
Out << (DE->isArrayForm() ? "da" : "dl");
mangleExpression(DE->getArgument());
break;
}
case Expr::UnaryOperatorClass: {
NotPrimaryExpr();
const UnaryOperator *UO = cast<UnaryOperator>(E);
mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
1);
mangleExpression(UO->getSubExpr());
break;
}
case Expr::ArraySubscriptExprClass: {
NotPrimaryExpr();
const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
Out << "ix";
mangleExpression(AE->getLHS());
mangleExpression(AE->getRHS());
break;
}
case Expr::MatrixSubscriptExprClass: {
NotPrimaryExpr();
const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
Out << "ixix";
mangleExpression(ME->getBase());
mangleExpression(ME->getRowIdx());
mangleExpression(ME->getColumnIdx());
break;
}
case Expr::CompoundAssignOperatorClass: case Expr::BinaryOperatorClass: {
NotPrimaryExpr();
const BinaryOperator *BO = cast<BinaryOperator>(E);
if (BO->getOpcode() == BO_PtrMemD)
Out << "ds";
else
mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2);
mangleExpression(BO->getLHS());
mangleExpression(BO->getRHS());
break;
}
case Expr::CXXRewrittenBinaryOperatorClass: {
NotPrimaryExpr();
CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
2);
mangleExpression(Decomposed.LHS);
mangleExpression(Decomposed.RHS);
break;
}
case Expr::ConditionalOperatorClass: {
NotPrimaryExpr();
const ConditionalOperator *CO = cast<ConditionalOperator>(E);
mangleOperatorName(OO_Conditional, 3);
mangleExpression(CO->getCond());
mangleExpression(CO->getLHS(), Arity);
mangleExpression(CO->getRHS(), Arity);
break;
}
case Expr::ImplicitCastExprClass: {
ImplicitlyConvertedToType = E->getType();
E = cast<ImplicitCastExpr>(E)->getSubExpr();
goto recurse;
}
case Expr::ObjCBridgedCastExprClass: {
NotPrimaryExpr();
StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
Out << "v1U" << Kind.size() << Kind;
mangleCastExpression(E, "cv");
break;
}
case Expr::CStyleCastExprClass:
NotPrimaryExpr();
mangleCastExpression(E, "cv");
break;
case Expr::CXXFunctionalCastExprClass: {
NotPrimaryExpr();
auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
if (CCE->getParenOrBraceRange().isInvalid())
Sub = CCE->getArg(0)->IgnoreImplicit();
if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
Sub = StdInitList->getSubExpr()->IgnoreImplicit();
if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
Out << "tl";
mangleType(E->getType());
mangleInitListElements(IL);
Out << "E";
} else {
mangleCastExpression(E, "cv");
}
break;
}
case Expr::CXXStaticCastExprClass:
NotPrimaryExpr();
mangleCastExpression(E, "sc");
break;
case Expr::CXXDynamicCastExprClass:
NotPrimaryExpr();
mangleCastExpression(E, "dc");
break;
case Expr::CXXReinterpretCastExprClass:
NotPrimaryExpr();
mangleCastExpression(E, "rc");
break;
case Expr::CXXConstCastExprClass:
NotPrimaryExpr();
mangleCastExpression(E, "cc");
break;
case Expr::CXXAddrspaceCastExprClass:
NotPrimaryExpr();
mangleCastExpression(E, "ac");
break;
case Expr::CXXOperatorCallExprClass: {
NotPrimaryExpr();
const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
unsigned NumArgs = CE->getNumArgs();
if (CE->getOperator() != OO_Arrow)
mangleOperatorName(CE->getOperator(), NumArgs);
for (unsigned i = 0; i != NumArgs; ++i)
mangleExpression(CE->getArg(i));
break;
}
case Expr::ParenExprClass:
E = cast<ParenExpr>(E)->getSubExpr();
goto recurse;
case Expr::ConceptSpecializationExprClass: {
Out << "L_Z";
auto *CSE = cast<ConceptSpecializationExpr>(E);
mangleTemplateName(CSE->getNamedConcept(),
CSE->getTemplateArguments().data(),
CSE->getTemplateArguments().size());
Out << 'E';
break;
}
case Expr::DeclRefExprClass:
MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
break;
case Expr::SubstNonTypeTemplateParmPackExprClass:
NotPrimaryExpr();
Out << "_SUBSTPACK_";
break;
case Expr::FunctionParmPackExprClass: {
NotPrimaryExpr();
const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
Out << "v110_SUBSTPACK";
MangleDeclRefExpr(FPPE->getParameterPack());
break;
}
case Expr::DependentScopeDeclRefExprClass: {
NotPrimaryExpr();
const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
Arity);
break;
}
case Expr::CXXBindTemporaryExprClass:
E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
goto recurse;
case Expr::ExprWithCleanupsClass:
E = cast<ExprWithCleanups>(E)->getSubExpr();
goto recurse;
case Expr::FloatingLiteralClass: {
const FloatingLiteral *FL = cast<FloatingLiteral>(E);
mangleFloatLiteral(FL->getType(), FL->getValue());
break;
}
case Expr::FixedPointLiteralClass:
mangleFixedPointLiteral();
break;
case Expr::CharacterLiteralClass:
Out << 'L';
mangleType(E->getType());
Out << cast<CharacterLiteral>(E)->getValue();
Out << 'E';
break;
case Expr::ObjCBoolLiteralExprClass:
Out << "Lb";
Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
Out << 'E';
break;
case Expr::CXXBoolLiteralExprClass:
Out << "Lb";
Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
Out << 'E';
break;
case Expr::IntegerLiteralClass: {
llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
if (E->getType()->isSignedIntegerType())
Value.setIsSigned(true);
mangleIntegerLiteral(E->getType(), Value);
break;
}
case Expr::ImaginaryLiteralClass: {
const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
Out << 'L';
mangleType(E->getType());
if (const FloatingLiteral *Imag =
dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
Out << '_';
mangleFloat(Imag->getValue());
} else {
Out << "0_";
llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
if (IE->getSubExpr()->getType()->isSignedIntegerType())
Value.setIsSigned(true);
mangleNumber(Value);
}
Out << 'E';
break;
}
case Expr::StringLiteralClass: {
Out << 'L';
assert(isa<ConstantArrayType>(E->getType()));
mangleType(E->getType());
Out << 'E';
break;
}
case Expr::GNUNullExprClass:
mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
break;
case Expr::CXXNullPtrLiteralExprClass: {
Out << "LDnE";
break;
}
case Expr::LambdaExprClass: {
Out << "L";
mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
Out << "E";
break;
}
case Expr::PackExpansionExprClass:
NotPrimaryExpr();
Out << "sp";
mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
break;
case Expr::SizeOfPackExprClass: {
NotPrimaryExpr();
auto *SPE = cast<SizeOfPackExpr>(E);
if (SPE->isPartiallySubstituted()) {
Out << "sP";
for (const auto &A : SPE->getPartialArguments())
mangleTemplateArg(A, false);
Out << "E";
break;
}
Out << "sZ";
const NamedDecl *Pack = SPE->getPack();
if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
else if (const NonTypeTemplateParmDecl *NTTP
= dyn_cast<NonTypeTemplateParmDecl>(Pack))
mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
else if (const TemplateTemplateParmDecl *TempTP
= dyn_cast<TemplateTemplateParmDecl>(Pack))
mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
else
mangleFunctionParam(cast<ParmVarDecl>(Pack));
break;
}
case Expr::MaterializeTemporaryExprClass:
E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
goto recurse;
case Expr::CXXFoldExprClass: {
NotPrimaryExpr();
auto *FE = cast<CXXFoldExpr>(E);
if (FE->isLeftFold())
Out << (FE->getInit() ? "fL" : "fl");
else
Out << (FE->getInit() ? "fR" : "fr");
if (FE->getOperator() == BO_PtrMemD)
Out << "ds";
else
mangleOperatorName(
BinaryOperator::getOverloadedOperator(FE->getOperator()),
2);
if (FE->getLHS())
mangleExpression(FE->getLHS());
if (FE->getRHS())
mangleExpression(FE->getRHS());
break;
}
case Expr::CXXThisExprClass:
NotPrimaryExpr();
Out << "fpT";
break;
case Expr::CoawaitExprClass:
NotPrimaryExpr();
Out << "v18co_await";
mangleExpression(cast<CoawaitExpr>(E)->getOperand());
break;
case Expr::DependentCoawaitExprClass:
NotPrimaryExpr();
Out << "v18co_await";
mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
break;
case Expr::CoyieldExprClass:
NotPrimaryExpr();
Out << "v18co_yield";
mangleExpression(cast<CoawaitExpr>(E)->getOperand());
break;
case Expr::SYCLUniqueStableNameExprClass: {
const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
NotPrimaryExpr();
Out << "u33__builtin_sycl_unique_stable_name";
mangleType(USN->getTypeSourceInfo()->getType());
Out << "E";
break;
}
}
if (AsTemplateArg && !IsPrimaryExpr)
Out << 'E';
}
void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
unsigned parmDepth = parm->getFunctionScopeDepth();
unsigned parmIndex = parm->getFunctionScopeIndex();
assert(parmDepth < FunctionTypeDepth.getDepth());
unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
if (FunctionTypeDepth.isInResultType())
nestingDepth--;
if (nestingDepth == 0) {
Out << "fp";
} else {
Out << "fL" << (nestingDepth - 1) << 'p';
}
assert(!parm->getType()->isArrayType()
&& "parameter's type is still an array type?");
if (const DependentAddressSpaceType *DAST =
dyn_cast<DependentAddressSpaceType>(parm->getType())) {
mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
} else {
mangleQualifiers(parm->getType().getQualifiers());
}
if (parmIndex != 0) {
Out << (parmIndex - 1);
}
Out << '_';
}
void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
const CXXRecordDecl *InheritedFrom) {
Out << 'C';
if (InheritedFrom)
Out << 'I';
switch (T) {
case Ctor_Complete:
Out << '1';
break;
case Ctor_Base:
Out << '2';
break;
case Ctor_Comdat:
Out << '5';
break;
case Ctor_DefaultClosure:
case Ctor_CopyingClosure:
llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
}
if (InheritedFrom)
mangleName(InheritedFrom);
}
void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
switch (T) {
case Dtor_Deleting:
Out << "D0";
break;
case Dtor_Complete:
Out << "D1";
break;
case Dtor_Base:
Out << "D2";
break;
case Dtor_Comdat:
Out << "D5";
break;
}
}
namespace {
struct TemplateArgManglingInfo {
TemplateDecl *ResolvedTemplate = nullptr;
bool SeenPackExpansionIntoNonPack = false;
const NamedDecl *UnresolvedExpandedPack = nullptr;
TemplateArgManglingInfo(TemplateName TN) {
if (TemplateDecl *TD = TN.getAsTemplateDecl())
ResolvedTemplate = TD;
}
bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) {
if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
return true;
const NamedDecl *Param = UnresolvedExpandedPack;
if (!Param) {
assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
"no parameter for argument");
Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
assert(getExpandedPackSize(Param) &&
"failed to form pack argument for parameter pack");
UnresolvedExpandedPack = Param;
}
}
if (Arg.isPackExpansion() &&
(!Param->isParameterPack() || UnresolvedExpandedPack)) {
SeenPackExpansionIntoNonPack = true;
return true;
}
if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) {
auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
if (!RD || !RD->isGenericLambda())
return true;
}
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
return NTTP && NTTP->getType()->getContainedDeducedType();
}
};
}
void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
const TemplateArgumentLoc *TemplateArgs,
unsigned NumTemplateArgs) {
Out << 'I';
TemplateArgManglingInfo Info(TN);
for (unsigned i = 0; i != NumTemplateArgs; ++i)
mangleTemplateArg(TemplateArgs[i].getArgument(),
Info.needExactType(i, TemplateArgs[i].getArgument()));
Out << 'E';
}
void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
const TemplateArgumentList &AL) {
Out << 'I';
TemplateArgManglingInfo Info(TN);
for (unsigned i = 0, e = AL.size(); i != e; ++i)
mangleTemplateArg(AL[i], Info.needExactType(i, AL[i]));
Out << 'E';
}
void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
const TemplateArgument *TemplateArgs,
unsigned NumTemplateArgs) {
Out << 'I';
TemplateArgManglingInfo Info(TN);
for (unsigned i = 0; i != NumTemplateArgs; ++i)
mangleTemplateArg(TemplateArgs[i], Info.needExactType(i, TemplateArgs[i]));
Out << 'E';
}
void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
if (!A.isInstantiationDependent() || A.isDependent())
A = Context.getASTContext().getCanonicalTemplateArgument(A);
switch (A.getKind()) {
case TemplateArgument::Null:
llvm_unreachable("Cannot mangle NULL template argument");
case TemplateArgument::Type:
mangleType(A.getAsType());
break;
case TemplateArgument::Template:
mangleType(A.getAsTemplate());
break;
case TemplateArgument::TemplateExpansion:
Out << "Dp";
mangleType(A.getAsTemplateOrTemplatePattern());
break;
case TemplateArgument::Expression:
mangleTemplateArgExpr(A.getAsExpr());
break;
case TemplateArgument::Integral:
mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
break;
case TemplateArgument::Declaration: {
ValueDecl *D = A.getAsDecl();
if (A.getParamTypeForDecl()->isRecordType()) {
auto *TPO = cast<TemplateParamObjectDecl>(D);
mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
TPO->getValue(), true,
NeedExactType);
break;
}
ASTContext &Ctx = Context.getASTContext();
APValue Value;
if (D->isCXXInstanceMember())
Value = APValue(D, false, {});
else if (D->getType()->isArrayType() &&
Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),
A.getParamTypeForDecl()) &&
Ctx.getLangOpts().getClangABICompat() >
LangOptions::ClangABI::Ver11)
Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
{APValue::LValuePathEntry::ArrayIndex(0)},
false);
else
Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
ArrayRef<APValue::LValuePathEntry>(),
false);
mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, true,
NeedExactType);
break;
}
case TemplateArgument::NullPtr: {
mangleNullPointer(A.getNullPtrType());
break;
}
case TemplateArgument::Pack: {
Out << 'J';
for (const auto &P : A.pack_elements())
mangleTemplateArg(P, NeedExactType);
Out << 'E';
}
}
}
void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
ASTContext &Ctx = Context.getASTContext();
if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver11) {
mangleExpression(E, UnknownArity, true);
return;
}
E = E->IgnoreParenImpCasts();
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
const ValueDecl *D = DRE->getDecl();
if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
Out << 'L';
mangle(D);
Out << 'E';
return;
}
}
Out << 'X';
mangleExpression(E);
Out << 'E';
}
static bool isZeroInitialized(QualType T, const APValue &V) {
switch (V.getKind()) {
case APValue::None:
case APValue::Indeterminate:
case APValue::AddrLabelDiff:
return false;
case APValue::Struct: {
const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
assert(RD && "unexpected type for record value");
unsigned I = 0;
for (const CXXBaseSpecifier &BS : RD->bases()) {
if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
return false;
++I;
}
I = 0;
for (const FieldDecl *FD : RD->fields()) {
if (!FD->isUnnamedBitfield() &&
!isZeroInitialized(FD->getType(), V.getStructField(I)))
return false;
++I;
}
return true;
}
case APValue::Union: {
const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
assert(RD && "unexpected type for union value");
for (const FieldDecl *FD : RD->fields()) {
if (!FD->isUnnamedBitfield())
return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
isZeroInitialized(FD->getType(), V.getUnionValue());
}
return true;
}
case APValue::Array: {
QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
return false;
return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
}
case APValue::Vector: {
const VectorType *VT = T->castAs<VectorType>();
for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
return false;
return true;
}
case APValue::Int:
return !V.getInt();
case APValue::Float:
return V.getFloat().isPosZero();
case APValue::FixedPoint:
return !V.getFixedPoint().getValue();
case APValue::ComplexFloat:
return V.getComplexFloatReal().isPosZero() &&
V.getComplexFloatImag().isPosZero();
case APValue::ComplexInt:
return !V.getComplexIntReal() && !V.getComplexIntImag();
case APValue::LValue:
return V.isNullPointer();
case APValue::MemberPointer:
return !V.getMemberPointerDecl();
}
llvm_unreachable("Unhandled APValue::ValueKind enum");
}
static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
QualType T = LV.getLValueBase().getType();
for (APValue::LValuePathEntry E : LV.getLValuePath()) {
if (const ArrayType *AT = Ctx.getAsArrayType(T))
T = AT->getElementType();
else if (const FieldDecl *FD =
dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
T = FD->getType();
else
T = Ctx.getRecordType(
cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
}
return T;
}
static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,
DiagnosticsEngine &Diags,
const FieldDecl *FD) {
if (FD->getIdentifier())
return FD->getIdentifier();
if (FD->isBitField())
return nullptr;
const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
for (const FieldDecl *RDField : RD->fields()) {
if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
return II;
}
unsigned DiagID = Diags.getCustomDiagID(
DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
Diags.Report(UnionLoc, DiagID);
return nullptr;
}
void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
bool TopLevel,
bool NeedExactType) {
Qualifiers Quals;
T = getASTContext().getUnqualifiedArrayType(T, Quals);
bool IsPrimaryExpr = true;
auto NotPrimaryExpr = [&] {
if (TopLevel && IsPrimaryExpr)
Out << 'X';
IsPrimaryExpr = false;
};
switch (V.getKind()) {
case APValue::None:
case APValue::Indeterminate:
Out << 'L';
mangleType(T);
Out << 'E';
break;
case APValue::AddrLabelDiff:
llvm_unreachable("unexpected value kind in template argument");
case APValue::Struct: {
const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
assert(RD && "unexpected type for record value");
llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());
while (
!Fields.empty() &&
(Fields.back()->isUnnamedBitfield() ||
isZeroInitialized(Fields.back()->getType(),
V.getStructField(Fields.back()->getFieldIndex())))) {
Fields.pop_back();
}
llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
if (Fields.empty()) {
while (!Bases.empty() &&
isZeroInitialized(Bases.back().getType(),
V.getStructBase(Bases.size() - 1)))
Bases = Bases.drop_back();
}
NotPrimaryExpr();
Out << "tl";
mangleType(T);
for (unsigned I = 0, N = Bases.size(); I != N; ++I)
mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
if (Fields[I]->isUnnamedBitfield())
continue;
mangleValueInTemplateArg(Fields[I]->getType(),
V.getStructField(Fields[I]->getFieldIndex()),
false);
}
Out << 'E';
break;
}
case APValue::Union: {
assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
const FieldDecl *FD = V.getUnionField();
if (!FD) {
Out << 'L';
mangleType(T);
Out << 'E';
break;
}
NotPrimaryExpr();
Out << "tl";
mangleType(T);
if (!isZeroInitialized(T, V)) {
Out << "di";
IdentifierInfo *II = (getUnionInitName(
T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
if (II)
mangleSourceName(II);
mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
}
Out << 'E';
break;
}
case APValue::Array: {
QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
NotPrimaryExpr();
Out << "tl";
mangleType(T);
unsigned N = V.getArraySize();
if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
N = V.getArrayInitializedElts();
while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
--N;
}
for (unsigned I = 0; I != N; ++I) {
const APValue &Elem = I < V.getArrayInitializedElts()
? V.getArrayInitializedElt(I)
: V.getArrayFiller();
mangleValueInTemplateArg(ElemT, Elem, false);
}
Out << 'E';
break;
}
case APValue::Vector: {
const VectorType *VT = T->castAs<VectorType>();
NotPrimaryExpr();
Out << "tl";
mangleType(T);
unsigned N = V.getVectorLength();
while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
--N;
for (unsigned I = 0; I != N; ++I)
mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
Out << 'E';
break;
}
case APValue::Int:
mangleIntegerLiteral(T, V.getInt());
break;
case APValue::Float:
mangleFloatLiteral(T, V.getFloat());
break;
case APValue::FixedPoint:
mangleFixedPointLiteral();
break;
case APValue::ComplexFloat: {
const ComplexType *CT = T->castAs<ComplexType>();
NotPrimaryExpr();
Out << "tl";
mangleType(T);
if (!V.getComplexFloatReal().isPosZero() ||
!V.getComplexFloatImag().isPosZero())
mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
if (!V.getComplexFloatImag().isPosZero())
mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
Out << 'E';
break;
}
case APValue::ComplexInt: {
const ComplexType *CT = T->castAs<ComplexType>();
NotPrimaryExpr();
Out << "tl";
mangleType(T);
if (V.getComplexIntReal().getBoolValue() ||
V.getComplexIntImag().getBoolValue())
mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
if (V.getComplexIntImag().getBoolValue())
mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
Out << 'E';
break;
}
case APValue::LValue: {
assert((T->isPointerType() || T->isReferenceType()) &&
"unexpected type for LValue template arg");
if (V.isNullPointer()) {
mangleNullPointer(T);
break;
}
APValue::LValueBase B = V.getLValueBase();
if (!B) {
CharUnits Offset = V.getLValueOffset();
if (Offset.isZero()) {
NotPrimaryExpr();
Out << "rc";
mangleType(T);
Out << "Li0E";
if (TopLevel)
Out << 'E';
} else {
Out << "L";
mangleType(T);
Out << Offset.getQuantity() << 'E';
}
break;
}
ASTContext &Ctx = Context.getASTContext();
enum { Base, Offset, Path } Kind;
if (!V.hasLValuePath()) {
if (T->isReferenceType()) {
NotPrimaryExpr();
Out << "decvP";
mangleType(T->getPointeeType());
} else {
NotPrimaryExpr();
Out << "cv";
mangleType(T);
}
Out << "plcvPcad";
Kind = Offset;
} else {
if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) {
NotPrimaryExpr();
if (NeedExactType && T->isVoidPointerType()) {
Out << "cv";
mangleType(T);
}
if (T->isPointerType())
Out << "ad";
Out << "so";
mangleType(T->isVoidPointerType()
? getLValueType(Ctx, V).getUnqualifiedType()
: T->getPointeeType());
Kind = Path;
} else {
if (NeedExactType &&
!Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
Ctx.getLangOpts().getClangABICompat() >
LangOptions::ClangABI::Ver11) {
NotPrimaryExpr();
Out << "cv";
mangleType(T);
}
if (T->isPointerType()) {
NotPrimaryExpr();
Out << "ad";
}
Kind = Base;
}
}
QualType TypeSoFar = B.getType();
if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
Out << 'L';
mangle(VD);
Out << 'E';
} else if (auto *E = B.dyn_cast<const Expr*>()) {
NotPrimaryExpr();
mangleExpression(E);
} else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
NotPrimaryExpr();
Out << "ti";
mangleType(QualType(TI.getType(), 0));
} else {
llvm_unreachable("unexpected lvalue base kind in template argument");
}
switch (Kind) {
case Base:
break;
case Offset:
Out << 'L';
mangleType(Ctx.getPointerDiffType());
mangleNumber(V.getLValueOffset().getQuantity());
Out << 'E';
break;
case Path:
if (!V.getLValueOffset().isZero())
mangleNumber(V.getLValueOffset().getQuantity());
bool OnePastTheEnd = V.isLValueOnePastTheEnd();
for (APValue::LValuePathEntry E : V.getLValuePath()) {
if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
TypeSoFar = AT->getElementType();
} else {
const Decl *D = E.getAsBaseOrMember().getPointer();
if (auto *FD = dyn_cast<FieldDecl>(D)) {
if (FD->getParent()->isUnion()) {
Out << '_';
if (FD->getFieldIndex())
Out << (FD->getFieldIndex() - 1);
}
TypeSoFar = FD->getType();
} else {
TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));
}
}
}
if (OnePastTheEnd)
Out << 'p';
Out << 'E';
break;
}
break;
}
case APValue::MemberPointer:
if (!V.getMemberPointerDecl()) {
mangleNullPointer(T);
break;
}
ASTContext &Ctx = Context.getASTContext();
NotPrimaryExpr();
if (!V.getMemberPointerPath().empty()) {
Out << "mc";
mangleType(T);
} else if (NeedExactType &&
!Ctx.hasSameType(
T->castAs<MemberPointerType>()->getPointeeType(),
V.getMemberPointerDecl()->getType()) &&
Ctx.getLangOpts().getClangABICompat() >
LangOptions::ClangABI::Ver11) {
Out << "cv";
mangleType(T);
}
Out << "adL";
mangle(V.getMemberPointerDecl());
Out << 'E';
if (!V.getMemberPointerPath().empty()) {
CharUnits Offset =
Context.getASTContext().getMemberPointerPathAdjustment(V);
if (!Offset.isZero())
mangleNumber(Offset.getQuantity());
Out << 'E';
}
break;
}
if (TopLevel && !IsPrimaryExpr)
Out << 'E';
}
void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
Out << 'T';
if (Depth != 0)
Out << 'L' << (Depth - 1) << '_';
if (Index != 0)
Out << (Index - 1);
Out << '_';
}
void CXXNameMangler::mangleSeqID(unsigned SeqID) {
if (SeqID == 0) {
} else if (SeqID == 1) {
Out << '0';
} else {
SeqID--;
char Buffer[7]; MutableArrayRef<char> BufferRef(Buffer);
MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
for (; SeqID != 0; SeqID /= 36) {
unsigned C = SeqID % 36;
*I++ = (C < 10 ? '0' + C : 'A' + C - 10);
}
Out.write(I.base(), I - BufferRef.rbegin());
}
Out << '_';
}
void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
bool result = mangleSubstitution(tname);
assert(result && "no existing substitution for template name");
(void) result;
}
bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
if (mangleStandardSubstitution(ND))
return true;
ND = cast<NamedDecl>(ND->getCanonicalDecl());
return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
}
bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {
assert(NNS->getKind() == NestedNameSpecifier::Identifier &&
"mangleSubstitution(NestedNameSpecifier *) is only used for "
"identifier nested name specifiers.");
NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS));
}
static bool hasMangledSubstitutionQualifiers(QualType T) {
Qualifiers Qs = T.getQualifiers();
return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
}
bool CXXNameMangler::mangleSubstitution(QualType T) {
if (!hasMangledSubstitutionQualifiers(T)) {
if (const RecordType *RT = T->getAs<RecordType>())
return mangleSubstitution(RT->getDecl());
}
uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
return mangleSubstitution(TypePtr);
}
bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
if (TemplateDecl *TD = Template.getAsTemplateDecl())
return mangleSubstitution(TD);
Template = Context.getASTContext().getCanonicalTemplateName(Template);
return mangleSubstitution(
reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
}
bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
if (I == Substitutions.end())
return false;
unsigned SeqID = I->second;
Out << 'S';
mangleSeqID(SeqID);
return true;
}
bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,
QualType A) {
if (S.isNull())
return false;
const RecordType *RT = S->getAs<RecordType>();
if (!RT)
return false;
const ClassTemplateSpecializationDecl *SD =
dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
if (!SD || !SD->getIdentifier()->isStr(Name))
return false;
if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
return false;
const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
if (TemplateArgs.size() != 1)
return false;
if (TemplateArgs[0].getAsType() != A)
return false;
if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
return false;
return true;
}
bool CXXNameMangler::isStdCharSpecialization(
const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,
bool HasAllocator) {
if (!SD->getIdentifier()->isStr(Name))
return false;
const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
return false;
QualType A = TemplateArgs[0].getAsType();
if (A.isNull())
return false;
if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&
!A->isSpecificBuiltinType(BuiltinType::Char_U))
return false;
if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))
return false;
if (HasAllocator &&
!isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))
return false;
if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
return false;
return true;
}
bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
if (isStd(NS)) {
Out << "St";
return true;
}
return false;
}
if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))
return false;
if (TD->getOwningModuleForLinkage())
return false;
if (TD->getIdentifier()->isStr("allocator")) {
Out << "Sa";
return true;
}
if (TD->getIdentifier()->isStr("basic_string")) {
Out << "Sb";
return true;
}
return false;
}
if (const ClassTemplateSpecializationDecl *SD =
dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
return false;
if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
return false;
if (isStdCharSpecialization(SD, "basic_string", true)) {
Out << "Ss";
return true;
}
if (isStdCharSpecialization(SD, "basic_istream", false)) {
Out << "Si";
return true;
}
if (isStdCharSpecialization(SD, "basic_ostream", false)) {
Out << "So";
return true;
}
if (isStdCharSpecialization(SD, "basic_iostream", false)) {
Out << "Sd";
return true;
}
return false;
}
return false;
}
void CXXNameMangler::addSubstitution(QualType T) {
if (!hasMangledSubstitutionQualifiers(T)) {
if (const RecordType *RT = T->getAs<RecordType>()) {
addSubstitution(RT->getDecl());
return;
}
}
uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
addSubstitution(TypePtr);
}
void CXXNameMangler::addSubstitution(TemplateName Template) {
if (TemplateDecl *TD = Template.getAsTemplateDecl())
return addSubstitution(TD);
Template = Context.getASTContext().getCanonicalTemplateName(Template);
addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
}
void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
assert(!Substitutions.count(Ptr) && "Substitution already exists!");
Substitutions[Ptr] = SeqID++;
}
void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
if (Other->SeqID > SeqID) {
Substitutions.swap(Other->Substitutions);
SeqID = Other->SeqID;
}
}
CXXNameMangler::AbiTagList
CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
if (DisableDerivedAbiTags)
return AbiTagList();
llvm::raw_null_ostream NullOutStream;
CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
TrackReturnTypeTags.disableDerivedAbiTags();
const FunctionProtoType *Proto =
cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
TrackReturnTypeTags.mangleType(Proto->getReturnType());
TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
}
CXXNameMangler::AbiTagList
CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
if (DisableDerivedAbiTags)
return AbiTagList();
llvm::raw_null_ostream NullOutStream;
CXXNameMangler TrackVariableType(*this, NullOutStream);
TrackVariableType.disableDerivedAbiTags();
TrackVariableType.mangleType(VD->getType());
return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
}
bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
const VarDecl *VD) {
llvm::raw_null_ostream NullOutStream;
CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
TrackAbiTags.mangle(VD);
return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
}
void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
raw_ostream &Out) {
const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&
"Invalid mangleName() call, argument is not a variable or function!");
PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
getASTContext().getSourceManager(),
"Mangling declaration");
if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
auto Type = GD.getCtorType();
CXXNameMangler Mangler(*this, Out, CD, Type);
return Mangler.mangle(GlobalDecl(CD, Type));
}
if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
auto Type = GD.getDtorType();
CXXNameMangler Mangler(*this, Out, DD, Type);
return Mangler.mangle(GlobalDecl(DD, Type));
}
CXXNameMangler Mangler(*this, Out, D);
Mangler.mangle(GD);
}
void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
}
void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
}
void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
const ThunkInfo &Thunk,
raw_ostream &Out) {
assert(!isa<CXXDestructorDecl>(MD) &&
"Use mangleCXXDtor for destructor decls!");
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZT";
if (!Thunk.Return.isEmpty())
Mangler.getStream() << 'c';
Mangler.mangleCallOffset(Thunk.This.NonVirtual,
Thunk.This.Virtual.Itanium.VCallOffsetOffset);
if (!Thunk.Return.isEmpty())
Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
Mangler.mangleFunctionEncoding(MD);
}
void ItaniumMangleContextImpl::mangleCXXDtorThunk(
const CXXDestructorDecl *DD, CXXDtorType Type,
const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out, DD, Type);
Mangler.getStream() << "_ZT";
Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
}
void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZGV";
Mangler.mangleName(D);
}
void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
raw_ostream &Out) {
Out << "__cxx_global_var_init";
}
void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "__dtor_";
if (shouldMangleDeclName(D))
Mangler.mangle(D);
else
Mangler.getStream() << D->getName();
}
void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "__finalize_";
if (shouldMangleDeclName(D))
Mangler.mangle(D);
else
Mangler.getStream() << D->getName();
}
void ItaniumMangleContextImpl::mangleSEHFilterExpression(
const NamedDecl *EnclosingDecl, raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "__filt_";
if (shouldMangleDeclName(EnclosingDecl))
Mangler.mangle(EnclosingDecl);
else
Mangler.getStream() << EnclosingDecl->getName();
}
void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
const NamedDecl *EnclosingDecl, raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "__fin_";
if (shouldMangleDeclName(EnclosingDecl))
Mangler.mangle(EnclosingDecl);
else
Mangler.getStream() << EnclosingDecl->getName();
}
void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZTH";
Mangler.mangleName(D);
}
void
ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZTW";
Mangler.mangleName(D);
}
void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
unsigned ManglingNumber,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZGR";
Mangler.mangleName(D);
assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
Mangler.mangleSeqID(ManglingNumber - 1);
}
void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZTV";
Mangler.mangleNameOrStandardSubstitution(RD);
}
void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZTT";
Mangler.mangleNameOrStandardSubstitution(RD);
}
void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
int64_t Offset,
const CXXRecordDecl *Type,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZTC";
Mangler.mangleNameOrStandardSubstitution(RD);
Mangler.getStream() << Offset;
Mangler.getStream() << '_';
Mangler.mangleNameOrStandardSubstitution(Type);
}
void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZTI";
Mangler.mangleType(Ty);
}
void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZTS";
Mangler.mangleType(Ty);
}
void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
mangleCXXRTTIName(Ty, Out);
}
void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
llvm_unreachable("Can't mangle string literals");
}
void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.mangleLambdaSig(Lambda);
}
void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
raw_ostream &Out) {
CXXNameMangler Mangler(*this, Out);
Mangler.getStream() << "_ZGI";
Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
if (M->isModulePartition()) {
auto Partition = M->Name.find(':');
Mangler.mangleModuleNamePrefix(
StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
true);
}
}
ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
DiagnosticsEngine &Diags,
bool IsAux) {
return new ItaniumMangleContextImpl(
Context, Diags,
[](ASTContext &, const NamedDecl *) -> llvm::Optional<unsigned> {
return llvm::None;
},
IsAux);
}
ItaniumMangleContext *
ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,
DiscriminatorOverrideTy DiscriminatorOverride,
bool IsAux) {
return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,
IsAux);
}