HELLO·Android
系统源代码
IT资讯
技术文章
我的收藏
注册
登录
-
我收藏的文章
创建代码块
我的代码块
我的账号
Pie
|
9.0.0_r8
下载
查看原文件
收藏
根目录
external
clang
lib
AST
MicrosoftMangle.cpp
//===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This provides C++ name mangling targeting the Microsoft Visual C++ ABI. // //===----------------------------------------------------------------------===// #include "clang/AST/Mangle.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/CharUnits.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/VTableBuilder.h" #include "clang/Basic/ABI.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/JamCRC.h" #include "llvm/Support/MD5.h" #include "llvm/Support/MathExtras.h" using namespace clang; namespace { struct msvc_hashing_ostream : public llvm::raw_svector_ostream { raw_ostream &OS; llvm::SmallString<64> Buffer; msvc_hashing_ostream(raw_ostream &OS) : llvm::raw_svector_ostream(Buffer), OS(OS) {} ~msvc_hashing_ostream() override { StringRef MangledName = str(); bool StartsWithEscape = MangledName.startswith("\01"); if (StartsWithEscape) MangledName = MangledName.drop_front(1); if (MangledName.size() <= 4096) { OS << str(); return; } llvm::MD5 Hasher; llvm::MD5::MD5Result Hash; Hasher.update(MangledName); Hasher.final(Hash); SmallString<32> HexString; llvm::MD5::stringifyResult(Hash, HexString); if (StartsWithEscape) OS << '\01'; OS << "??@" << HexString << '@'; } }; /// \brief Retrieve the declaration context that should be used when mangling /// the given declaration. static const DeclContext *getEffectiveDeclContext(const Decl *D) { // The ABI assumes that lambda closure types that occur within // default arguments live in the context of the function. However, due to // the way in which Clang parses and creates function declarations, this is // not the case: the lambda closure type ends up living in the context // where the function itself resides, because the function declaration itself // had not yet been created. Fix the context here. if (const CXXRecordDecl *RD = dyn_cast
(D)) { if (RD->isLambda()) if (ParmVarDecl *ContextParam = dyn_cast_or_null
(RD->getLambdaContextDecl())) return ContextParam->getDeclContext(); } // Perform the same check for block literals. if (const BlockDecl *BD = dyn_cast
(D)) { if (ParmVarDecl *ContextParam = dyn_cast_or_null
(BD->getBlockManglingContextDecl())) return ContextParam->getDeclContext(); } const DeclContext *DC = D->getDeclContext(); if (isa
(DC) || isa
(DC)) { return getEffectiveDeclContext(cast
(DC)); } return DC->getRedeclContext(); } static const DeclContext *getEffectiveParentContext(const DeclContext *DC) { return getEffectiveDeclContext(cast
(DC)); } static const FunctionDecl *getStructor(const NamedDecl *ND) { if (const auto *FTD = dyn_cast
(ND)) return FTD->getTemplatedDecl(); const auto *FD = cast
(ND); if (const auto *FTD = FD->getPrimaryTemplate()) return FTD->getTemplatedDecl(); return FD; } static bool isLambda(const NamedDecl *ND) { const CXXRecordDecl *Record = dyn_cast
(ND); if (!Record) return false; return Record->isLambda(); } /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the /// Microsoft Visual C++ ABI. class MicrosoftMangleContextImpl : public MicrosoftMangleContext { typedef std::pair
DiscriminatorKeyTy; llvm::DenseMap
Discriminator; llvm::DenseMap
Uniquifier; llvm::DenseMap
LambdaIds; llvm::DenseMap
SEHFilterIds; llvm::DenseMap
SEHFinallyIds; public: MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags) : MicrosoftMangleContext(Context, Diags) {} bool shouldMangleCXXName(const NamedDecl *D) override; bool shouldMangleStringLiteral(const StringLiteral *SL) override; void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override; void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD, 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 mangleCXXVFTable(const CXXRecordDecl *Derived, ArrayRef
BasePath, raw_ostream &Out) override; void mangleCXXVBTable(const CXXRecordDecl *Derived, ArrayRef
BasePath, raw_ostream &Out) override; void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) override; void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile, bool IsUnaligned, uint32_t NumEntries, raw_ostream &Out) override; void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries, raw_ostream &Out) override; void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size, uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex, raw_ostream &Out) override; void mangleCXXRTTI(QualType T, raw_ostream &Out) override; void mangleCXXRTTIName(QualType T, raw_ostream &Out) override; void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) override; void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived, raw_ostream &Out) override; void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived, raw_ostream &Out) override; void mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived, ArrayRef
BasePath, raw_ostream &Out) override; void mangleTypeName(QualType T, raw_ostream &) override; void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, raw_ostream &) override; void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, raw_ostream &) override; void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber, raw_ostream &) override; void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override; void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum, raw_ostream &Out) override; void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override; void mangleDynamicAtExitDestructor(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 mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override; bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) { const DeclContext *DC = getEffectiveDeclContext(ND); if (!DC->isFunctionOrMethod()) return false; // Lambda closure types are already numbered, give out a phony number so // that they demangle nicely. if (isLambda(ND)) { disc = 1; return true; } // Use the canonical number for externally visible decls. if (ND->isExternallyVisible()) { disc = getASTContext().getManglingNumber(ND); return true; } // Anonymous tags are already numbered. if (const TagDecl *Tag = dyn_cast
(ND)) { if (!Tag->hasNameForLinkage() && !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) && !getASTContext().getTypedefNameForUnnamedTagDecl(Tag)) return false; } // Make up a reasonable number for internal decls. unsigned &discriminator = Uniquifier[ND]; if (!discriminator) discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())]; disc = discriminator + 1; return true; } unsigned getLambdaId(const CXXRecordDecl *RD) { assert(RD->isLambda() && "RD must be a lambda!"); assert(!RD->isExternallyVisible() && "RD must not be visible!"); assert(RD->getLambdaManglingNumber() == 0 && "RD must not have a mangling number!"); std::pair
::iterator, bool> Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size())); return Result.first->second; } private: void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out); }; /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the /// Microsoft Visual C++ ABI. class MicrosoftCXXNameMangler { MicrosoftMangleContextImpl &Context; raw_ostream &Out; /// The "structor" is the top-level declaration being mangled, if /// that's not a template specialization; otherwise it's the pattern /// for that specialization. const NamedDecl *Structor; unsigned StructorType; typedef llvm::SmallVector
BackRefVec; BackRefVec NameBackReferences; typedef llvm::DenseMap
ArgBackRefMap; ArgBackRefMap TypeBackReferences; typedef std::set
PassObjectSizeArgsSet; PassObjectSizeArgsSet PassObjectSizeArgs; ASTContext &getASTContext() const { return Context.getASTContext(); } // FIXME: If we add support for __ptr32/64 qualifiers, then we should push // this check into mangleQualifiers(). const bool PointersAre64Bit; public: enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result }; MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_) : Context(C), Out(Out_), Structor(nullptr), StructorType(-1), PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) == 64) {} MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_, const CXXConstructorDecl *D, CXXCtorType Type) : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) == 64) {} MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_, const CXXDestructorDecl *D, CXXDtorType Type) : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) == 64) {} raw_ostream &getStream() const { return Out; } void mangle(const NamedDecl *D, StringRef Prefix = "\01?"); void mangleName(const NamedDecl *ND); void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle); void mangleVariableEncoding(const VarDecl *VD); void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD); void mangleMemberFunctionPointer(const CXXRecordDecl *RD, const CXXMethodDecl *MD); void mangleVirtualMemPtrThunk( const CXXMethodDecl *MD, const MicrosoftVTableContext::MethodVFTableLocation &ML); void mangleNumber(int64_t Number); void mangleTagTypeKind(TagTypeKind TK); void mangleArtificalTagType(TagTypeKind TK, StringRef UnqualifiedName, ArrayRef
NestedNames = None); void mangleType(QualType T, SourceRange Range, QualifierMangleMode QMM = QMM_Mangle); void mangleFunctionType(const FunctionType *T, const FunctionDecl *D = nullptr, bool ForceThisQuals = false); void mangleNestedName(const NamedDecl *ND); private: void mangleUnqualifiedName(const NamedDecl *ND) { mangleUnqualifiedName(ND, ND->getDeclName()); } void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name); void mangleSourceName(StringRef Name); void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc); void mangleCXXDtorType(CXXDtorType T); void mangleQualifiers(Qualifiers Quals, bool IsMember); void mangleRefQualifier(RefQualifierKind RefQualifier); void manglePointerCVQualifiers(Qualifiers Quals); void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType); void mangleUnscopedTemplateName(const TemplateDecl *ND); void mangleTemplateInstantiationName(const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs); void mangleObjCMethodName(const ObjCMethodDecl *MD); void mangleArgumentType(QualType T, SourceRange Range); void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA); // Declare manglers for every type class. #define ABSTRACT_TYPE(CLASS, PARENT) #define NON_CANONICAL_TYPE(CLASS, PARENT) #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \ Qualifiers Quals, \ SourceRange Range); #include "clang/AST/TypeNodes.def" #undef ABSTRACT_TYPE #undef NON_CANONICAL_TYPE #undef TYPE void mangleType(const TagDecl *TD); void mangleDecayedArrayType(const ArrayType *T); void mangleArrayType(const ArrayType *T); void mangleFunctionClass(const FunctionDecl *FD); void mangleCallingConvention(CallingConv CC); void mangleCallingConvention(const FunctionType *T); void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean); void mangleExpression(const Expr *E); void mangleThrowSpecification(const FunctionProtoType *T); void mangleTemplateArgs(const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs); void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA, const NamedDecl *Parm); }; } bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) { if (const FunctionDecl *FD = dyn_cast
(D)) { LanguageLinkage L = FD->getLanguageLinkage(); // Overloadable functions need mangling. if (FD->hasAttr
()) return true; // The ABI expects that we would never mangle "typical" user-defined entry // points regardless of visibility or freestanding-ness. // // N.B. This is distinct from asking about "main". "main" has a lot of // special rules associated with it in the standard while these // user-defined entry points are outside of the purview of the standard. // For example, there can be only one definition for "main" in a standards // compliant program; however nothing forbids the existence of wmain and // WinMain in the same translation unit. if (FD->isMSVCRTEntryPoint()) return false; // C++ functions and those whose names are not a simple identifier need // mangling. if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage) return true; // C functions are not mangled. if (L == CLanguageLinkage) return false; } // Otherwise, no mangling is done outside C++ mode. if (!getASTContext().getLangOpts().CPlusPlus) return false; if (const VarDecl *VD = dyn_cast
(D)) { // C variables are not mangled. if (VD->isExternC()) return false; // Variables at global scope with non-internal linkage are not mangled. const DeclContext *DC = getEffectiveDeclContext(D); // Check for extern variable declared locally. if (DC->isFunctionOrMethod() && D->hasLinkage()) while (!DC->isNamespace() && !DC->isTranslationUnit()) DC = getEffectiveParentContext(DC); if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage && !isa
(D) && D->getIdentifier() != nullptr) return false; } return true; } bool MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) { return true; } void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) { // MSVC doesn't mangle C++ names the same way it mangles extern "C" names. // Therefore it's really important that we don't decorate the // name with leading underscores or leading/trailing at signs. So, by // default, we emit an asm marker at the start so we get the name right. // Callers can override this with a custom prefix. //
::= ?
Out << Prefix; mangleName(D); if (const FunctionDecl *FD = dyn_cast
(D)) mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD)); else if (const VarDecl *VD = dyn_cast
(D)) mangleVariableEncoding(VD); else llvm_unreachable("Tried to mangle unexpected NamedDecl!"); } void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle) { //
::=
// Since MSVC operates on the type as written and not the canonical type, it // actually matters which decl we have here. MSVC appears to choose the // first, since it is most likely to be the declaration in a header file. FD = FD->getFirstDecl(); // We should never ever see a FunctionNoProtoType at this point. // We don't even know how to mangle their types anyway :). const FunctionProtoType *FT = FD->getType()->castAs
(); // extern "C" functions can hold entities that must be mangled. // As it stands, these functions still need to get expressed in the full // external name. They have their class and type omitted, replaced with '9'. if (ShouldMangle) { // We would like to mangle all extern "C" functions using this additional // component but this would break compatibility with MSVC's behavior. // Instead, do this when we know that compatibility isn't important (in // other words, when it is an overloaded extern "C" function). if (FD->isExternC() && FD->hasAttr
()) Out << "$$J0"; mangleFunctionClass(FD); mangleFunctionType(FT, FD); } else { Out << '9'; } } void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) { //
::=
//
::= 0 # private static member // ::= 1 # protected static member // ::= 2 # public static member // ::= 3 # global // ::= 4 # static local // The first character in the encoding (after the name) is the storage class. if (VD->isStaticDataMember()) { // If it's a static member, it also encodes the access level. switch (VD->getAccess()) { default: case AS_private: Out << '0'; break; case AS_protected: Out << '1'; break; case AS_public: Out << '2'; break; } } else if (!VD->isStaticLocal()) Out << '3'; else Out << '4'; // Now mangle the type. //
::=
// ::=
# pointers, references // Pointers and references are odd. The type of 'int * const foo;' gets // mangled as 'QAHA' instead of 'PAHB', for example. SourceRange SR = VD->getSourceRange(); QualType Ty = VD->getType(); if (Ty->isPointerType() || Ty->isReferenceType() || Ty->isMemberPointerType()) { mangleType(Ty, SR, QMM_Drop); manglePointerExtQualifiers( Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType()); if (const MemberPointerType *MPT = Ty->getAs
()) { mangleQualifiers(MPT->getPointeeType().getQualifiers(), true); // Member pointers are suffixed with a back reference to the member // pointer's class name. mangleName(MPT->getClass()->getAsCXXRecordDecl()); } else mangleQualifiers(Ty->getPointeeType().getQualifiers(), false); } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) { // Global arrays are funny, too. mangleDecayedArrayType(AT); if (AT->getElementType()->isArrayType()) Out << 'A'; else mangleQualifiers(Ty.getQualifiers(), false); } else { mangleType(Ty, SR, QMM_Drop); mangleQualifiers(Ty.getQualifiers(), false); } } void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD) { //
::=
// ::= $F
// ::= $G
int64_t FieldOffset; int64_t VBTableOffset; MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel(); if (VD) { FieldOffset = getASTContext().getFieldOffset(VD); assert(FieldOffset % getASTContext().getCharWidth() == 0 && "cannot take address of bitfield"); FieldOffset /= getASTContext().getCharWidth(); VBTableOffset = 0; if (IM == MSInheritanceAttr::Keyword_virtual_inheritance) FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity(); } else { FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1; VBTableOffset = -1; } char Code = '\0'; switch (IM) { case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break; case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break; case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break; case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break; } Out << '$' << Code; mangleNumber(FieldOffset); // The C++ standard doesn't allow base-to-derived member pointer conversions // in template parameter contexts, so the vbptr offset of data member pointers // is always zero. if (MSInheritanceAttr::hasVBPtrOffsetField(IM)) mangleNumber(0); if (MSInheritanceAttr::hasVBTableOffsetField(IM)) mangleNumber(VBTableOffset); } void MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD, const CXXMethodDecl *MD) { //
::= $1?
// ::= $H?
// ::= $I?
// ::= $J?
MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel(); char Code = '\0'; switch (IM) { case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break; case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break; case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break; case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break; } // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr // thunk. uint64_t NVOffset = 0; uint64_t VBTableOffset = 0; uint64_t VBPtrOffset = 0; if (MD) { Out << '$' << Code << '?'; if (MD->isVirtual()) { MicrosoftVTableContext *VTContext = cast
(getASTContext().getVTableContext()); const MicrosoftVTableContext::MethodVFTableLocation &ML = VTContext->getMethodVFTableLocation(GlobalDecl(MD)); mangleVirtualMemPtrThunk(MD, ML); NVOffset = ML.VFPtrOffset.getQuantity(); VBTableOffset = ML.VBTableIndex * 4; if (ML.VBase) { const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD); VBPtrOffset = Layout.getVBPtrOffset().getQuantity(); } } else { mangleName(MD); mangleFunctionEncoding(MD, /*ShouldMangle=*/true); } if (VBTableOffset == 0 && IM == MSInheritanceAttr::Keyword_virtual_inheritance) NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity(); } else { // Null single inheritance member functions are encoded as a simple nullptr. if (IM == MSInheritanceAttr::Keyword_single_inheritance) { Out << "$0A@"; return; } if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance) VBTableOffset = -1; Out << '$' << Code; } if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM)) mangleNumber(static_cast
(NVOffset)); if (MSInheritanceAttr::hasVBPtrOffsetField(IM)) mangleNumber(VBPtrOffset); if (MSInheritanceAttr::hasVBTableOffsetField(IM)) mangleNumber(VBTableOffset); } void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk( const CXXMethodDecl *MD, const MicrosoftVTableContext::MethodVFTableLocation &ML) { // Get the vftable offset. CharUnits PointerWidth = getASTContext().toCharUnitsFromBits( getASTContext().getTargetInfo().getPointerWidth(0)); uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity(); Out << "?_9"; mangleName(MD->getParent()); Out << "$B"; mangleNumber(OffsetInVFTable); Out << 'A'; mangleCallingConvention(MD->getType()->getAs
()); } void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) { //
::=
{[
]+ | [
]}? @ // Always start with the unqualified name. mangleUnqualifiedName(ND); mangleNestedName(ND); // Terminate the whole name with an '@'. Out << '@'; } void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) { //
::= A@ # when Number == 0 // ::=
# when 1 <= Number <= 10 // ::=
+ @ # when Number >= 10 // //
::= [?]
uint64_t Value = static_cast
(Number); if (Number < 0) { Value = -Value; Out << '?'; } if (Value == 0) Out << "A@"; else if (Value >= 1 && Value <= 10) Out << (Value - 1); else { // Numbers that are not encoded as decimal digits are represented as nibbles // in the range of ASCII characters 'A' to 'P'. // The number 0x123450 would be encoded as 'BCDEFA' char EncodedNumberBuffer[sizeof(uint64_t) * 2]; MutableArrayRef
BufferRef(EncodedNumberBuffer); MutableArrayRef
::reverse_iterator I = BufferRef.rbegin(); for (; Value != 0; Value >>= 4) *I++ = 'A' + (Value & 0xf); Out.write(I.base(), I - BufferRef.rbegin()); Out << '@'; } } static const TemplateDecl * isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) { // Check if we have a function template. if (const FunctionDecl *FD = dyn_cast
(ND)) { if (const TemplateDecl *TD = FD->getPrimaryTemplate()) { TemplateArgs = FD->getTemplateSpecializationArgs(); return TD; } } // Check if we have a class template. if (const ClassTemplateSpecializationDecl *Spec = dyn_cast
(ND)) { TemplateArgs = &Spec->getTemplateArgs(); return Spec->getSpecializedTemplate(); } // Check if we have a variable template. if (const VarTemplateSpecializationDecl *Spec = dyn_cast
(ND)) { TemplateArgs = &Spec->getTemplateArgs(); return Spec->getSpecializedTemplate(); } return nullptr; } void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name) { //
::=
// ::=
// ::=
// ::=
// Check if we have a template. const TemplateArgumentList *TemplateArgs = nullptr; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { // Function templates aren't considered for name back referencing. This // makes sense since function templates aren't likely to occur multiple // times in a symbol. if (isa
(TD)) { mangleTemplateInstantiationName(TD, *TemplateArgs); Out << '@'; return; } // Here comes the tricky thing: if we need to mangle something like // void foo(A::X
, B::X
), // the X
part is aliased. However, if you need to mangle // void foo(A::X
, A::X
), // the A::X<> part is not aliased. // That said, from the mangler's perspective we have a structure like this: // namespace[s] -> type[ -> template-parameters] // but from the Clang perspective we have // type [ -> template-parameters] // \-> namespace[s] // What we do is we create a new mangler, mangle the same type (without // a namespace suffix) to a string using the extra mangler and then use // the mangled type name as a key to check the mangling of different types // for aliasing. llvm::SmallString<64> TemplateMangling; llvm::raw_svector_ostream Stream(TemplateMangling); MicrosoftCXXNameMangler Extra(Context, Stream); Extra.mangleTemplateInstantiationName(TD, *TemplateArgs); mangleSourceName(TemplateMangling); return; } switch (Name.getNameKind()) { case DeclarationName::Identifier: { if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { mangleSourceName(II->getName()); break; } // Otherwise, an anonymous entity. We must have a declaration. assert(ND && "mangling empty name without declaration"); if (const NamespaceDecl *NS = dyn_cast
(ND)) { if (NS->isAnonymousNamespace()) { Out << "?A@"; break; } } if (const VarDecl *VD = dyn_cast
(ND)) { // We must have an anonymous union or struct declaration. const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl(); assert(RD && "expected variable decl to have a record type"); // Anonymous types with no tag or typedef get the name of their // declarator mangled in. If they have no declarator, number them with // a $S prefix. llvm::SmallString<64> Name("$S"); // Get a unique id for the anonymous struct. Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1); mangleSourceName(Name.str()); break; } // We must have an anonymous struct. const TagDecl *TD = cast
(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()->getName()); break; } if (const CXXRecordDecl *Record = dyn_cast
(TD)) { if (Record->isLambda()) { llvm::SmallString<10> Name("
getLambdaManglingNumber()) LambdaId = Record->getLambdaManglingNumber(); else LambdaId = Context.getLambdaId(Record); Name += llvm::utostr(LambdaId); Name += ">"; mangleSourceName(Name); break; } } llvm::SmallString<64> Name("
getName(); } else if (TypedefNameDecl *TND = Context.getASTContext().getTypedefNameForUnnamedTagDecl( TD)) { // Anonymous types without a name for linkage purposes have their // associate typedef mangled in if they have one. Name += TND->getName(); } else { // Otherwise, number the types using a $S prefix. Name += "$S"; Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1); } Name += ">"; mangleSourceName(Name.str()); break; } case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: llvm_unreachable("Can't mangle Objective-C selector names here!"); case DeclarationName::CXXConstructorName: if (Structor == getStructor(ND)) { if (StructorType == Ctor_CopyingClosure) { Out << "?_O"; return; } if (StructorType == Ctor_DefaultClosure) { Out << "?_F"; return; } } Out << "?0"; return; case DeclarationName::CXXDestructorName: if (ND == Structor) // If the named decl is the C++ destructor we're mangling, // use the type we were given. mangleCXXDtorType(static_cast
(StructorType)); else // Otherwise, use the base destructor name. This is relevant if a // class with a destructor is declared within a destructor. mangleCXXDtorType(Dtor_Base); break; case DeclarationName::CXXConversionFunctionName: //
::= ?B # (cast) // The target type is encoded as the return type. Out << "?B"; break; case DeclarationName::CXXOperatorName: mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation()); break; case DeclarationName::CXXLiteralOperatorName: { Out << "?__K"; mangleSourceName(Name.getCXXLiteralIdentifier()->getName()); break; } case DeclarationName::CXXUsingDirective: llvm_unreachable("Can't mangle a using directive name!"); } } void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) { //
::=
[
] // ::=
[
] const DeclContext *DC = getEffectiveDeclContext(ND); while (!DC->isTranslationUnit()) { if (isa
(ND) || isa
(ND)) { unsigned Disc; if (Context.getNextDiscriminator(ND, Disc)) { Out << '?'; mangleNumber(Disc); Out << '?'; } } if (const BlockDecl *BD = dyn_cast
(DC)) { DiagnosticsEngine &Diags = Context.getDiags(); unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "cannot mangle a local inside this block yet"); Diags.Report(BD->getLocation(), DiagID); // FIXME: This is completely, utterly, wrong; see ItaniumMangle // for how this should be done. Out << "__block_invoke" << Context.getBlockId(BD, false); Out << '@'; continue; } else if (const ObjCMethodDecl *Method = dyn_cast
(DC)) { mangleObjCMethodName(Method); } else if (isa
(DC)) { ND = cast
(DC); if (const FunctionDecl *FD = dyn_cast
(ND)) { mangle(FD, "?"); break; } else mangleUnqualifiedName(ND); } DC = DC->getParent(); } } void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) { // Microsoft uses the names on the case labels for these dtor variants. Clang // uses the Itanium terminology internally. Everything in this ABI delegates // towards the base dtor. switch (T) { //
::= ?1 # destructor case Dtor_Base: Out << "?1"; return; //
::= ?_D # vbase destructor case Dtor_Complete: Out << "?_D"; return; //
::= ?_G # scalar deleting destructor case Dtor_Deleting: Out << "?_G"; return; //
::= ?_E # vector deleting destructor // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need // it. case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT"); } llvm_unreachable("Unsupported dtor type?"); } void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc) { switch (OO) { // ?0 # constructor // ?1 # destructor //
::= ?2 # new case OO_New: Out << "?2"; break; //
::= ?3 # delete case OO_Delete: Out << "?3"; break; //
::= ?4 # = case OO_Equal: Out << "?4"; break; //
::= ?5 # >> case OO_GreaterGreater: Out << "?5"; break; //
::= ?6 # << case OO_LessLess: Out << "?6"; break; //
::= ?7 # ! case OO_Exclaim: Out << "?7"; break; //
::= ?8 # == case OO_EqualEqual: Out << "?8"; break; //
::= ?9 # != case OO_ExclaimEqual: Out << "?9"; break; //
::= ?A # [] case OO_Subscript: Out << "?A"; break; // ?B # conversion //
::= ?C # -> case OO_Arrow: Out << "?C"; break; //
::= ?D # * case OO_Star: Out << "?D"; break; //
::= ?E # ++ case OO_PlusPlus: Out << "?E"; break; //
::= ?F # -- case OO_MinusMinus: Out << "?F"; break; //
::= ?G # - case OO_Minus: Out << "?G"; break; //
::= ?H # + case OO_Plus: Out << "?H"; break; //
::= ?I # & case OO_Amp: Out << "?I"; break; //
::= ?J # ->* case OO_ArrowStar: Out << "?J"; break; //
::= ?K # / case OO_Slash: Out << "?K"; break; //
::= ?L # % case OO_Percent: Out << "?L"; break; //
::= ?M # < case OO_Less: Out << "?M"; break; //
::= ?N # <= case OO_LessEqual: Out << "?N"; break; //
::= ?O # > case OO_Greater: Out << "?O"; break; //
::= ?P # >= case OO_GreaterEqual: Out << "?P"; break; //
::= ?Q # , case OO_Comma: Out << "?Q"; break; //
::= ?R # () case OO_Call: Out << "?R"; break; //
::= ?S # ~ case OO_Tilde: Out << "?S"; break; //
::= ?T # ^ case OO_Caret: Out << "?T"; break; //
::= ?U # | case OO_Pipe: Out << "?U"; break; //
::= ?V # && case OO_AmpAmp: Out << "?V"; break; //
::= ?W # || case OO_PipePipe: Out << "?W"; break; //
::= ?X # *= case OO_StarEqual: Out << "?X"; break; //
::= ?Y # += case OO_PlusEqual: Out << "?Y"; break; //
::= ?Z # -= case OO_MinusEqual: Out << "?Z"; break; //
::= ?_0 # /= case OO_SlashEqual: Out << "?_0"; break; //
::= ?_1 # %= case OO_PercentEqual: Out << "?_1"; break; //
::= ?_2 # >>= case OO_GreaterGreaterEqual: Out << "?_2"; break; //
::= ?_3 # <<= case OO_LessLessEqual: Out << "?_3"; break; //
::= ?_4 # &= case OO_AmpEqual: Out << "?_4"; break; //
::= ?_5 # |= case OO_PipeEqual: Out << "?_5"; break; //
::= ?_6 # ^= case OO_CaretEqual: Out << "?_6"; break; // ?_7 # vftable // ?_8 # vbtable // ?_9 # vcall // ?_A # typeof // ?_B # local static guard // ?_C # string // ?_D # vbase destructor // ?_E # vector deleting destructor // ?_F # default constructor closure // ?_G # scalar deleting destructor // ?_H # vector constructor iterator // ?_I # vector destructor iterator // ?_J # vector vbase constructor iterator // ?_K # virtual displacement map // ?_L # eh vector constructor iterator // ?_M # eh vector destructor iterator // ?_N # eh vector vbase constructor iterator // ?_O # copy constructor closure // ?_P
# udt returning
// ?_Q #
// ?_R0 # RTTI Type Descriptor // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d) // ?_R2 # RTTI Base Class Array // ?_R3 # RTTI Class Hierarchy Descriptor // ?_R4 # RTTI Complete Object Locator // ?_S # local vftable // ?_T # local vftable constructor closure //
::= ?_U # new[] case OO_Array_New: Out << "?_U"; break; //
::= ?_V # delete[] case OO_Array_Delete: Out << "?_V"; break; case OO_Conditional: { DiagnosticsEngine &Diags = Context.getDiags(); unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "cannot mangle this conditional operator yet"); Diags.Report(Loc, DiagID); break; } case OO_Coawait: { DiagnosticsEngine &Diags = Context.getDiags(); unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "cannot mangle this operator co_await yet"); Diags.Report(Loc, DiagID); break; } case OO_None: case NUM_OVERLOADED_OPERATORS: llvm_unreachable("Not an overloaded operator"); } } void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) { //
::=
@ BackRefVec::iterator Found = std::find(NameBackReferences.begin(), NameBackReferences.end(), Name); if (Found == NameBackReferences.end()) { if (NameBackReferences.size() < 10) NameBackReferences.push_back(Name); Out << Name << '@'; } else { Out << (Found - NameBackReferences.begin()); } } void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { Context.mangleObjCMethodName(MD, Out); } void MicrosoftCXXNameMangler::mangleTemplateInstantiationName( const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) { //
::=
// ::=
// Always start with the unqualified name. // Templates have their own context for back references. ArgBackRefMap OuterArgsContext; BackRefVec OuterTemplateContext; PassObjectSizeArgsSet OuterPassObjectSizeArgs; NameBackReferences.swap(OuterTemplateContext); TypeBackReferences.swap(OuterArgsContext); PassObjectSizeArgs.swap(OuterPassObjectSizeArgs); mangleUnscopedTemplateName(TD); mangleTemplateArgs(TD, TemplateArgs); // Restore the previous back reference contexts. NameBackReferences.swap(OuterTemplateContext); TypeBackReferences.swap(OuterArgsContext); PassObjectSizeArgs.swap(OuterPassObjectSizeArgs); } void MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) { //
::= ?$
Out << "?$"; mangleUnqualifiedName(TD); } void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value, bool IsBoolean) { //
::= $0
Out << "$0"; // Make sure booleans are encoded as 0/1. if (IsBoolean && Value.getBoolValue()) mangleNumber(1); else if (Value.isSigned()) mangleNumber(Value.getSExtValue()); else mangleNumber(Value.getZExtValue()); } void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) { // See if this is a constant expression. llvm::APSInt Value; if (E->isIntegerConstantExpr(Value, Context.getASTContext())) { mangleIntegerLiteral(Value, E->getType()->isBooleanType()); return; } // Look through no-op casts like template parameter substitutions. E = E->IgnoreParenNoopCasts(Context.getASTContext()); const CXXUuidofExpr *UE = nullptr; if (const UnaryOperator *UO = dyn_cast
(E)) { if (UO->getOpcode() == UO_AddrOf) UE = dyn_cast
(UO->getSubExpr()); } else UE = dyn_cast
(E); if (UE) { // If we had to peek through an address-of operator, treat this like we are // dealing with a pointer type. Otherwise, treat it like a const reference. // // N.B. This matches up with the handling of TemplateArgument::Declaration // in mangleTemplateArg if (UE == E) Out << "$E?"; else Out << "$1?"; // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from // const __s_GUID _GUID_{lower case UUID with underscores} StringRef Uuid = UE->getUuidStr(); std::string Name = "_GUID_" + Uuid.lower(); std::replace(Name.begin(), Name.end(), '-', '_'); mangleSourceName(Name); // Terminate the whole name with an '@'. Out << '@'; // It's a global variable. Out << '3'; // It's a struct called __s_GUID. mangleArtificalTagType(TTK_Struct, "__s_GUID"); // It's const. Out << 'B'; return; } // As bad as this diagnostic is, it's better than crashing. 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(); } void MicrosoftCXXNameMangler::mangleTemplateArgs( const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) { //
::=
+ const TemplateParameterList *TPL = TD->getTemplateParameters(); assert(TPL->size() == TemplateArgs.size() && "size mismatch between args and parms!"); unsigned Idx = 0; for (const TemplateArgument &TA : TemplateArgs.asArray()) mangleTemplateArg(TD, TA, TPL->getParam(Idx++)); } void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA, const NamedDecl *Parm) { //
::=
// ::=
// ::=
// ::=
// ::= $E?
// ::= $1?
// ::= $0A@ // ::=
switch (TA.getKind()) { case TemplateArgument::Null: llvm_unreachable("Can't mangle null template arguments!"); case TemplateArgument::TemplateExpansion: llvm_unreachable("Can't mangle template expansion arguments!"); case TemplateArgument::Type: { QualType T = TA.getAsType(); mangleType(T, SourceRange(), QMM_Escape); break; } case TemplateArgument::Declaration: { const NamedDecl *ND = cast
(TA.getAsDecl()); if (isa
(ND) || isa
(ND)) { mangleMemberDataPointer( cast
(ND->getDeclContext())->getMostRecentDecl(), cast
(ND)); } else if (const FunctionDecl *FD = dyn_cast
(ND)) { const CXXMethodDecl *MD = dyn_cast
(FD); if (MD && MD->isInstance()) { mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD); } else { Out << "$1?"; mangleName(FD); mangleFunctionEncoding(FD, /*ShouldMangle=*/true); } } else { mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?"); } break; } case TemplateArgument::Integral: mangleIntegerLiteral(TA.getAsIntegral(), TA.getIntegralType()->isBooleanType()); break; case TemplateArgument::NullPtr: { QualType T = TA.getNullPtrType(); if (const MemberPointerType *MPT = T->getAs
()) { const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); if (MPT->isMemberFunctionPointerType() && !isa
(TD)) { mangleMemberFunctionPointer(RD, nullptr); return; } if (MPT->isMemberDataPointer()) { if (!isa
(TD)) { mangleMemberDataPointer(RD, nullptr); return; } // nullptr data pointers are always represented with a single field // which is initialized with either 0 or -1. Why -1? Well, we need to // distinguish the case where the data member is at offset zero in the // record. // However, we are free to use 0 *if* we would use multiple fields for // non-nullptr member pointers. if (!RD->nullFieldOffsetIsZero()) { mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false); return; } } } mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false); break; } case TemplateArgument::Expression: mangleExpression(TA.getAsExpr()); break; case TemplateArgument::Pack: { ArrayRef
TemplateArgs = TA.getPackAsArray(); if (TemplateArgs.empty()) { if (isa
(Parm) || isa
(Parm)) // MSVC 2015 changed the mangling for empty expanded template packs, // use the old mangling for link compatibility for old versions. Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC( LangOptions::MSVC2015) ? "$$V" : "$$$V"); else if (isa
(Parm)) Out << "$S"; else llvm_unreachable("unexpected template parameter decl!"); } else { for (const TemplateArgument &PA : TemplateArgs) mangleTemplateArg(TD, PA, Parm); } break; } case TemplateArgument::Template: { const NamedDecl *ND = TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl(); if (const auto *TD = dyn_cast
(ND)) { mangleType(TD); } else if (isa
(ND)) { Out << "$$Y"; mangleName(ND); } else { llvm_unreachable("unexpected template template NamedDecl!"); } break; } } } void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals, bool IsMember) { //
::= [E] [F] [I]
// 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only); // 'I' means __restrict (32/64-bit). // Note that the MSVC __restrict keyword isn't the same as the C99 restrict // keyword! //
::= A # near // ::= B # near const // ::= C # near volatile // ::= D # near const volatile // ::= E # far (16-bit) // ::= F # far const (16-bit) // ::= G # far volatile (16-bit) // ::= H # far const volatile (16-bit) // ::= I # huge (16-bit) // ::= J # huge const (16-bit) // ::= K # huge volatile (16-bit) // ::= L # huge const volatile (16-bit) // ::= M
# based // ::= N
# based const // ::= O
# based volatile // ::= P
# based const volatile // ::= Q # near member // ::= R # near const member // ::= S # near volatile member // ::= T # near const volatile member // ::= U # far member (16-bit) // ::= V # far const member (16-bit) // ::= W # far volatile member (16-bit) // ::= X # far const volatile member (16-bit) // ::= Y # huge member (16-bit) // ::= Z # huge const member (16-bit) // ::= 0 # huge volatile member (16-bit) // ::= 1 # huge const volatile member (16-bit) // ::= 2
# based member // ::= 3
# based const member // ::= 4
# based volatile member // ::= 5
# based const volatile member // ::= 6 # near function (pointers only) // ::= 7 # far function (pointers only) // ::= 8 # near method (pointers only) // ::= 9 # far method (pointers only) // ::= _A
# based function (pointers only) // ::= _B
# based function (far?) (pointers only) // ::= _C
# based method (pointers only) // ::= _D
# based method (far?) (pointers only) // ::= _E # block (Clang) //
::= 0 # __based(void) // ::= 1 # __based(segment)? // ::= 2
# __based(name) // ::= 3 # ? // ::= 4 # ? // ::= 5 # not really based bool HasConst = Quals.hasConst(), HasVolatile = Quals.hasVolatile(); if (!IsMember) { if (HasConst && HasVolatile) { Out << 'D'; } else if (HasVolatile) { Out << 'C'; } else if (HasConst) { Out << 'B'; } else { Out << 'A'; } } else { if (HasConst && HasVolatile) { Out << 'T'; } else if (HasVolatile) { Out << 'S'; } else if (HasConst) { Out << 'R'; } else { Out << 'Q'; } } // FIXME: For now, just drop all extension qualifiers on the floor. } void MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { //
::= G # lvalue reference // ::= H # rvalue-reference switch (RefQualifier) { case RQ_None: break; case RQ_LValue: Out << 'G'; break; case RQ_RValue: Out << 'H'; break; } } void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType) { bool HasRestrict = Quals.hasRestrict(); if (PointersAre64Bit && (PointeeType.isNull() || !PointeeType->isFunctionType())) Out << 'E'; if (HasRestrict) Out << 'I'; if (Quals.hasUnaligned() || (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned())) Out << 'F'; } void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) { //
::= P # no qualifiers // ::= Q # const // ::= R # volatile // ::= S # const volatile bool HasConst = Quals.hasConst(), HasVolatile = Quals.hasVolatile(); if (HasConst && HasVolatile) { Out << 'S'; } else if (HasVolatile) { Out << 'R'; } else if (HasConst) { Out << 'Q'; } else { Out << 'P'; } } void MicrosoftCXXNameMangler::mangleArgumentType(QualType T, SourceRange Range) { // MSVC will backreference two canonically equivalent types that have slightly // different manglings when mangled alone. // Decayed types do not match up with non-decayed versions of the same type. // // e.g. // void (*x)(void) will not form a backreference with void x(void) void *TypePtr; if (const auto *DT = T->getAs
()) { QualType OriginalType = DT->getOriginalType(); // All decayed ArrayTypes should be treated identically; as-if they were // a decayed IncompleteArrayType. if (const auto *AT = getASTContext().getAsArrayType(OriginalType)) OriginalType = getASTContext().getIncompleteArrayType( AT->getElementType(), AT->getSizeModifier(), AT->getIndexTypeCVRQualifiers()); TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr(); // If the original parameter was textually written as an array, // instead treat the decayed parameter like it's const. // // e.g. // int [] -> int * const if (OriginalType->isArrayType()) T = T.withConst(); } else { TypePtr = T.getCanonicalType().getAsOpaquePtr(); } ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr); if (Found == TypeBackReferences.end()) { size_t OutSizeBefore = Out.tell(); mangleType(T, Range, QMM_Drop); // See if it's worth creating a back reference. // Only types longer than 1 character are considered // and only 10 back references slots are available: bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1); if (LongerThanOneChar && TypeBackReferences.size() < 10) { size_t Size = TypeBackReferences.size(); TypeBackReferences[TypePtr] = Size; } } else { Out << Found->second; } } void MicrosoftCXXNameMangler::manglePassObjectSizeArg( const PassObjectSizeAttr *POSA) { int Type = POSA->getType(); auto Iter = PassObjectSizeArgs.insert(Type).first; auto *TypePtr = (const void *)&*Iter; ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr); if (Found == TypeBackReferences.end()) { mangleArtificalTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type), {"__clang"}); if (TypeBackReferences.size() < 10) { size_t Size = TypeBackReferences.size(); TypeBackReferences[TypePtr] = Size; } } else { Out << Found->second; } } void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range, QualifierMangleMode QMM) { // Don't use the canonical types. MSVC includes things like 'const' on // pointer arguments to function pointers that canonicalization strips away. T = T.getDesugaredType(getASTContext()); Qualifiers Quals = T.getLocalQualifiers(); if (const ArrayType *AT = getASTContext().getAsArrayType(T)) { // If there were any Quals, getAsArrayType() pushed them onto the array // element type. if (QMM == QMM_Mangle) Out << 'A'; else if (QMM == QMM_Escape || QMM == QMM_Result) Out << "$$B"; mangleArrayType(AT); return; } bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() || T->isReferenceType() || T->isBlockPointerType(); switch (QMM) { case QMM_Drop: break; case QMM_Mangle: if (const FunctionType *FT = dyn_cast
(T)) { Out << '6'; mangleFunctionType(FT); return; } mangleQualifiers(Quals, false); break; case QMM_Escape: if (!IsPointer && Quals) { Out << "$$C"; mangleQualifiers(Quals, false); } break; case QMM_Result: // Presence of __unaligned qualifier shouldn't affect mangling here. Quals.removeUnaligned(); if ((!IsPointer && Quals) || isa
(T)) { Out << '?'; mangleQualifiers(Quals, false); } break; } const Type *ty = T.getTypePtr(); 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(cast
(ty), Quals, Range); \ break; #include "clang/AST/TypeNodes.def" #undef ABSTRACT_TYPE #undef NON_CANONICAL_TYPE #undef TYPE } } void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers, SourceRange Range) { //
::=
//
::= X # void // ::= C # signed char // ::= D # char // ::= E # unsigned char // ::= F # short // ::= G # unsigned short (or wchar_t if it's not a builtin) // ::= H # int // ::= I # unsigned int // ::= J # long // ::= K # unsigned long // L #
// ::= M # float // ::= N # double // ::= O # long double (__float80 is mangled differently) // ::= _J # long long, __int64 // ::= _K # unsigned long long, __int64 // ::= _L # __int128 // ::= _M # unsigned __int128 // ::= _N # bool // _O #
// ::= _T # __float80 (Intel) // ::= _W # wchar_t // ::= _Z # __float80 (Digital Mars) switch (T->getKind()) { case BuiltinType::Void: Out << 'X'; break; case BuiltinType::SChar: Out << 'C'; break; case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break; case BuiltinType::UChar: Out << 'E'; break; case BuiltinType::Short: Out << 'F'; break; case BuiltinType::UShort: Out << 'G'; break; case BuiltinType::Int: Out << 'H'; break; case BuiltinType::UInt: Out << 'I'; break; case BuiltinType::Long: Out << 'J'; break; case BuiltinType::ULong: Out << 'K'; break; case BuiltinType::Float: Out << 'M'; break; case BuiltinType::Double: Out << 'N'; break; // TODO: Determine size and mangle accordingly case BuiltinType::LongDouble: Out << 'O'; break; case BuiltinType::LongLong: Out << "_J"; break; case BuiltinType::ULongLong: Out << "_K"; break; case BuiltinType::Int128: Out << "_L"; break; case BuiltinType::UInt128: Out << "_M"; break; case BuiltinType::Bool: Out << "_N"; break; case BuiltinType::Char16: Out << "_S"; break; case BuiltinType::Char32: Out << "_U"; break; case BuiltinType::WChar_S: case BuiltinType::WChar_U: Out << "_W"; break; #define BUILTIN_TYPE(Id, SingletonId) #define PLACEHOLDER_TYPE(Id, SingletonId) \ case BuiltinType::Id: #include "clang/AST/BuiltinTypes.def" case BuiltinType::Dependent: llvm_unreachable("placeholder types shouldn't get to name mangling"); case BuiltinType::ObjCId: Out << "PA"; mangleArtificalTagType(TTK_Struct, "objc_object"); break; case BuiltinType::ObjCClass: Out << "PA"; mangleArtificalTagType(TTK_Struct, "objc_class"); break; case BuiltinType::ObjCSel: Out << "PA"; mangleArtificalTagType(TTK_Struct, "objc_selector"); break; #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: \ Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \ break; #include "clang/Basic/OpenCLImageTypes.def" case BuiltinType::OCLSampler: Out << "PA"; mangleArtificalTagType(TTK_Struct, "ocl_sampler"); break; case BuiltinType::OCLEvent: Out << "PA"; mangleArtificalTagType(TTK_Struct, "ocl_event"); break; case BuiltinType::OCLClkEvent: Out << "PA"; mangleArtificalTagType(TTK_Struct, "ocl_clkevent"); break; case BuiltinType::OCLQueue: Out << "PA"; mangleArtificalTagType(TTK_Struct, "ocl_queue"); break; case BuiltinType::OCLNDRange: Out << "PA"; mangleArtificalTagType(TTK_Struct, "ocl_ndrange"); break; case BuiltinType::OCLReserveID: Out << "PA"; mangleArtificalTagType(TTK_Struct, "ocl_reserveid"); break; case BuiltinType::NullPtr: Out << "$$T"; break; case BuiltinType::Float128: case BuiltinType::Half: { DiagnosticsEngine &Diags = Context.getDiags(); unsigned DiagID = Diags.getCustomDiagID( DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet"); Diags.Report(Range.getBegin(), DiagID) << T->getName(Context.getASTContext().getPrintingPolicy()) << Range; break; } } } //
::=
void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers, SourceRange) { // Structors only appear in decls, so at this point we know it's not a // structor type. // FIXME: This may not be lambda-friendly. if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) { Out << "$$A8@@"; mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true); } else { Out << "$$A6"; mangleFunctionType(T); } } void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T, Qualifiers, SourceRange) { Out << "$$A6"; mangleFunctionType(T); } void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T, const FunctionDecl *D, bool ForceThisQuals) { //
::=
//
const FunctionProtoType *Proto = dyn_cast
(T); SourceRange Range; if (D) Range = D->getSourceRange(); bool IsInLambda = false; bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false; CallingConv CC = T->getCallConv(); if (const CXXMethodDecl *MD = dyn_cast_or_null
(D)) { if (MD->getParent()->isLambda()) IsInLambda = true; if (MD->isInstance()) HasThisQuals = true; if (isa
(MD)) { IsStructor = true; } else if (isa
(MD)) { IsStructor = true; IsCtorClosure = (StructorType == Ctor_CopyingClosure || StructorType == Ctor_DefaultClosure) && getStructor(MD) == Structor; if (IsCtorClosure) CC = getASTContext().getDefaultCallingConvention( /*IsVariadic=*/false, /*IsCXXMethod=*/true); } } // If this is a C++ instance method, mangle the CVR qualifiers for the // this pointer. if (HasThisQuals) { Qualifiers Quals = Qualifiers::fromCVRUMask(Proto->getTypeQuals()); manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType()); mangleRefQualifier(Proto->getRefQualifier()); mangleQualifiers(Quals, /*IsMember=*/false); } mangleCallingConvention(CC); //
::=
// ::= @ # structors (they have no declared return type) if (IsStructor) { if (isa
(D) && D == Structor && StructorType == Dtor_Deleting) { // The scalar deleting destructor takes an extra int argument. // However, the FunctionType generated has 0 arguments. // FIXME: This is a temporary hack. // Maybe should fix the FunctionType creation instead? Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z"); return; } if (IsCtorClosure) { // Default constructor closure and copy constructor closure both return // void. Out << 'X'; if (StructorType == Ctor_DefaultClosure) { // Default constructor closure always has no arguments. Out << 'X'; } else if (StructorType == Ctor_CopyingClosure) { // Copy constructor closure always takes an unqualified reference. mangleArgumentType(getASTContext().getLValueReferenceType( Proto->getParamType(0) ->getAs
() ->getPointeeType(), /*SpelledAsLValue=*/true), Range); Out << '@'; } else { llvm_unreachable("unexpected constructor closure!"); } Out << 'Z'; return; } Out << '@'; } else { QualType ResultType = T->getReturnType(); if (const auto *AT = dyn_cast_or_null
(ResultType->getContainedAutoType())) { Out << '?'; mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false); Out << '?'; assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType && "shouldn't need to mangle __auto_type!"); mangleSourceName(AT->isDecltypeAuto() ? "
" : "