//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements C++ name mangling according to the Itanium C++ ABI, // which is used in GCC 3.2 and newer (and many compilers that are // ABI-compatible with GCC): // // http://mentorembedded.github.io/cxx-abi/abi.html#mangling // //===----------------------------------------------------------------------===// #include "clang/AST/Mangle.h" #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/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/ABI.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #define MANGLE_CHECKER 0 #if MANGLE_CHECKER #include #endif using namespace clang; namespace { /// 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 (const CapturedDecl *CD = dyn_cast(DC)) return getEffectiveDeclContext(CD); if (const auto *VD = dyn_cast(D)) if (VD->isExternC()) return VD->getASTContext().getTranslationUnitDecl(); if (const auto *FD = dyn_cast(D)) if (FD->isExternC()) return FD->getASTContext().getTranslationUnitDecl(); return DC; } static const DeclContext *getEffectiveParentContext(const DeclContext *DC) { return getEffectiveDeclContext(cast(DC)); } static bool isLocalContainerContext(const DeclContext *DC) { return isa(DC) || isa(DC) || isa(DC); } static const RecordDecl *GetLocalClassDecl(const Decl *D) { const DeclContext *DC = getEffectiveDeclContext(D); while (!DC->isNamespace() && !DC->isTranslationUnit()) { if (isLocalContainerContext(DC)) return dyn_cast(D); D = cast(DC); DC = getEffectiveDeclContext(D); } return nullptr; } 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(decl); return (fn ? getStructor(fn) : decl); } static bool isLambda(const NamedDecl *ND) { const CXXRecordDecl *Record = dyn_cast(ND); if (!Record) return false; return Record->isLambda(); } static const unsigned UnknownArity = ~0U; class ItaniumMangleContextImpl : public ItaniumMangleContext { typedef std::pair DiscriminatorKeyTy; llvm::DenseMap Discriminator; llvm::DenseMap Uniquifier; public: explicit ItaniumMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags) : ItaniumMangleContext(Context, Diags) {} /// @name Mangler Entry Points /// @{ bool shouldMangleCXXName(const NamedDecl *D) override; bool shouldMangleStringLiteral(const StringLiteral *) override { return false; } void mangleCXXName(const NamedDecl *D, 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 mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, raw_ostream &) override; void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, 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 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; bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) { // Lambda closure types are already numbered. if (isLambda(ND)) return false; // Anonymous tags are already numbered. if (const TagDecl *Tag = dyn_cast(ND)) { if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl()) return false; } // Use the canonical number for externally visible decls. if (ND->isExternallyVisible()) { unsigned discriminator = getASTContext().getManglingNumber(ND); if (discriminator == 1) return false; disc = discriminator - 2; return true; } // Make up a reasonable number for internal decls. 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; } /// @} }; /// Manage the mangling of a single name. class CXXNameMangler { ItaniumMangleContextImpl &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; /// The next substitution sequence number. unsigned SeqID; class FunctionTypeDepthState { unsigned Bits; enum { InResultTypeMask = 1 }; public: FunctionTypeDepthState() : Bits(0) {} /// The number of function types we're inside. unsigned getDepth() const { return Bits >> 1; } /// True if we're in the return type of the innermost function type. 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; llvm::DenseMap Substitutions; ASTContext &getASTContext() const { return Context.getASTContext(); } public: CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, const NamedDecl *D = nullptr) : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0), SeqID(0) { // These can't be mangled without a ctor type or dtor type. assert(!D || (!isa(D) && !isa(D))); } CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, const CXXConstructorDecl *D, CXXCtorType Type) : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), SeqID(0) { } CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, const CXXDestructorDecl *D, CXXDtorType Type) : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), SeqID(0) { } #if MANGLE_CHECKER ~CXXNameMangler() { if (Out.str()[0] == '\01') return; int status = 0; char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status); assert(status == 0 && "Could not demangle mangled name!"); free(result); } #endif raw_ostream &getStream() { return Out; } void mangle(const NamedDecl *D); 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(const FunctionDecl *FD); void mangleSeqID(unsigned SeqID); void mangleName(const NamedDecl *ND); void mangleType(QualType T); void mangleNameOrStandardSubstitution(const NamedDecl *ND); private: bool mangleSubstitution(const NamedDecl *ND); bool mangleSubstitution(QualType T); bool mangleSubstitution(TemplateName Template); bool mangleSubstitution(uintptr_t Ptr); void mangleExistingSubstitution(QualType type); void mangleExistingSubstitution(TemplateName name); bool mangleStandardSubstitution(const NamedDecl *ND); void addSubstitution(const NamedDecl *ND) { ND = cast(ND->getCanonicalDecl()); addSubstitution(reinterpret_cast(ND)); } void addSubstitution(QualType T); void addSubstitution(TemplateName Template); void addSubstitution(uintptr_t Ptr); void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, bool recursive = false); void mangleUnresolvedName(NestedNameSpecifier *qualifier, DeclarationName name, unsigned KnownArity = UnknownArity); void mangleName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void mangleUnqualifiedName(const NamedDecl *ND) { mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity); } void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name, unsigned KnownArity); void mangleUnscopedName(const NamedDecl *ND); void mangleUnscopedTemplateName(const TemplateDecl *ND); void mangleUnscopedTemplateName(TemplateName); void mangleSourceName(const IdentifierInfo *II); void mangleLocalName(const Decl *D); void mangleBlockForPrefix(const BlockDecl *Block); void mangleUnqualifiedBlock(const BlockDecl *Block); void mangleLambda(const CXXRecordDecl *Lambda); void mangleNestedName(const NamedDecl *ND, const DeclContext *DC, bool NoFunction=false); void mangleNestedName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void manglePrefix(NestedNameSpecifier *qualifier); void manglePrefix(const DeclContext *DC, bool NoFunction=false); void manglePrefix(QualType type); void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false); void mangleTemplatePrefix(TemplateName Template); bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType, StringRef Prefix = ""); void mangleOperatorName(DeclarationName Name, unsigned Arity); void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity); void mangleQualifiers(Qualifiers Quals); void mangleRefQualifier(RefQualifierKind RefQualifier); void mangleObjCMethodName(const ObjCMethodDecl *MD); // 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); #include "clang/AST/TypeNodes.def" void mangleType(const TagType*); void mangleType(TemplateName); void mangleBareFunctionType(const FunctionType *T, bool MangleReturnType, const FunctionDecl *FD = nullptr); void mangleNeonVectorType(const VectorType *T); void mangleAArch64NeonVectorType(const VectorType *T); void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value); void mangleMemberExprBase(const Expr *base, bool isArrow); void mangleMemberExpr(const Expr *base, bool isArrow, NestedNameSpecifier *qualifier, NamedDecl *firstQualifierLookup, DeclarationName name, unsigned knownArity); void mangleCastExpression(const Expr *E, StringRef CastEncoding); void mangleInitListElements(const InitListExpr *InitList); void mangleExpression(const Expr *E, unsigned Arity = UnknownArity); void mangleCXXCtorType(CXXCtorType T); void mangleCXXDtorType(CXXDtorType T); void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs); void mangleTemplateArgs(const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void mangleTemplateArgs(const TemplateArgumentList &AL); void mangleTemplateArg(TemplateArgument A); void mangleTemplateParameter(unsigned Index); void mangleFunctionParam(const ParmVarDecl *parm); }; } bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) { const FunctionDecl *FD = dyn_cast(D); if (FD) { LanguageLinkage L = FD->getLanguageLinkage(); // Overloadable functions need mangling. if (FD->hasAttr()) return true; // "main" is not mangled. if (FD->isMain()) 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; const VarDecl *VD = dyn_cast(D); if (VD) { // 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)) return false; } return true; } void CXXNameMangler::mangle(const NamedDecl *D) { // ::= _Z // ::= // ::= Out << "_Z"; if (const FunctionDecl *FD = dyn_cast(D)) mangleFunctionEncoding(FD); else if (const VarDecl *VD = dyn_cast(D)) mangleName(VD); else if (const IndirectFieldDecl *IFD = dyn_cast(D)) mangleName(IFD->getAnonField()); else mangleName(cast(D)); } void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) { // ::= mangleName(FD); // Don't mangle in the type if this isn't a decl we should typically mangle. if (!Context.shouldMangleDeclName(FD)) return; if (FD->hasAttr()) { FunctionTypeDepthState Saved = FunctionTypeDepth.push(); Out << "Ua9enable_ifI"; // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use // it here. for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(), E = FD->getAttrs().rend(); I != E; ++I) { EnableIfAttr *EIA = dyn_cast(*I); if (!EIA) continue; Out << 'X'; mangleExpression(EIA->getCond()); Out << 'E'; } Out << 'E'; FunctionTypeDepth.pop(Saved); } // Whether the mangling of a function type includes the return type depends on // the context and the nature of the function. The rules for deciding whether // the return type is included are: // // 1. Template functions (names or types) have return types encoded, with // the exceptions listed below. // 2. Function types not appearing as part of a function name mangling, // e.g. parameters, pointer types, etc., have return type encoded, with the // exceptions listed below. // 3. Non-template function names do not have return types encoded. // // The exceptions mentioned in (1) and (2) above, for which the return type is // never included, are // 1. Constructors. // 2. Destructors. // 3. Conversion operator functions, e.g. operator int. bool MangleReturnType = false; if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) { if (!(isa(FD) || isa(FD) || isa(FD))) MangleReturnType = true; // Mangle the type of the primary template. FD = PrimaryTemplate->getTemplatedDecl(); } mangleBareFunctionType(FD->getType()->getAs(), MangleReturnType, FD); } static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) { while (isa(DC)) { DC = getEffectiveParentContext(DC); } return DC; } /// Return whether a given namespace is the 'std' namespace. static bool isStd(const NamespaceDecl *NS) { if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS)) ->isTranslationUnit()) return false; const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier(); return II && II->isStr("std"); } // isStdNamespace - Return whether a given decl context is a toplevel 'std' // namespace. static bool isStdNamespace(const DeclContext *DC) { if (!DC->isNamespace()) return false; return isStd(cast(DC)); } 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 CXXNameMangler::mangleName(const NamedDecl *ND) { // ::= // ::= // ::= // ::= // const DeclContext *DC = getEffectiveDeclContext(ND); // If this is an extern variable declared locally, the relevant DeclContext // is that of the containing namespace, or the translation unit. // FIXME: This is a hack; extern variables declared locally should have // a proper semantic declaration context! if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND)) while (!DC->isNamespace() && !DC->isTranslationUnit()) DC = getEffectiveParentContext(DC); else if (GetLocalClassDecl(ND)) { mangleLocalName(ND); return; } DC = IgnoreLinkageSpecDecls(DC); if (DC->isTranslationUnit() || isStdNamespace(DC)) { // Check if we have a template. const TemplateArgumentList *TemplateArgs = nullptr; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { mangleUnscopedTemplateName(TD); mangleTemplateArgs(*TemplateArgs); return; } mangleUnscopedName(ND); return; } if (isLocalContainerContext(DC)) { mangleLocalName(ND); return; } mangleNestedName(ND, DC); } void CXXNameMangler::mangleName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD)); if (DC->isTranslationUnit() || isStdNamespace(DC)) { mangleUnscopedTemplateName(TD); mangleTemplateArgs(TemplateArgs, NumTemplateArgs); } else { mangleNestedName(TD, TemplateArgs, NumTemplateArgs); } } void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) { // ::= // ::= St # ::std:: if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND)))) Out << "St"; mangleUnqualifiedName(ND); } void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) { // ::= // ::= if (mangleSubstitution(ND)) return; // ::= if (const auto *TTP = dyn_cast(ND)) mangleTemplateParameter(TTP->getIndex()); else mangleUnscopedName(ND->getTemplatedDecl()); addSubstitution(ND); } void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) { // ::= // ::= if (TemplateDecl *TD = Template.getAsTemplateDecl()) return mangleUnscopedTemplateName(TD); if (mangleSubstitution(Template)) return; DependentTemplateName *Dependent = Template.getAsDependentTemplateName(); assert(Dependent && "Not a dependent template name?"); if (const IdentifierInfo *Id = Dependent->getIdentifier()) mangleSourceName(Id); else mangleOperatorName(Dependent->getOperator(), UnknownArity); addSubstitution(Template); } void CXXNameMangler::mangleFloat(const llvm::APFloat &f) { // ABI: // Floating-point literals are encoded using a fixed-length // lowercase hexadecimal string corresponding to the internal // representation (IEEE on Itanium), high-order bytes first, // without leading zeroes. For example: "Lf bf800000 E" is -1.0f // on Itanium. // The 'without leading zeroes' thing seems to be an editorial // mistake; see the discussion on cxx-abi-dev beginning on // 2012-01-16. // Our requirements here are just barely weird enough to justify // using a custom algorithm instead of post-processing APInt::toString(). llvm::APInt valueBits = f.bitcastToAPInt(); unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4; assert(numCharacters != 0); // Allocate a buffer of the right number of characters. SmallVector buffer(numCharacters); // Fill the buffer left-to-right. for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) { // The bit-index of the next hex digit. unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1); // Project out 4 bits starting at 'digitIndex'. llvm::integerPart hexDigit = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth]; hexDigit >>= (digitBitIndex % llvm::integerPartWidth); hexDigit &= 0xF; // Map that over to a lowercase hex digit. 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::mangleNumber(const llvm::APSInt &Value) { if (Value.isSigned() && Value.isNegative()) { Out << 'n'; Value.abs().print(Out, /*signed*/ false); } else { Value.print(Out, /*signed*/ false); } } void CXXNameMangler::mangleNumber(int64_t Number) { // ::= [n] if (Number < 0) { Out << 'n'; Number = -Number; } Out << Number; } void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) { // ::= h _ // ::= v _ // ::= # non-virtual base override // ::= _ // # virtual base override, with vcall offset 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()) { if (!mangleSubstitution(QualType(TST, 0))) { mangleTemplatePrefix(TST->getTemplateName()); // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? mangleTemplateArgs(TST->getArgs(), TST->getNumArgs()); addSubstitution(QualType(TST, 0)); } } else if (const auto *DTST = type->getAs()) { if (!mangleSubstitution(QualType(DTST, 0))) { TemplateName Template = getASTContext().getDependentTemplateName( DTST->getQualifier(), DTST->getIdentifier()); mangleTemplatePrefix(Template); // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs()); addSubstitution(QualType(DTST, 0)); } } else { // We use the QualType mangle type variant here because it handles // substitutions. mangleType(type); } } /// Mangle everything prior to the base-unresolved-name in an unresolved-name. /// /// \param recursive - true if this is being called recursively, /// i.e. if there is more prefix "to the right". void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, bool recursive) { // x, ::x // ::= [gs] // T::x / decltype(p)::x // ::= sr // T::N::x /decltype(p)::N::x // ::= srN + E // // A::x, N::y, A::z; "gs" means leading "::" // ::= [gs] sr + E // switch (qualifier->getKind()) { case NestedNameSpecifier::Global: Out << "gs"; // We want an 'sr' unless this is the entire NNS. if (recursive) Out << "sr"; // We never want an 'E' here. return; case NestedNameSpecifier::Super: llvm_unreachable("Can't mangle __super specifier"); case NestedNameSpecifier::Namespace: if (qualifier->getPrefix()) mangleUnresolvedPrefix(qualifier->getPrefix(), /*recursive*/ true); else Out << "sr"; mangleSourceName(qualifier->getAsNamespace()->getIdentifier()); break; case NestedNameSpecifier::NamespaceAlias: if (qualifier->getPrefix()) mangleUnresolvedPrefix(qualifier->getPrefix(), /*recursive*/ true); else Out << "sr"; mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier()); break; case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { const Type *type = qualifier->getAsType(); // We only want to use an unresolved-type encoding if this is one of: // - a decltype // - a template type parameter // - a template template parameter with arguments // In all of these cases, we should have no prefix. if (qualifier->getPrefix()) { mangleUnresolvedPrefix(qualifier->getPrefix(), /*recursive*/ true); } else { // Otherwise, all the cases want this. Out << "sr"; } if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : "")) return; break; } case NestedNameSpecifier::Identifier: // Member expressions can have these without prefixes. if (qualifier->getPrefix()) mangleUnresolvedPrefix(qualifier->getPrefix(), /*recursive*/ true); else Out << "sr"; mangleSourceName(qualifier->getAsIdentifier()); break; } // If this was the innermost part of the NNS, and we fell out to // here, append an 'E'. if (!recursive) Out << 'E'; } /// Mangle an unresolved-name, which is generally used for names which /// weren't resolved to specific entities. void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier, DeclarationName name, unsigned knownArity) { if (qualifier) mangleUnresolvedPrefix(qualifier); switch (name.getNameKind()) { // ::= case DeclarationName::Identifier: mangleSourceName(name.getAsIdentifierInfo()); break; // ::= dn case DeclarationName::CXXDestructorName: Out << "dn"; mangleUnresolvedTypeOrSimpleId(name.getCXXNameType()); break; // ::= on 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::ObjCMultiArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCZeroArgSelector: llvm_unreachable("Can't mangle Objective-C selector names here!"); } } void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name, unsigned KnownArity) { unsigned Arity = KnownArity; // ::= // ::= // ::= switch (Name.getNameKind()) { case DeclarationName::Identifier: { if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { // We must avoid conflicts between internally- and externally- // linked variable and function declaration names in the same TU: // void test() { extern void foo(); } // static void foo(); // This naming convention is the same as that followed by GCC, // though it shouldn't actually matter. if (ND && ND->getFormalLinkage() == InternalLinkage && getEffectiveDeclContext(ND)->isFileContext()) Out << 'L'; mangleSourceName(II); 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()) { // This is how gcc mangles these names. Out << "12_GLOBAL__N_1"; break; } } if (const VarDecl *VD = dyn_cast(ND)) { // We must have an anonymous union or struct declaration. const RecordDecl *RD = cast(VD->getType()->getAs()->getDecl()); // Itanium C++ ABI 5.1.2: // // For the purposes of mangling, the name of an anonymous union is // considered to be the name of the first named data member found by a // pre-order, depth-first, declaration-order walk of the data members of // the anonymous union. If there is no such data member (i.e., if all of // the data members in the union are unnamed), then there is no way for // a program to refer to the anonymous union, and there is therefore no // need to mangle its name. assert(RD->isAnonymousStructOrUnion() && "Expected anonymous struct or union!"); const FieldDecl *FD = RD->findFirstNamedDataMember(); // It's actually possible for various reasons for us to get here // with an empty anonymous struct / union. Fortunately, it // doesn't really matter what name we generate. if (!FD) break; assert(FD->getIdentifier() && "Data member name isn't an identifier!"); mangleSourceName(FD->getIdentifier()); break; } // Class extensions have no name as a category, and it's possible // for them to be the semantic parent of certain declarations // (primarily, tag decls defined within declarations). Such // declarations will always have internal linkage, so the name // doesn't really matter, but we shouldn't crash on them. For // safety, just handle all ObjC containers here. if (isa(ND)) 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()); break; } // ::= // // ::= Ul E [ ] _ // ::= + # Parameter types or 'v' for 'void'. if (const CXXRecordDecl *Record = dyn_cast(TD)) { if (Record->isLambda() && Record->getLambdaManglingNumber()) { mangleLambda(Record); break; } } if (TD->isExternallyVisible()) { unsigned UnnamedMangle = getASTContext().getManglingNumber(TD); Out << "Ut"; if (UnnamedMangle > 1) Out << UnnamedMangle - 2; Out << '_'; break; } // Get a unique id for the anonymous struct. unsigned AnonStructId = Context.getAnonymousStructId(TD); // Mangle it as a source name in the form // [n] $_ // where n is the length of the string. 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: if (ND == Structor) // If the named decl is the C++ constructor we're mangling, use the type // we were given. mangleCXXCtorType(static_cast(StructorType)); else // Otherwise, use the complete constructor name. This is relevant if a // class with a constructor is declared within a constructor. mangleCXXCtorType(Ctor_Complete); break; 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 complete destructor name. This is relevant if a // class with a destructor is declared within a destructor. mangleCXXDtorType(Dtor_Complete); break; case DeclarationName::CXXOperatorName: if (ND && Arity == UnknownArity) { Arity = cast(ND)->getNumParams(); // If we have a member function, we need to include the 'this' pointer. if (const auto *MD = dyn_cast(ND)) if (!MD->isStatic()) Arity++; } // FALLTHROUGH case DeclarationName::CXXConversionFunctionName: case DeclarationName::CXXLiteralOperatorName: mangleOperatorName(Name, Arity); break; case DeclarationName::CXXUsingDirective: llvm_unreachable("Can't mangle a using directive name!"); } } void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) { // ::= // ::= [n] // ::= Out << II->getLength() << II->getName(); } void CXXNameMangler::mangleNestedName(const NamedDecl *ND, const DeclContext *DC, bool NoFunction) { // // ::= N [] [] E // ::= N [] [] // E Out << 'N'; if (const CXXMethodDecl *Method = dyn_cast(ND)) { Qualifiers MethodQuals = Qualifiers::fromCVRMask(Method->getTypeQualifiers()); // We do not consider restrict a distinguishing attribute for overloading // purposes so we must not mangle it. MethodQuals.removeRestrict(); mangleQualifiers(MethodQuals); mangleRefQualifier(Method->getRefQualifier()); } // Check if we have a template. const TemplateArgumentList *TemplateArgs = nullptr; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { mangleTemplatePrefix(TD, NoFunction); mangleTemplateArgs(*TemplateArgs); } else { manglePrefix(DC, NoFunction); mangleUnqualifiedName(ND); } Out << 'E'; } void CXXNameMangler::mangleNestedName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { // ::= N [] E Out << 'N'; mangleTemplatePrefix(TD); mangleTemplateArgs(TemplateArgs, NumTemplateArgs); Out << 'E'; } void CXXNameMangler::mangleLocalName(const Decl *D) { // := Z E [] // := Z E s [] // := Z E d [ ] // _ // := _ assert(isa(D) || isa(D)); const RecordDecl *RD = GetLocalClassDecl(D); const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D); Out << 'Z'; if (const ObjCMethodDecl *MD = dyn_cast(DC)) mangleObjCMethodName(MD); else if (const BlockDecl *BD = dyn_cast(DC)) mangleBlockForPrefix(BD); else mangleFunctionEncoding(cast(DC)); Out << 'E'; if (RD) { // The parameter number is omitted for the last parameter, 0 for the // second-to-last parameter, 1 for the third-to-last parameter, etc. The // will of course contain a : Its // numbering will be local to the particular argument in which it appears // -- other default arguments do not affect its encoding. const CXXRecordDecl *CXXRD = dyn_cast(RD); if (CXXRD->isLambda()) { if (const ParmVarDecl *Parm = dyn_cast_or_null(CXXRD->getLambdaContextDecl())) { if (const FunctionDecl *Func = dyn_cast(Parm->getDeclContext())) { Out << 'd'; unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); if (Num > 1) mangleNumber(Num - 2); Out << '_'; } } } // Mangle the name relative to the closest enclosing function. // equality ok because RD derived from ND above if (D == RD) { mangleUnqualifiedName(RD); } else if (const BlockDecl *BD = dyn_cast(D)) { manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/); mangleUnqualifiedBlock(BD); } else { const NamedDecl *ND = cast(D); mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/); } } else if (const BlockDecl *BD = dyn_cast(D)) { // Mangle a block in a default parameter; see above explanation for // lambdas. if (const ParmVarDecl *Parm = dyn_cast_or_null(BD->getBlockManglingContextDecl())) { if (const FunctionDecl *Func = dyn_cast(Parm->getDeclContext())) { Out << 'd'; unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); if (Num > 1) mangleNumber(Num - 2); Out << '_'; } } mangleUnqualifiedBlock(BD); } else { mangleUnqualifiedName(cast(D)); } if (const NamedDecl *ND = dyn_cast(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); return; } const DeclContext *DC = getEffectiveDeclContext(Block); if (isLocalContainerContext(DC)) { mangleLocalName(Block); return; } manglePrefix(getEffectiveDeclContext(Block)); mangleUnqualifiedBlock(Block); } void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) { if (Decl *Context = Block->getBlockManglingContextDecl()) { if ((isa(Context) || isa(Context)) && Context->getDeclContext()->isRecord()) { if (const IdentifierInfo *Name = cast(Context)->getIdentifier()) { mangleSourceName(Name); Out << 'M'; } } } // If we have a block mangling number, use it. unsigned Number = Block->getBlockManglingNumber(); // Otherwise, just make up a number. It doesn't matter what it is because // the symbol in question isn't externally visible. if (!Number) Number = Context.getBlockId(Block, false); Out << "Ub"; if (Number > 0) Out << Number - 1; Out << '_'; } void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { // If the context of a closure type is an initializer for a class member // (static or nonstatic), it is encoded in a qualified name with a final // of the form: // // := M // // Technically, the data-member-prefix is part of the . However, // since a closure type will always be mangled with a prefix, it's easier // to emit that last part of the prefix here. if (Decl *Context = Lambda->getLambdaContextDecl()) { if ((isa(Context) || isa(Context)) && Context->getDeclContext()->isRecord()) { if (const IdentifierInfo *Name = cast(Context)->getIdentifier()) { mangleSourceName(Name); Out << 'M'; } } } Out << "Ul"; const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()-> getAs(); mangleBareFunctionType(Proto, /*MangleReturnType=*/false, Lambda->getLambdaStaticInvoker()); Out << "E"; // The number is omitted for the first closure type with a given // in a given context; it is n-2 for the nth closure type // (in lexical order) with that same and context. // // The AST keeps track of the number for us. unsigned Number = Lambda->getLambdaManglingNumber(); assert(Number > 0 && "Lambda should be mangled as an unnamed class"); if (Number > 1) mangleNumber(Number - 2); Out << '_'; } void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) { switch (qualifier->getKind()) { case NestedNameSpecifier::Global: // nothing 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: // Member expressions can have these without prefixes, but that // should end up in mangleUnresolvedPrefix instead. assert(qualifier->getPrefix()); manglePrefix(qualifier->getPrefix()); mangleSourceName(qualifier->getAsIdentifier()); return; } llvm_unreachable("unexpected nested name specifier"); } void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) { // ::= // ::= // ::= // ::= # empty // ::= DC = IgnoreLinkageSpecDecls(DC); if (DC->isTranslationUnit()) return; if (NoFunction && isLocalContainerContext(DC)) return; assert(!isLocalContainerContext(DC)); const NamedDecl *ND = cast(DC); if (mangleSubstitution(ND)) return; // Check if we have a template. const TemplateArgumentList *TemplateArgs = nullptr; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { mangleTemplatePrefix(TD); mangleTemplateArgs(*TemplateArgs); } else { manglePrefix(getEffectiveDeclContext(ND), NoFunction); mangleUnqualifiedName(ND); } addSubstitution(ND); } void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) { // ::=