Home | History | Annotate | Line # | Download | only in AST
      1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 // Implements C++ name mangling according to the Itanium C++ ABI,
     10 // which is used in GCC 3.2 and newer (and many compilers that are
     11 // ABI-compatible with GCC):
     12 //
     13 //   http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
     14 //
     15 //===----------------------------------------------------------------------===//
     16 
     17 #include "clang/AST/ASTContext.h"
     18 #include "clang/AST/Attr.h"
     19 #include "clang/AST/Decl.h"
     20 #include "clang/AST/DeclCXX.h"
     21 #include "clang/AST/DeclObjC.h"
     22 #include "clang/AST/DeclOpenMP.h"
     23 #include "clang/AST/DeclTemplate.h"
     24 #include "clang/AST/Expr.h"
     25 #include "clang/AST/ExprCXX.h"
     26 #include "clang/AST/ExprConcepts.h"
     27 #include "clang/AST/ExprObjC.h"
     28 #include "clang/AST/Mangle.h"
     29 #include "clang/AST/TypeLoc.h"
     30 #include "clang/Basic/ABI.h"
     31 #include "clang/Basic/Module.h"
     32 #include "clang/Basic/SourceManager.h"
     33 #include "clang/Basic/TargetInfo.h"
     34 #include "clang/Basic/Thunk.h"
     35 #include "llvm/ADT/StringExtras.h"
     36 #include "llvm/Support/ErrorHandling.h"
     37 #include "llvm/Support/raw_ostream.h"
     38 
     39 using namespace clang;
     40 
     41 namespace {
     42 
     43 /// Retrieve the declaration context that should be used when mangling the given
     44 /// declaration.
     45 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
     46   // The ABI assumes that lambda closure types that occur within
     47   // default arguments live in the context of the function. However, due to
     48   // the way in which Clang parses and creates function declarations, this is
     49   // not the case: the lambda closure type ends up living in the context
     50   // where the function itself resides, because the function declaration itself
     51   // had not yet been created. Fix the context here.
     52   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
     53     if (RD->isLambda())
     54       if (ParmVarDecl *ContextParam
     55             = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
     56         return ContextParam->getDeclContext();
     57   }
     58 
     59   // Perform the same check for block literals.
     60   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
     61     if (ParmVarDecl *ContextParam
     62           = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
     63       return ContextParam->getDeclContext();
     64   }
     65 
     66   const DeclContext *DC = D->getDeclContext();
     67   if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
     68       isa<OMPDeclareMapperDecl>(DC)) {
     69     return getEffectiveDeclContext(cast<Decl>(DC));
     70   }
     71 
     72   if (const auto *VD = dyn_cast<VarDecl>(D))
     73     if (VD->isExternC())
     74       return VD->getASTContext().getTranslationUnitDecl();
     75 
     76   if (const auto *FD = dyn_cast<FunctionDecl>(D))
     77     if (FD->isExternC())
     78       return FD->getASTContext().getTranslationUnitDecl();
     79 
     80   return DC->getRedeclContext();
     81 }
     82 
     83 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
     84   return getEffectiveDeclContext(cast<Decl>(DC));
     85 }
     86 
     87 static bool isLocalContainerContext(const DeclContext *DC) {
     88   return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
     89 }
     90 
     91 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
     92   const DeclContext *DC = getEffectiveDeclContext(D);
     93   while (!DC->isNamespace() && !DC->isTranslationUnit()) {
     94     if (isLocalContainerContext(DC))
     95       return dyn_cast<RecordDecl>(D);
     96     D = cast<Decl>(DC);
     97     DC = getEffectiveDeclContext(D);
     98   }
     99   return nullptr;
    100 }
    101 
    102 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
    103   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
    104     return ftd->getTemplatedDecl();
    105 
    106   return fn;
    107 }
    108 
    109 static const NamedDecl *getStructor(const NamedDecl *decl) {
    110   const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
    111   return (fn ? getStructor(fn) : decl);
    112 }
    113 
    114 static bool isLambda(const NamedDecl *ND) {
    115   const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
    116   if (!Record)
    117     return false;
    118 
    119   return Record->isLambda();
    120 }
    121 
    122 static const unsigned UnknownArity = ~0U;
    123 
    124 class ItaniumMangleContextImpl : public ItaniumMangleContext {
    125   typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
    126   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
    127   llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
    128 
    129   bool IsDevCtx = false;
    130   bool NeedsUniqueInternalLinkageNames = false;
    131 
    132 public:
    133   explicit ItaniumMangleContextImpl(ASTContext &Context,
    134                                     DiagnosticsEngine &Diags)
    135       : ItaniumMangleContext(Context, Diags) {}
    136 
    137   /// @name Mangler Entry Points
    138   /// @{
    139 
    140   bool shouldMangleCXXName(const NamedDecl *D) override;
    141   bool shouldMangleStringLiteral(const StringLiteral *) override {
    142     return false;
    143   }
    144 
    145   bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
    146   void needsUniqueInternalLinkageNames() override {
    147     NeedsUniqueInternalLinkageNames = true;
    148   }
    149 
    150   bool isDeviceMangleContext() const override { return IsDevCtx; }
    151   void setDeviceMangleContext(bool IsDev) override { IsDevCtx = IsDev; }
    152 
    153   void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
    154   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
    155                    raw_ostream &) override;
    156   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
    157                           const ThisAdjustment &ThisAdjustment,
    158                           raw_ostream &) override;
    159   void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
    160                                 raw_ostream &) override;
    161   void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
    162   void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
    163   void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
    164                            const CXXRecordDecl *Type, raw_ostream &) override;
    165   void mangleCXXRTTI(QualType T, raw_ostream &) override;
    166   void mangleCXXRTTIName(QualType T, raw_ostream &) override;
    167   void mangleTypeName(QualType T, raw_ostream &) override;
    168 
    169   void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
    170   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
    171   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
    172   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
    173   void mangleDynamicAtExitDestructor(const VarDecl *D,
    174                                      raw_ostream &Out) override;
    175   void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
    176   void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
    177                                  raw_ostream &Out) override;
    178   void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
    179                              raw_ostream &Out) override;
    180   void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
    181   void mangleItaniumThreadLocalWrapper(const VarDecl *D,
    182                                        raw_ostream &) override;
    183 
    184   void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
    185 
    186   void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
    187 
    188   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
    189     // Lambda closure types are already numbered.
    190     if (isLambda(ND))
    191       return false;
    192 
    193     // Anonymous tags are already numbered.
    194     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
    195       if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
    196         return false;
    197     }
    198 
    199     // Use the canonical number for externally visible decls.
    200     if (ND->isExternallyVisible()) {
    201       unsigned discriminator = getASTContext().getManglingNumber(ND);
    202       if (discriminator == 1)
    203         return false;
    204       disc = discriminator - 2;
    205       return true;
    206     }
    207 
    208     // Make up a reasonable number for internal decls.
    209     unsigned &discriminator = Uniquifier[ND];
    210     if (!discriminator) {
    211       const DeclContext *DC = getEffectiveDeclContext(ND);
    212       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
    213     }
    214     if (discriminator == 1)
    215       return false;
    216     disc = discriminator-2;
    217     return true;
    218   }
    219 
    220   std::string getLambdaString(const CXXRecordDecl *Lambda) override {
    221     // This function matches the one in MicrosoftMangle, which returns
    222     // the string that is used in lambda mangled names.
    223     assert(Lambda->isLambda() && "RD must be a lambda!");
    224     std::string Name("<lambda");
    225     Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
    226     unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
    227     unsigned LambdaId;
    228     const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
    229     const FunctionDecl *Func =
    230         Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
    231 
    232     if (Func) {
    233       unsigned DefaultArgNo =
    234           Func->getNumParams() - Parm->getFunctionScopeIndex();
    235       Name += llvm::utostr(DefaultArgNo);
    236       Name += "_";
    237     }
    238 
    239     if (LambdaManglingNumber)
    240       LambdaId = LambdaManglingNumber;
    241     else
    242       LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
    243 
    244     Name += llvm::utostr(LambdaId);
    245     Name += '>';
    246     return Name;
    247   }
    248 
    249   /// @}
    250 };
    251 
    252 /// Manage the mangling of a single name.
    253 class CXXNameMangler {
    254   ItaniumMangleContextImpl &Context;
    255   raw_ostream &Out;
    256   bool NullOut = false;
    257   /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
    258   /// This mode is used when mangler creates another mangler recursively to
    259   /// calculate ABI tags for the function return value or the variable type.
    260   /// Also it is required to avoid infinite recursion in some cases.
    261   bool DisableDerivedAbiTags = false;
    262 
    263   /// The "structor" is the top-level declaration being mangled, if
    264   /// that's not a template specialization; otherwise it's the pattern
    265   /// for that specialization.
    266   const NamedDecl *Structor;
    267   unsigned StructorType;
    268 
    269   /// The next substitution sequence number.
    270   unsigned SeqID;
    271 
    272   class FunctionTypeDepthState {
    273     unsigned Bits;
    274 
    275     enum { InResultTypeMask = 1 };
    276 
    277   public:
    278     FunctionTypeDepthState() : Bits(0) {}
    279 
    280     /// The number of function types we're inside.
    281     unsigned getDepth() const {
    282       return Bits >> 1;
    283     }
    284 
    285     /// True if we're in the return type of the innermost function type.
    286     bool isInResultType() const {
    287       return Bits & InResultTypeMask;
    288     }
    289 
    290     FunctionTypeDepthState push() {
    291       FunctionTypeDepthState tmp = *this;
    292       Bits = (Bits & ~InResultTypeMask) + 2;
    293       return tmp;
    294     }
    295 
    296     void enterResultType() {
    297       Bits |= InResultTypeMask;
    298     }
    299 
    300     void leaveResultType() {
    301       Bits &= ~InResultTypeMask;
    302     }
    303 
    304     void pop(FunctionTypeDepthState saved) {
    305       assert(getDepth() == saved.getDepth() + 1);
    306       Bits = saved.Bits;
    307     }
    308 
    309   } FunctionTypeDepth;
    310 
    311   // abi_tag is a gcc attribute, taking one or more strings called "tags".
    312   // The goal is to annotate against which version of a library an object was
    313   // built and to be able to provide backwards compatibility ("dual abi").
    314   // For more information see docs/ItaniumMangleAbiTags.rst.
    315   typedef SmallVector<StringRef, 4> AbiTagList;
    316 
    317   // State to gather all implicit and explicit tags used in a mangled name.
    318   // Must always have an instance of this while emitting any name to keep
    319   // track.
    320   class AbiTagState final {
    321   public:
    322     explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
    323       Parent = LinkHead;
    324       LinkHead = this;
    325     }
    326 
    327     // No copy, no move.
    328     AbiTagState(const AbiTagState &) = delete;
    329     AbiTagState &operator=(const AbiTagState &) = delete;
    330 
    331     ~AbiTagState() { pop(); }
    332 
    333     void write(raw_ostream &Out, const NamedDecl *ND,
    334                const AbiTagList *AdditionalAbiTags) {
    335       ND = cast<NamedDecl>(ND->getCanonicalDecl());
    336       if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
    337         assert(
    338             !AdditionalAbiTags &&
    339             "only function and variables need a list of additional abi tags");
    340         if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
    341           if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
    342             UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
    343                                AbiTag->tags().end());
    344           }
    345           // Don't emit abi tags for namespaces.
    346           return;
    347         }
    348       }
    349 
    350       AbiTagList TagList;
    351       if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
    352         UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
    353                            AbiTag->tags().end());
    354         TagList.insert(TagList.end(), AbiTag->tags().begin(),
    355                        AbiTag->tags().end());
    356       }
    357 
    358       if (AdditionalAbiTags) {
    359         UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
    360                            AdditionalAbiTags->end());
    361         TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
    362                        AdditionalAbiTags->end());
    363       }
    364 
    365       llvm::sort(TagList);
    366       TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
    367 
    368       writeSortedUniqueAbiTags(Out, TagList);
    369     }
    370 
    371     const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
    372     void setUsedAbiTags(const AbiTagList &AbiTags) {
    373       UsedAbiTags = AbiTags;
    374     }
    375 
    376     const AbiTagList &getEmittedAbiTags() const {
    377       return EmittedAbiTags;
    378     }
    379 
    380     const AbiTagList &getSortedUniqueUsedAbiTags() {
    381       llvm::sort(UsedAbiTags);
    382       UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
    383                         UsedAbiTags.end());
    384       return UsedAbiTags;
    385     }
    386 
    387   private:
    388     //! All abi tags used implicitly or explicitly.
    389     AbiTagList UsedAbiTags;
    390     //! All explicit abi tags (i.e. not from namespace).
    391     AbiTagList EmittedAbiTags;
    392 
    393     AbiTagState *&LinkHead;
    394     AbiTagState *Parent = nullptr;
    395 
    396     void pop() {
    397       assert(LinkHead == this &&
    398              "abi tag link head must point to us on destruction");
    399       if (Parent) {
    400         Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
    401                                    UsedAbiTags.begin(), UsedAbiTags.end());
    402         Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
    403                                       EmittedAbiTags.begin(),
    404                                       EmittedAbiTags.end());
    405       }
    406       LinkHead = Parent;
    407     }
    408 
    409     void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
    410       for (const auto &Tag : AbiTags) {
    411         EmittedAbiTags.push_back(Tag);
    412         Out << "B";
    413         Out << Tag.size();
    414         Out << Tag;
    415       }
    416     }
    417   };
    418 
    419   AbiTagState *AbiTags = nullptr;
    420   AbiTagState AbiTagsRoot;
    421 
    422   llvm::DenseMap<uintptr_t, unsigned> Substitutions;
    423   llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
    424 
    425   ASTContext &getASTContext() const { return Context.getASTContext(); }
    426 
    427 public:
    428   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
    429                  const NamedDecl *D = nullptr, bool NullOut_ = false)
    430     : Context(C), Out(Out_), NullOut(NullOut_),  Structor(getStructor(D)),
    431       StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
    432     // These can't be mangled without a ctor type or dtor type.
    433     assert(!D || (!isa<CXXDestructorDecl>(D) &&
    434                   !isa<CXXConstructorDecl>(D)));
    435   }
    436   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
    437                  const CXXConstructorDecl *D, CXXCtorType Type)
    438     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
    439       SeqID(0), AbiTagsRoot(AbiTags) { }
    440   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
    441                  const CXXDestructorDecl *D, CXXDtorType Type)
    442     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
    443       SeqID(0), AbiTagsRoot(AbiTags) { }
    444 
    445   CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
    446       : Context(Outer.Context), Out(Out_), NullOut(false),
    447         Structor(Outer.Structor), StructorType(Outer.StructorType),
    448         SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
    449         AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
    450 
    451   CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
    452       : Context(Outer.Context), Out(Out_), NullOut(true),
    453         Structor(Outer.Structor), StructorType(Outer.StructorType),
    454         SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
    455         AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
    456 
    457   raw_ostream &getStream() { return Out; }
    458 
    459   void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
    460   static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
    461 
    462   void mangle(GlobalDecl GD);
    463   void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
    464   void mangleNumber(const llvm::APSInt &I);
    465   void mangleNumber(int64_t Number);
    466   void mangleFloat(const llvm::APFloat &F);
    467   void mangleFunctionEncoding(GlobalDecl GD);
    468   void mangleSeqID(unsigned SeqID);
    469   void mangleName(GlobalDecl GD);
    470   void mangleType(QualType T);
    471   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
    472   void mangleLambdaSig(const CXXRecordDecl *Lambda);
    473 
    474 private:
    475 
    476   bool mangleSubstitution(const NamedDecl *ND);
    477   bool mangleSubstitution(QualType T);
    478   bool mangleSubstitution(TemplateName Template);
    479   bool mangleSubstitution(uintptr_t Ptr);
    480 
    481   void mangleExistingSubstitution(TemplateName name);
    482 
    483   bool mangleStandardSubstitution(const NamedDecl *ND);
    484 
    485   void addSubstitution(const NamedDecl *ND) {
    486     ND = cast<NamedDecl>(ND->getCanonicalDecl());
    487 
    488     addSubstitution(reinterpret_cast<uintptr_t>(ND));
    489   }
    490   void addSubstitution(QualType T);
    491   void addSubstitution(TemplateName Template);
    492   void addSubstitution(uintptr_t Ptr);
    493   // Destructive copy substitutions from other mangler.
    494   void extendSubstitutions(CXXNameMangler* Other);
    495 
    496   void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
    497                               bool recursive = false);
    498   void mangleUnresolvedName(NestedNameSpecifier *qualifier,
    499                             DeclarationName name,
    500                             const TemplateArgumentLoc *TemplateArgs,
    501                             unsigned NumTemplateArgs,
    502                             unsigned KnownArity = UnknownArity);
    503 
    504   void mangleFunctionEncodingBareType(const FunctionDecl *FD);
    505 
    506   void mangleNameWithAbiTags(GlobalDecl GD,
    507                              const AbiTagList *AdditionalAbiTags);
    508   void mangleModuleName(const Module *M);
    509   void mangleModuleNamePrefix(StringRef Name);
    510   void mangleTemplateName(const TemplateDecl *TD,
    511                           const TemplateArgument *TemplateArgs,
    512                           unsigned NumTemplateArgs);
    513   void mangleUnqualifiedName(GlobalDecl GD,
    514                              const AbiTagList *AdditionalAbiTags) {
    515     mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), UnknownArity,
    516                           AdditionalAbiTags);
    517   }
    518   void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
    519                              unsigned KnownArity,
    520                              const AbiTagList *AdditionalAbiTags);
    521   void mangleUnscopedName(GlobalDecl GD,
    522                           const AbiTagList *AdditionalAbiTags);
    523   void mangleUnscopedTemplateName(GlobalDecl GD,
    524                                   const AbiTagList *AdditionalAbiTags);
    525   void mangleSourceName(const IdentifierInfo *II);
    526   void mangleRegCallName(const IdentifierInfo *II);
    527   void mangleDeviceStubName(const IdentifierInfo *II);
    528   void mangleSourceNameWithAbiTags(
    529       const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
    530   void mangleLocalName(GlobalDecl GD,
    531                        const AbiTagList *AdditionalAbiTags);
    532   void mangleBlockForPrefix(const BlockDecl *Block);
    533   void mangleUnqualifiedBlock(const BlockDecl *Block);
    534   void mangleTemplateParamDecl(const NamedDecl *Decl);
    535   void mangleLambda(const CXXRecordDecl *Lambda);
    536   void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
    537                         const AbiTagList *AdditionalAbiTags,
    538                         bool NoFunction=false);
    539   void mangleNestedName(const TemplateDecl *TD,
    540                         const TemplateArgument *TemplateArgs,
    541                         unsigned NumTemplateArgs);
    542   void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
    543                                          const NamedDecl *PrefixND,
    544                                          const AbiTagList *AdditionalAbiTags);
    545   void manglePrefix(NestedNameSpecifier *qualifier);
    546   void manglePrefix(const DeclContext *DC, bool NoFunction=false);
    547   void manglePrefix(QualType type);
    548   void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
    549   void mangleTemplatePrefix(TemplateName Template);
    550   const NamedDecl *getClosurePrefix(const Decl *ND);
    551   void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
    552   bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
    553                                       StringRef Prefix = "");
    554   void mangleOperatorName(DeclarationName Name, unsigned Arity);
    555   void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
    556   void mangleVendorQualifier(StringRef qualifier);
    557   void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
    558   void mangleRefQualifier(RefQualifierKind RefQualifier);
    559 
    560   void mangleObjCMethodName(const ObjCMethodDecl *MD);
    561 
    562   // Declare manglers for every type class.
    563 #define ABSTRACT_TYPE(CLASS, PARENT)
    564 #define NON_CANONICAL_TYPE(CLASS, PARENT)
    565 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
    566 #include "clang/AST/TypeNodes.inc"
    567 
    568   void mangleType(const TagType*);
    569   void mangleType(TemplateName);
    570   static StringRef getCallingConvQualifierName(CallingConv CC);
    571   void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
    572   void mangleExtFunctionInfo(const FunctionType *T);
    573   void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
    574                               const FunctionDecl *FD = nullptr);
    575   void mangleNeonVectorType(const VectorType *T);
    576   void mangleNeonVectorType(const DependentVectorType *T);
    577   void mangleAArch64NeonVectorType(const VectorType *T);
    578   void mangleAArch64NeonVectorType(const DependentVectorType *T);
    579   void mangleAArch64FixedSveVectorType(const VectorType *T);
    580   void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
    581 
    582   void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
    583   void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
    584   void mangleFixedPointLiteral();
    585   void mangleNullPointer(QualType T);
    586 
    587   void mangleMemberExprBase(const Expr *base, bool isArrow);
    588   void mangleMemberExpr(const Expr *base, bool isArrow,
    589                         NestedNameSpecifier *qualifier,
    590                         NamedDecl *firstQualifierLookup,
    591                         DeclarationName name,
    592                         const TemplateArgumentLoc *TemplateArgs,
    593                         unsigned NumTemplateArgs,
    594                         unsigned knownArity);
    595   void mangleCastExpression(const Expr *E, StringRef CastEncoding);
    596   void mangleInitListElements(const InitListExpr *InitList);
    597   void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
    598                         bool AsTemplateArg = false);
    599   void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
    600   void mangleCXXDtorType(CXXDtorType T);
    601 
    602   void mangleTemplateArgs(TemplateName TN,
    603                           const TemplateArgumentLoc *TemplateArgs,
    604                           unsigned NumTemplateArgs);
    605   void mangleTemplateArgs(TemplateName TN, const TemplateArgument *TemplateArgs,
    606                           unsigned NumTemplateArgs);
    607   void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
    608   void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
    609   void mangleTemplateArgExpr(const Expr *E);
    610   void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
    611                                 bool NeedExactType = false);
    612 
    613   void mangleTemplateParameter(unsigned Depth, unsigned Index);
    614 
    615   void mangleFunctionParam(const ParmVarDecl *parm);
    616 
    617   void writeAbiTags(const NamedDecl *ND,
    618                     const AbiTagList *AdditionalAbiTags);
    619 
    620   // Returns sorted unique list of ABI tags.
    621   AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
    622   // Returns sorted unique list of ABI tags.
    623   AbiTagList makeVariableTypeTags(const VarDecl *VD);
    624 };
    625 
    626 }
    627 
    628 static bool isInternalLinkageDecl(const NamedDecl *ND) {
    629   if (ND && ND->getFormalLinkage() == InternalLinkage &&
    630       !ND->isExternallyVisible() &&
    631       getEffectiveDeclContext(ND)->isFileContext() &&
    632       !ND->isInAnonymousNamespace())
    633     return true;
    634   return false;
    635 }
    636 
    637 // Check if this Function Decl needs a unique internal linkage name.
    638 bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
    639     const NamedDecl *ND) {
    640   if (!NeedsUniqueInternalLinkageNames || !ND)
    641     return false;
    642 
    643   const auto *FD = dyn_cast<FunctionDecl>(ND);
    644   if (!FD)
    645     return false;
    646 
    647   // For C functions without prototypes, return false as their
    648   // names should not be mangled.
    649   if (!FD->hasPrototype())
    650     return false;
    651 
    652   if (isInternalLinkageDecl(ND))
    653     return true;
    654 
    655   return false;
    656 }
    657 
    658 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
    659   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
    660   if (FD) {
    661     LanguageLinkage L = FD->getLanguageLinkage();
    662     // Overloadable functions need mangling.
    663     if (FD->hasAttr<OverloadableAttr>())
    664       return true;
    665 
    666     // "main" is not mangled.
    667     if (FD->isMain())
    668       return false;
    669 
    670     // The Windows ABI expects that we would never mangle "typical"
    671     // user-defined entry points regardless of visibility or freestanding-ness.
    672     //
    673     // N.B. This is distinct from asking about "main".  "main" has a lot of
    674     // special rules associated with it in the standard while these
    675     // user-defined entry points are outside of the purview of the standard.
    676     // For example, there can be only one definition for "main" in a standards
    677     // compliant program; however nothing forbids the existence of wmain and
    678     // WinMain in the same translation unit.
    679     if (FD->isMSVCRTEntryPoint())
    680       return false;
    681 
    682     // C++ functions and those whose names are not a simple identifier need
    683     // mangling.
    684     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
    685       return true;
    686 
    687     // C functions are not mangled.
    688     if (L == CLanguageLinkage)
    689       return false;
    690   }
    691 
    692   // Otherwise, no mangling is done outside C++ mode.
    693   if (!getASTContext().getLangOpts().CPlusPlus)
    694     return false;
    695 
    696   const VarDecl *VD = dyn_cast<VarDecl>(D);
    697   if (VD && !isa<DecompositionDecl>(D)) {
    698     // C variables are not mangled.
    699     if (VD->isExternC())
    700       return false;
    701 
    702     // Variables at global scope with non-internal linkage are not mangled
    703     const DeclContext *DC = getEffectiveDeclContext(D);
    704     // Check for extern variable declared locally.
    705     if (DC->isFunctionOrMethod() && D->hasLinkage())
    706       while (!DC->isNamespace() && !DC->isTranslationUnit())
    707         DC = getEffectiveParentContext(DC);
    708     if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
    709         !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
    710         !isa<VarTemplateSpecializationDecl>(D))
    711       return false;
    712   }
    713 
    714   return true;
    715 }
    716 
    717 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
    718                                   const AbiTagList *AdditionalAbiTags) {
    719   assert(AbiTags && "require AbiTagState");
    720   AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
    721 }
    722 
    723 void CXXNameMangler::mangleSourceNameWithAbiTags(
    724     const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
    725   mangleSourceName(ND->getIdentifier());
    726   writeAbiTags(ND, AdditionalAbiTags);
    727 }
    728 
    729 void CXXNameMangler::mangle(GlobalDecl GD) {
    730   // <mangled-name> ::= _Z <encoding>
    731   //            ::= <data name>
    732   //            ::= <special-name>
    733   Out << "_Z";
    734   if (isa<FunctionDecl>(GD.getDecl()))
    735     mangleFunctionEncoding(GD);
    736   else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
    737                BindingDecl>(GD.getDecl()))
    738     mangleName(GD);
    739   else if (const IndirectFieldDecl *IFD =
    740                dyn_cast<IndirectFieldDecl>(GD.getDecl()))
    741     mangleName(IFD->getAnonField());
    742   else
    743     llvm_unreachable("unexpected kind of global decl");
    744 }
    745 
    746 void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
    747   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
    748   // <encoding> ::= <function name> <bare-function-type>
    749 
    750   // Don't mangle in the type if this isn't a decl we should typically mangle.
    751   if (!Context.shouldMangleDeclName(FD)) {
    752     mangleName(GD);
    753     return;
    754   }
    755 
    756   AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
    757   if (ReturnTypeAbiTags.empty()) {
    758     // There are no tags for return type, the simplest case.
    759     mangleName(GD);
    760     mangleFunctionEncodingBareType(FD);
    761     return;
    762   }
    763 
    764   // Mangle function name and encoding to temporary buffer.
    765   // We have to output name and encoding to the same mangler to get the same
    766   // substitution as it will be in final mangling.
    767   SmallString<256> FunctionEncodingBuf;
    768   llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
    769   CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
    770   // Output name of the function.
    771   FunctionEncodingMangler.disableDerivedAbiTags();
    772   FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
    773 
    774   // Remember length of the function name in the buffer.
    775   size_t EncodingPositionStart = FunctionEncodingStream.str().size();
    776   FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
    777 
    778   // Get tags from return type that are not present in function name or
    779   // encoding.
    780   const AbiTagList &UsedAbiTags =
    781       FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
    782   AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
    783   AdditionalAbiTags.erase(
    784       std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
    785                           UsedAbiTags.begin(), UsedAbiTags.end(),
    786                           AdditionalAbiTags.begin()),
    787       AdditionalAbiTags.end());
    788 
    789   // Output name with implicit tags and function encoding from temporary buffer.
    790   mangleNameWithAbiTags(FD, &AdditionalAbiTags);
    791   Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
    792 
    793   // Function encoding could create new substitutions so we have to add
    794   // temp mangled substitutions to main mangler.
    795   extendSubstitutions(&FunctionEncodingMangler);
    796 }
    797 
    798 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
    799   if (FD->hasAttr<EnableIfAttr>()) {
    800     FunctionTypeDepthState Saved = FunctionTypeDepth.push();
    801     Out << "Ua9enable_ifI";
    802     for (AttrVec::const_iterator I = FD->getAttrs().begin(),
    803                                  E = FD->getAttrs().end();
    804          I != E; ++I) {
    805       EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
    806       if (!EIA)
    807         continue;
    808       if (Context.getASTContext().getLangOpts().getClangABICompat() >
    809           LangOptions::ClangABI::Ver11) {
    810         mangleTemplateArgExpr(EIA->getCond());
    811       } else {
    812         // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
    813         // even though <template-arg> should not include an X/E around
    814         // <expr-primary>.
    815         Out << 'X';
    816         mangleExpression(EIA->getCond());
    817         Out << 'E';
    818       }
    819     }
    820     Out << 'E';
    821     FunctionTypeDepth.pop(Saved);
    822   }
    823 
    824   // When mangling an inheriting constructor, the bare function type used is
    825   // that of the inherited constructor.
    826   if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
    827     if (auto Inherited = CD->getInheritedConstructor())
    828       FD = Inherited.getConstructor();
    829 
    830   // Whether the mangling of a function type includes the return type depends on
    831   // the context and the nature of the function. The rules for deciding whether
    832   // the return type is included are:
    833   //
    834   //   1. Template functions (names or types) have return types encoded, with
    835   //   the exceptions listed below.
    836   //   2. Function types not appearing as part of a function name mangling,
    837   //   e.g. parameters, pointer types, etc., have return type encoded, with the
    838   //   exceptions listed below.
    839   //   3. Non-template function names do not have return types encoded.
    840   //
    841   // The exceptions mentioned in (1) and (2) above, for which the return type is
    842   // never included, are
    843   //   1. Constructors.
    844   //   2. Destructors.
    845   //   3. Conversion operator functions, e.g. operator int.
    846   bool MangleReturnType = false;
    847   if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
    848     if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
    849           isa<CXXConversionDecl>(FD)))
    850       MangleReturnType = true;
    851 
    852     // Mangle the type of the primary template.
    853     FD = PrimaryTemplate->getTemplatedDecl();
    854   }
    855 
    856   mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
    857                          MangleReturnType, FD);
    858 }
    859 
    860 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
    861   while (isa<LinkageSpecDecl>(DC)) {
    862     DC = getEffectiveParentContext(DC);
    863   }
    864 
    865   return DC;
    866 }
    867 
    868 /// Return whether a given namespace is the 'std' namespace.
    869 static bool isStd(const NamespaceDecl *NS) {
    870   if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
    871                                 ->isTranslationUnit())
    872     return false;
    873 
    874   const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
    875   return II && II->isStr("std");
    876 }
    877 
    878 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
    879 // namespace.
    880 static bool isStdNamespace(const DeclContext *DC) {
    881   if (!DC->isNamespace())
    882     return false;
    883 
    884   return isStd(cast<NamespaceDecl>(DC));
    885 }
    886 
    887 static const GlobalDecl
    888 isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
    889   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
    890   // Check if we have a function template.
    891   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
    892     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
    893       TemplateArgs = FD->getTemplateSpecializationArgs();
    894       return GD.getWithDecl(TD);
    895     }
    896   }
    897 
    898   // Check if we have a class template.
    899   if (const ClassTemplateSpecializationDecl *Spec =
    900         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
    901     TemplateArgs = &Spec->getTemplateArgs();
    902     return GD.getWithDecl(Spec->getSpecializedTemplate());
    903   }
    904 
    905   // Check if we have a variable template.
    906   if (const VarTemplateSpecializationDecl *Spec =
    907           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
    908     TemplateArgs = &Spec->getTemplateArgs();
    909     return GD.getWithDecl(Spec->getSpecializedTemplate());
    910   }
    911 
    912   return GlobalDecl();
    913 }
    914 
    915 static TemplateName asTemplateName(GlobalDecl GD) {
    916   const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
    917   return TemplateName(const_cast<TemplateDecl*>(TD));
    918 }
    919 
    920 void CXXNameMangler::mangleName(GlobalDecl GD) {
    921   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
    922   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
    923     // Variables should have implicit tags from its type.
    924     AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
    925     if (VariableTypeAbiTags.empty()) {
    926       // Simple case no variable type tags.
    927       mangleNameWithAbiTags(VD, nullptr);
    928       return;
    929     }
    930 
    931     // Mangle variable name to null stream to collect tags.
    932     llvm::raw_null_ostream NullOutStream;
    933     CXXNameMangler VariableNameMangler(*this, NullOutStream);
    934     VariableNameMangler.disableDerivedAbiTags();
    935     VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
    936 
    937     // Get tags from variable type that are not present in its name.
    938     const AbiTagList &UsedAbiTags =
    939         VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
    940     AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
    941     AdditionalAbiTags.erase(
    942         std::set_difference(VariableTypeAbiTags.begin(),
    943                             VariableTypeAbiTags.end(), UsedAbiTags.begin(),
    944                             UsedAbiTags.end(), AdditionalAbiTags.begin()),
    945         AdditionalAbiTags.end());
    946 
    947     // Output name with implicit tags.
    948     mangleNameWithAbiTags(VD, &AdditionalAbiTags);
    949   } else {
    950     mangleNameWithAbiTags(GD, nullptr);
    951   }
    952 }
    953 
    954 void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
    955                                            const AbiTagList *AdditionalAbiTags) {
    956   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
    957   //  <name> ::= [<module-name>] <nested-name>
    958   //         ::= [<module-name>] <unscoped-name>
    959   //         ::= [<module-name>] <unscoped-template-name> <template-args>
    960   //         ::= <local-name>
    961   //
    962   const DeclContext *DC = getEffectiveDeclContext(ND);
    963 
    964   // If this is an extern variable declared locally, the relevant DeclContext
    965   // is that of the containing namespace, or the translation unit.
    966   // FIXME: This is a hack; extern variables declared locally should have
    967   // a proper semantic declaration context!
    968   if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
    969     while (!DC->isNamespace() && !DC->isTranslationUnit())
    970       DC = getEffectiveParentContext(DC);
    971   else if (GetLocalClassDecl(ND)) {
    972     mangleLocalName(GD, AdditionalAbiTags);
    973     return;
    974   }
    975 
    976   DC = IgnoreLinkageSpecDecls(DC);
    977 
    978   if (isLocalContainerContext(DC)) {
    979     mangleLocalName(GD, AdditionalAbiTags);
    980     return;
    981   }
    982 
    983   // Do not mangle the owning module for an external linkage declaration.
    984   // This enables backwards-compatibility with non-modular code, and is
    985   // a valid choice since conflicts are not permitted by C++ Modules TS
    986   // [basic.def.odr]/6.2.
    987   if (!ND->hasExternalFormalLinkage())
    988     if (Module *M = ND->getOwningModuleForLinkage())
    989       mangleModuleName(M);
    990 
    991   // Closures can require a nested-name mangling even if they're semantically
    992   // in the global namespace.
    993   if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
    994     mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
    995     return;
    996   }
    997 
    998   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
    999     // Check if we have a template.
   1000     const TemplateArgumentList *TemplateArgs = nullptr;
   1001     if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
   1002       mangleUnscopedTemplateName(TD, AdditionalAbiTags);
   1003       mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
   1004       return;
   1005     }
   1006 
   1007     mangleUnscopedName(GD, AdditionalAbiTags);
   1008     return;
   1009   }
   1010 
   1011   mangleNestedName(GD, DC, AdditionalAbiTags);
   1012 }
   1013 
   1014 void CXXNameMangler::mangleModuleName(const Module *M) {
   1015   // Implement the C++ Modules TS name mangling proposal; see
   1016   //     https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
   1017   //
   1018   //   <module-name> ::= W <unscoped-name>+ E
   1019   //                 ::= W <module-subst> <unscoped-name>* E
   1020   Out << 'W';
   1021   mangleModuleNamePrefix(M->Name);
   1022   Out << 'E';
   1023 }
   1024 
   1025 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
   1026   //  <module-subst> ::= _ <seq-id>          # 0 < seq-id < 10
   1027   //                 ::= W <seq-id - 10> _   # otherwise
   1028   auto It = ModuleSubstitutions.find(Name);
   1029   if (It != ModuleSubstitutions.end()) {
   1030     if (It->second < 10)
   1031       Out << '_' << static_cast<char>('0' + It->second);
   1032     else
   1033       Out << 'W' << (It->second - 10) << '_';
   1034     return;
   1035   }
   1036 
   1037   // FIXME: Preserve hierarchy in module names rather than flattening
   1038   // them to strings; use Module*s as substitution keys.
   1039   auto Parts = Name.rsplit('.');
   1040   if (Parts.second.empty())
   1041     Parts.second = Parts.first;
   1042   else
   1043     mangleModuleNamePrefix(Parts.first);
   1044 
   1045   Out << Parts.second.size() << Parts.second;
   1046   ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
   1047 }
   1048 
   1049 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
   1050                                         const TemplateArgument *TemplateArgs,
   1051                                         unsigned NumTemplateArgs) {
   1052   const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
   1053 
   1054   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
   1055     mangleUnscopedTemplateName(TD, nullptr);
   1056     mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs);
   1057   } else {
   1058     mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
   1059   }
   1060 }
   1061 
   1062 void CXXNameMangler::mangleUnscopedName(GlobalDecl GD,
   1063                                         const AbiTagList *AdditionalAbiTags) {
   1064   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
   1065   //  <unscoped-name> ::= <unqualified-name>
   1066   //                  ::= St <unqualified-name>   # ::std::
   1067 
   1068   if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
   1069     Out << "St";
   1070 
   1071   mangleUnqualifiedName(GD, AdditionalAbiTags);
   1072 }
   1073 
   1074 void CXXNameMangler::mangleUnscopedTemplateName(
   1075     GlobalDecl GD, const AbiTagList *AdditionalAbiTags) {
   1076   const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
   1077   //     <unscoped-template-name> ::= <unscoped-name>
   1078   //                              ::= <substitution>
   1079   if (mangleSubstitution(ND))
   1080     return;
   1081 
   1082   // <template-template-param> ::= <template-param>
   1083   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
   1084     assert(!AdditionalAbiTags &&
   1085            "template template param cannot have abi tags");
   1086     mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
   1087   } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
   1088     mangleUnscopedName(GD, AdditionalAbiTags);
   1089   } else {
   1090     mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), AdditionalAbiTags);
   1091   }
   1092 
   1093   addSubstitution(ND);
   1094 }
   1095 
   1096 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
   1097   // ABI:
   1098   //   Floating-point literals are encoded using a fixed-length
   1099   //   lowercase hexadecimal string corresponding to the internal
   1100   //   representation (IEEE on Itanium), high-order bytes first,
   1101   //   without leading zeroes. For example: "Lf bf800000 E" is -1.0f
   1102   //   on Itanium.
   1103   // The 'without leading zeroes' thing seems to be an editorial
   1104   // mistake; see the discussion on cxx-abi-dev beginning on
   1105   // 2012-01-16.
   1106 
   1107   // Our requirements here are just barely weird enough to justify
   1108   // using a custom algorithm instead of post-processing APInt::toString().
   1109 
   1110   llvm::APInt valueBits = f.bitcastToAPInt();
   1111   unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
   1112   assert(numCharacters != 0);
   1113 
   1114   // Allocate a buffer of the right number of characters.
   1115   SmallVector<char, 20> buffer(numCharacters);
   1116 
   1117   // Fill the buffer left-to-right.
   1118   for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
   1119     // The bit-index of the next hex digit.
   1120     unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
   1121 
   1122     // Project out 4 bits starting at 'digitIndex'.
   1123     uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
   1124     hexDigit >>= (digitBitIndex % 64);
   1125     hexDigit &= 0xF;
   1126 
   1127     // Map that over to a lowercase hex digit.
   1128     static const char charForHex[16] = {
   1129       '0', '1', '2', '3', '4', '5', '6', '7',
   1130       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
   1131     };
   1132     buffer[stringIndex] = charForHex[hexDigit];
   1133   }
   1134 
   1135   Out.write(buffer.data(), numCharacters);
   1136 }
   1137 
   1138 void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
   1139   Out << 'L';
   1140   mangleType(T);
   1141   mangleFloat(V);
   1142   Out << 'E';
   1143 }
   1144 
   1145 void CXXNameMangler::mangleFixedPointLiteral() {
   1146   DiagnosticsEngine &Diags = Context.getDiags();
   1147   unsigned DiagID = Diags.getCustomDiagID(
   1148       DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
   1149   Diags.Report(DiagID);
   1150 }
   1151 
   1152 void CXXNameMangler::mangleNullPointer(QualType T) {
   1153   //  <expr-primary> ::= L <type> 0 E
   1154   Out << 'L';
   1155   mangleType(T);
   1156   Out << "0E";
   1157 }
   1158 
   1159 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
   1160   if (Value.isSigned() && Value.isNegative()) {
   1161     Out << 'n';
   1162     Value.abs().print(Out, /*signed*/ false);
   1163   } else {
   1164     Value.print(Out, /*signed*/ false);
   1165   }
   1166 }
   1167 
   1168 void CXXNameMangler::mangleNumber(int64_t Number) {
   1169   //  <number> ::= [n] <non-negative decimal integer>
   1170   if (Number < 0) {
   1171     Out << 'n';
   1172     Number = -Number;
   1173   }
   1174 
   1175   Out << Number;
   1176 }
   1177 
   1178 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
   1179   //  <call-offset>  ::= h <nv-offset> _
   1180   //                 ::= v <v-offset> _
   1181   //  <nv-offset>    ::= <offset number>        # non-virtual base override
   1182   //  <v-offset>     ::= <offset number> _ <virtual offset number>
   1183   //                      # virtual base override, with vcall offset
   1184   if (!Virtual) {
   1185     Out << 'h';
   1186     mangleNumber(NonVirtual);
   1187     Out << '_';
   1188     return;
   1189   }
   1190 
   1191   Out << 'v';
   1192   mangleNumber(NonVirtual);
   1193   Out << '_';
   1194   mangleNumber(Virtual);
   1195   Out << '_';
   1196 }
   1197 
   1198 void CXXNameMangler::manglePrefix(QualType type) {
   1199   if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
   1200     if (!mangleSubstitution(QualType(TST, 0))) {
   1201       mangleTemplatePrefix(TST->getTemplateName());
   1202 
   1203       // FIXME: GCC does not appear to mangle the template arguments when
   1204       // the template in question is a dependent template name. Should we
   1205       // emulate that badness?
   1206       mangleTemplateArgs(TST->getTemplateName(), TST->getArgs(),
   1207                          TST->getNumArgs());
   1208       addSubstitution(QualType(TST, 0));
   1209     }
   1210   } else if (const auto *DTST =
   1211                  type->getAs<DependentTemplateSpecializationType>()) {
   1212     if (!mangleSubstitution(QualType(DTST, 0))) {
   1213       TemplateName Template = getASTContext().getDependentTemplateName(
   1214           DTST->getQualifier(), DTST->getIdentifier());
   1215       mangleTemplatePrefix(Template);
   1216 
   1217       // FIXME: GCC does not appear to mangle the template arguments when
   1218       // the template in question is a dependent template name. Should we
   1219       // emulate that badness?
   1220       mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
   1221       addSubstitution(QualType(DTST, 0));
   1222     }
   1223   } else {
   1224     // We use the QualType mangle type variant here because it handles
   1225     // substitutions.
   1226     mangleType(type);
   1227   }
   1228 }
   1229 
   1230 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
   1231 ///
   1232 /// \param recursive - true if this is being called recursively,
   1233 ///   i.e. if there is more prefix "to the right".
   1234 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
   1235                                             bool recursive) {
   1236 
   1237   // x, ::x
   1238   // <unresolved-name> ::= [gs] <base-unresolved-name>
   1239 
   1240   // T::x / decltype(p)::x
   1241   // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
   1242 
   1243   // T::N::x /decltype(p)::N::x
   1244   // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
   1245   //                       <base-unresolved-name>
   1246 
   1247   // A::x, N::y, A<T>::z; "gs" means leading "::"
   1248   // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
   1249   //                       <base-unresolved-name>
   1250 
   1251   switch (qualifier->getKind()) {
   1252   case NestedNameSpecifier::Global:
   1253     Out << "gs";
   1254 
   1255     // We want an 'sr' unless this is the entire NNS.
   1256     if (recursive)
   1257       Out << "sr";
   1258 
   1259     // We never want an 'E' here.
   1260     return;
   1261 
   1262   case NestedNameSpecifier::Super:
   1263     llvm_unreachable("Can't mangle __super specifier");
   1264 
   1265   case NestedNameSpecifier::Namespace:
   1266     if (qualifier->getPrefix())
   1267       mangleUnresolvedPrefix(qualifier->getPrefix(),
   1268                              /*recursive*/ true);
   1269     else
   1270       Out << "sr";
   1271     mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
   1272     break;
   1273   case NestedNameSpecifier::NamespaceAlias:
   1274     if (qualifier->getPrefix())
   1275       mangleUnresolvedPrefix(qualifier->getPrefix(),
   1276                              /*recursive*/ true);
   1277     else
   1278       Out << "sr";
   1279     mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
   1280     break;
   1281 
   1282   case NestedNameSpecifier::TypeSpec:
   1283   case NestedNameSpecifier::TypeSpecWithTemplate: {
   1284     const Type *type = qualifier->getAsType();
   1285 
   1286     // We only want to use an unresolved-type encoding if this is one of:
   1287     //   - a decltype
   1288     //   - a template type parameter
   1289     //   - a template template parameter with arguments
   1290     // In all of these cases, we should have no prefix.
   1291     if (qualifier->getPrefix()) {
   1292       mangleUnresolvedPrefix(qualifier->getPrefix(),
   1293                              /*recursive*/ true);
   1294     } else {
   1295       // Otherwise, all the cases want this.
   1296       Out << "sr";
   1297     }
   1298 
   1299     if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
   1300       return;
   1301 
   1302     break;
   1303   }
   1304 
   1305   case NestedNameSpecifier::Identifier:
   1306     // Member expressions can have these without prefixes.
   1307     if (qualifier->getPrefix())
   1308       mangleUnresolvedPrefix(qualifier->getPrefix(),
   1309                              /*recursive*/ true);
   1310     else
   1311       Out << "sr";
   1312 
   1313     mangleSourceName(qualifier->getAsIdentifier());
   1314     // An Identifier has no type information, so we can't emit abi tags for it.
   1315     break;
   1316   }
   1317 
   1318   // If this was the innermost part of the NNS, and we fell out to
   1319   // here, append an 'E'.
   1320   if (!recursive)
   1321     Out << 'E';
   1322 }
   1323 
   1324 /// Mangle an unresolved-name, which is generally used for names which
   1325 /// weren't resolved to specific entities.
   1326 void CXXNameMangler::mangleUnresolvedName(
   1327     NestedNameSpecifier *qualifier, DeclarationName name,
   1328     const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
   1329     unsigned knownArity) {
   1330   if (qualifier) mangleUnresolvedPrefix(qualifier);
   1331   switch (name.getNameKind()) {
   1332     // <base-unresolved-name> ::= <simple-id>
   1333     case DeclarationName::Identifier:
   1334       mangleSourceName(name.getAsIdentifierInfo());
   1335       break;
   1336     // <base-unresolved-name> ::= dn <destructor-name>
   1337     case DeclarationName::CXXDestructorName:
   1338       Out << "dn";
   1339       mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
   1340       break;
   1341     // <base-unresolved-name> ::= on <operator-name>
   1342     case DeclarationName::CXXConversionFunctionName:
   1343     case DeclarationName::CXXLiteralOperatorName:
   1344     case DeclarationName::CXXOperatorName:
   1345       Out << "on";
   1346       mangleOperatorName(name, knownArity);
   1347       break;
   1348     case DeclarationName::CXXConstructorName:
   1349       llvm_unreachable("Can't mangle a constructor name!");
   1350     case DeclarationName::CXXUsingDirective:
   1351       llvm_unreachable("Can't mangle a using directive name!");
   1352     case DeclarationName::CXXDeductionGuideName:
   1353       llvm_unreachable("Can't mangle a deduction guide name!");
   1354     case DeclarationName::ObjCMultiArgSelector:
   1355     case DeclarationName::ObjCOneArgSelector:
   1356     case DeclarationName::ObjCZeroArgSelector:
   1357       llvm_unreachable("Can't mangle Objective-C selector names here!");
   1358   }
   1359 
   1360   // The <simple-id> and on <operator-name> productions end in an optional
   1361   // <template-args>.
   1362   if (TemplateArgs)
   1363     mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
   1364 }
   1365 
   1366 void CXXNameMangler::mangleUnqualifiedName(GlobalDecl GD,
   1367                                            DeclarationName Name,
   1368                                            unsigned KnownArity,
   1369                                            const AbiTagList *AdditionalAbiTags) {
   1370   const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
   1371   unsigned Arity = KnownArity;
   1372   //  <unqualified-name> ::= <operator-name>
   1373   //                     ::= <ctor-dtor-name>
   1374   //                     ::= <source-name>
   1375   switch (Name.getNameKind()) {
   1376   case DeclarationName::Identifier: {
   1377     const IdentifierInfo *II = Name.getAsIdentifierInfo();
   1378 
   1379     // We mangle decomposition declarations as the names of their bindings.
   1380     if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
   1381       // FIXME: Non-standard mangling for decomposition declarations:
   1382       //
   1383       //  <unqualified-name> ::= DC <source-name>* E
   1384       //
   1385       // These can never be referenced across translation units, so we do
   1386       // not need a cross-vendor mangling for anything other than demanglers.
   1387       // Proposed on cxx-abi-dev on 2016-08-12
   1388       Out << "DC";
   1389       for (auto *BD : DD->bindings())
   1390         mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
   1391       Out << 'E';
   1392       writeAbiTags(ND, AdditionalAbiTags);
   1393       break;
   1394     }
   1395 
   1396     if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
   1397       // We follow MSVC in mangling GUID declarations as if they were variables
   1398       // with a particular reserved name. Continue the pretense here.
   1399       SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
   1400       llvm::raw_svector_ostream GUIDOS(GUID);
   1401       Context.mangleMSGuidDecl(GD, GUIDOS);
   1402       Out << GUID.size() << GUID;
   1403       break;
   1404     }
   1405 
   1406     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
   1407       // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
   1408       Out << "TA";
   1409       mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
   1410                                TPO->getValue(), /*TopLevel=*/true);
   1411       break;
   1412     }
   1413 
   1414     if (II) {
   1415       // Match GCC's naming convention for internal linkage symbols, for
   1416       // symbols that are not actually visible outside of this TU. GCC
   1417       // distinguishes between internal and external linkage symbols in
   1418       // its mangling, to support cases like this that were valid C++ prior
   1419       // to DR426:
   1420       //
   1421       //   void test() { extern void foo(); }
   1422       //   static void foo();
   1423       //
   1424       // Don't bother with the L marker for names in anonymous namespaces; the
   1425       // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
   1426       // matches GCC anyway, because GCC does not treat anonymous namespaces as
   1427       // implying internal linkage.
   1428       if (isInternalLinkageDecl(ND))
   1429         Out << 'L';
   1430 
   1431       auto *FD = dyn_cast<FunctionDecl>(ND);
   1432       bool IsRegCall = FD &&
   1433                        FD->getType()->castAs<FunctionType>()->getCallConv() ==
   1434                            clang::CC_X86RegCall;
   1435       bool IsDeviceStub =
   1436           FD && FD->hasAttr<CUDAGlobalAttr>() &&
   1437           GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
   1438       if (IsDeviceStub)
   1439         mangleDeviceStubName(II);
   1440       else if (IsRegCall)
   1441         mangleRegCallName(II);
   1442       else
   1443         mangleSourceName(II);
   1444 
   1445       writeAbiTags(ND, AdditionalAbiTags);
   1446       break;
   1447     }
   1448 
   1449     // Otherwise, an anonymous entity.  We must have a declaration.
   1450     assert(ND && "mangling empty name without declaration");
   1451 
   1452     if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
   1453       if (NS->isAnonymousNamespace()) {
   1454         // This is how gcc mangles these names.
   1455         Out << "12_GLOBAL__N_1";
   1456         break;
   1457       }
   1458     }
   1459 
   1460     if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
   1461       // We must have an anonymous union or struct declaration.
   1462       const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
   1463 
   1464       // Itanium C++ ABI 5.1.2:
   1465       //
   1466       //   For the purposes of mangling, the name of an anonymous union is
   1467       //   considered to be the name of the first named data member found by a
   1468       //   pre-order, depth-first, declaration-order walk of the data members of
   1469       //   the anonymous union. If there is no such data member (i.e., if all of
   1470       //   the data members in the union are unnamed), then there is no way for
   1471       //   a program to refer to the anonymous union, and there is therefore no
   1472       //   need to mangle its name.
   1473       assert(RD->isAnonymousStructOrUnion()
   1474              && "Expected anonymous struct or union!");
   1475       const FieldDecl *FD = RD->findFirstNamedDataMember();
   1476 
   1477       // It's actually possible for various reasons for us to get here
   1478       // with an empty anonymous struct / union.  Fortunately, it
   1479       // doesn't really matter what name we generate.
   1480       if (!FD) break;
   1481       assert(FD->getIdentifier() && "Data member name isn't an identifier!");
   1482 
   1483       mangleSourceName(FD->getIdentifier());
   1484       // Not emitting abi tags: internal name anyway.
   1485       break;
   1486     }
   1487 
   1488     // Class extensions have no name as a category, and it's possible
   1489     // for them to be the semantic parent of certain declarations
   1490     // (primarily, tag decls defined within declarations).  Such
   1491     // declarations will always have internal linkage, so the name
   1492     // doesn't really matter, but we shouldn't crash on them.  For
   1493     // safety, just handle all ObjC containers here.
   1494     if (isa<ObjCContainerDecl>(ND))
   1495       break;
   1496 
   1497     // We must have an anonymous struct.
   1498     const TagDecl *TD = cast<TagDecl>(ND);
   1499     if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
   1500       assert(TD->getDeclContext() == D->getDeclContext() &&
   1501              "Typedef should not be in another decl context!");
   1502       assert(D->getDeclName().getAsIdentifierInfo() &&
   1503              "Typedef was not named!");
   1504       mangleSourceName(D->getDeclName().getAsIdentifierInfo());
   1505       assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
   1506       // Explicit abi tags are still possible; take from underlying type, not
   1507       // from typedef.
   1508       writeAbiTags(TD, nullptr);
   1509       break;
   1510     }
   1511 
   1512     // <unnamed-type-name> ::= <closure-type-name>
   1513     //
   1514     // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
   1515     // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
   1516     //     # Parameter types or 'v' for 'void'.
   1517     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
   1518       if (Record->isLambda() && Record->getLambdaManglingNumber()) {
   1519         assert(!AdditionalAbiTags &&
   1520                "Lambda type cannot have additional abi tags");
   1521         mangleLambda(Record);
   1522         break;
   1523       }
   1524     }
   1525 
   1526     if (TD->isExternallyVisible()) {
   1527       unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
   1528       Out << "Ut";
   1529       if (UnnamedMangle > 1)
   1530         Out << UnnamedMangle - 2;
   1531       Out << '_';
   1532       writeAbiTags(TD, AdditionalAbiTags);
   1533       break;
   1534     }
   1535 
   1536     // Get a unique id for the anonymous struct. If it is not a real output
   1537     // ID doesn't matter so use fake one.
   1538     unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
   1539 
   1540     // Mangle it as a source name in the form
   1541     // [n] $_<id>
   1542     // where n is the length of the string.
   1543     SmallString<8> Str;
   1544     Str += "$_";
   1545     Str += llvm::utostr(AnonStructId);
   1546 
   1547     Out << Str.size();
   1548     Out << Str;
   1549     break;
   1550   }
   1551 
   1552   case DeclarationName::ObjCZeroArgSelector:
   1553   case DeclarationName::ObjCOneArgSelector:
   1554   case DeclarationName::ObjCMultiArgSelector:
   1555     llvm_unreachable("Can't mangle Objective-C selector names here!");
   1556 
   1557   case DeclarationName::CXXConstructorName: {
   1558     const CXXRecordDecl *InheritedFrom = nullptr;
   1559     TemplateName InheritedTemplateName;
   1560     const TemplateArgumentList *InheritedTemplateArgs = nullptr;
   1561     if (auto Inherited =
   1562             cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
   1563       InheritedFrom = Inherited.getConstructor()->getParent();
   1564       InheritedTemplateName =
   1565           TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
   1566       InheritedTemplateArgs =
   1567           Inherited.getConstructor()->getTemplateSpecializationArgs();
   1568     }
   1569 
   1570     if (ND == Structor)
   1571       // If the named decl is the C++ constructor we're mangling, use the type
   1572       // we were given.
   1573       mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
   1574     else
   1575       // Otherwise, use the complete constructor name. This is relevant if a
   1576       // class with a constructor is declared within a constructor.
   1577       mangleCXXCtorType(Ctor_Complete, InheritedFrom);
   1578 
   1579     // FIXME: The template arguments are part of the enclosing prefix or
   1580     // nested-name, but it's more convenient to mangle them here.
   1581     if (InheritedTemplateArgs)
   1582       mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
   1583 
   1584     writeAbiTags(ND, AdditionalAbiTags);
   1585     break;
   1586   }
   1587 
   1588   case DeclarationName::CXXDestructorName:
   1589     if (ND == Structor)
   1590       // If the named decl is the C++ destructor we're mangling, use the type we
   1591       // were given.
   1592       mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
   1593     else
   1594       // Otherwise, use the complete destructor name. This is relevant if a
   1595       // class with a destructor is declared within a destructor.
   1596       mangleCXXDtorType(Dtor_Complete);
   1597     writeAbiTags(ND, AdditionalAbiTags);
   1598     break;
   1599 
   1600   case DeclarationName::CXXOperatorName:
   1601     if (ND && Arity == UnknownArity) {
   1602       Arity = cast<FunctionDecl>(ND)->getNumParams();
   1603 
   1604       // If we have a member function, we need to include the 'this' pointer.
   1605       if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
   1606         if (!MD->isStatic())
   1607           Arity++;
   1608     }
   1609     LLVM_FALLTHROUGH;
   1610   case DeclarationName::CXXConversionFunctionName:
   1611   case DeclarationName::CXXLiteralOperatorName:
   1612     mangleOperatorName(Name, Arity);
   1613     writeAbiTags(ND, AdditionalAbiTags);
   1614     break;
   1615 
   1616   case DeclarationName::CXXDeductionGuideName:
   1617     llvm_unreachable("Can't mangle a deduction guide name!");
   1618 
   1619   case DeclarationName::CXXUsingDirective:
   1620     llvm_unreachable("Can't mangle a using directive name!");
   1621   }
   1622 }
   1623 
   1624 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
   1625   // <source-name> ::= <positive length number> __regcall3__ <identifier>
   1626   // <number> ::= [n] <non-negative decimal integer>
   1627   // <identifier> ::= <unqualified source code identifier>
   1628   Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
   1629       << II->getName();
   1630 }
   1631 
   1632 void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
   1633   // <source-name> ::= <positive length number> __device_stub__ <identifier>
   1634   // <number> ::= [n] <non-negative decimal integer>
   1635   // <identifier> ::= <unqualified source code identifier>
   1636   Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
   1637       << II->getName();
   1638 }
   1639 
   1640 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
   1641   // <source-name> ::= <positive length number> <identifier>
   1642   // <number> ::= [n] <non-negative decimal integer>
   1643   // <identifier> ::= <unqualified source code identifier>
   1644   Out << II->getLength() << II->getName();
   1645 }
   1646 
   1647 void CXXNameMangler::mangleNestedName(GlobalDecl GD,
   1648                                       const DeclContext *DC,
   1649                                       const AbiTagList *AdditionalAbiTags,
   1650                                       bool NoFunction) {
   1651   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
   1652   // <nested-name>
   1653   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
   1654   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
   1655   //       <template-args> E
   1656 
   1657   Out << 'N';
   1658   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
   1659     Qualifiers MethodQuals = Method->getMethodQualifiers();
   1660     // We do not consider restrict a distinguishing attribute for overloading
   1661     // purposes so we must not mangle it.
   1662     MethodQuals.removeRestrict();
   1663     mangleQualifiers(MethodQuals);
   1664     mangleRefQualifier(Method->getRefQualifier());
   1665   }
   1666 
   1667   // Check if we have a template.
   1668   const TemplateArgumentList *TemplateArgs = nullptr;
   1669   if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
   1670     mangleTemplatePrefix(TD, NoFunction);
   1671     mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
   1672   } else {
   1673     manglePrefix(DC, NoFunction);
   1674     mangleUnqualifiedName(GD, AdditionalAbiTags);
   1675   }
   1676 
   1677   Out << 'E';
   1678 }
   1679 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
   1680                                       const TemplateArgument *TemplateArgs,
   1681                                       unsigned NumTemplateArgs) {
   1682   // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
   1683 
   1684   Out << 'N';
   1685 
   1686   mangleTemplatePrefix(TD);
   1687   mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs);
   1688 
   1689   Out << 'E';
   1690 }
   1691 
   1692 void CXXNameMangler::mangleNestedNameWithClosurePrefix(
   1693     GlobalDecl GD, const NamedDecl *PrefixND,
   1694     const AbiTagList *AdditionalAbiTags) {
   1695   // A <closure-prefix> represents a variable or field, not a regular
   1696   // DeclContext, so needs special handling. In this case we're mangling a
   1697   // limited form of <nested-name>:
   1698   //
   1699   // <nested-name> ::= N <closure-prefix> <closure-type-name> E
   1700 
   1701   Out << 'N';
   1702 
   1703   mangleClosurePrefix(PrefixND);
   1704   mangleUnqualifiedName(GD, AdditionalAbiTags);
   1705 
   1706   Out << 'E';
   1707 }
   1708 
   1709 static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
   1710   GlobalDecl GD;
   1711   // The Itanium spec says:
   1712   // For entities in constructors and destructors, the mangling of the
   1713   // complete object constructor or destructor is used as the base function
   1714   // name, i.e. the C1 or D1 version.
   1715   if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
   1716     GD = GlobalDecl(CD, Ctor_Complete);
   1717   else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
   1718     GD = GlobalDecl(DD, Dtor_Complete);
   1719   else
   1720     GD = GlobalDecl(cast<FunctionDecl>(DC));
   1721   return GD;
   1722 }
   1723 
   1724 void CXXNameMangler::mangleLocalName(GlobalDecl GD,
   1725                                      const AbiTagList *AdditionalAbiTags) {
   1726   const Decl *D = GD.getDecl();
   1727   // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
   1728   //              := Z <function encoding> E s [<discriminator>]
   1729   // <local-name> := Z <function encoding> E d [ <parameter number> ]
   1730   //                 _ <entity name>
   1731   // <discriminator> := _ <non-negative number>
   1732   assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
   1733   const RecordDecl *RD = GetLocalClassDecl(D);
   1734   const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
   1735 
   1736   Out << 'Z';
   1737 
   1738   {
   1739     AbiTagState LocalAbiTags(AbiTags);
   1740 
   1741     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
   1742       mangleObjCMethodName(MD);
   1743     else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
   1744       mangleBlockForPrefix(BD);
   1745     else
   1746       mangleFunctionEncoding(getParentOfLocalEntity(DC));
   1747 
   1748     // Implicit ABI tags (from namespace) are not available in the following
   1749     // entity; reset to actually emitted tags, which are available.
   1750     LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
   1751   }
   1752 
   1753   Out << 'E';
   1754 
   1755   // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
   1756   // be a bug that is fixed in trunk.
   1757 
   1758   if (RD) {
   1759     // The parameter number is omitted for the last parameter, 0 for the
   1760     // second-to-last parameter, 1 for the third-to-last parameter, etc. The
   1761     // <entity name> will of course contain a <closure-type-name>: Its
   1762     // numbering will be local to the particular argument in which it appears
   1763     // -- other default arguments do not affect its encoding.
   1764     const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
   1765     if (CXXRD && CXXRD->isLambda()) {
   1766       if (const ParmVarDecl *Parm
   1767               = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
   1768         if (const FunctionDecl *Func
   1769               = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
   1770           Out << 'd';
   1771           unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
   1772           if (Num > 1)
   1773             mangleNumber(Num - 2);
   1774           Out << '_';
   1775         }
   1776       }
   1777     }
   1778 
   1779     // Mangle the name relative to the closest enclosing function.
   1780     // equality ok because RD derived from ND above
   1781     if (D == RD)  {
   1782       mangleUnqualifiedName(RD, AdditionalAbiTags);
   1783     } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
   1784       if (const NamedDecl *PrefixND = getClosurePrefix(BD))
   1785         mangleClosurePrefix(PrefixND, true /*NoFunction*/);
   1786       else
   1787         manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
   1788       assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
   1789       mangleUnqualifiedBlock(BD);
   1790     } else {
   1791       const NamedDecl *ND = cast<NamedDecl>(D);
   1792       mangleNestedName(GD, getEffectiveDeclContext(ND), AdditionalAbiTags,
   1793                        true /*NoFunction*/);
   1794     }
   1795   } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
   1796     // Mangle a block in a default parameter; see above explanation for
   1797     // lambdas.
   1798     if (const ParmVarDecl *Parm
   1799             = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
   1800       if (const FunctionDecl *Func
   1801             = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
   1802         Out << 'd';
   1803         unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
   1804         if (Num > 1)
   1805           mangleNumber(Num - 2);
   1806         Out << '_';
   1807       }
   1808     }
   1809 
   1810     assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
   1811     mangleUnqualifiedBlock(BD);
   1812   } else {
   1813     mangleUnqualifiedName(GD, AdditionalAbiTags);
   1814   }
   1815 
   1816   if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
   1817     unsigned disc;
   1818     if (Context.getNextDiscriminator(ND, disc)) {
   1819       if (disc < 10)
   1820         Out << '_' << disc;
   1821       else
   1822         Out << "__" << disc << '_';
   1823     }
   1824   }
   1825 }
   1826 
   1827 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
   1828   if (GetLocalClassDecl(Block)) {
   1829     mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
   1830     return;
   1831   }
   1832   const DeclContext *DC = getEffectiveDeclContext(Block);
   1833   if (isLocalContainerContext(DC)) {
   1834     mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
   1835     return;
   1836   }
   1837   if (const NamedDecl *PrefixND = getClosurePrefix(Block))
   1838     mangleClosurePrefix(PrefixND);
   1839   else
   1840     manglePrefix(DC);
   1841   mangleUnqualifiedBlock(Block);
   1842 }
   1843 
   1844 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
   1845   // When trying to be ABI-compatibility with clang 12 and before, mangle a
   1846   // <data-member-prefix> now, with no substitutions and no <template-args>.
   1847   if (Decl *Context = Block->getBlockManglingContextDecl()) {
   1848     if (getASTContext().getLangOpts().getClangABICompat() <=
   1849             LangOptions::ClangABI::Ver12 &&
   1850         (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
   1851         Context->getDeclContext()->isRecord()) {
   1852       const auto *ND = cast<NamedDecl>(Context);
   1853       if (ND->getIdentifier()) {
   1854         mangleSourceNameWithAbiTags(ND);
   1855         Out << 'M';
   1856       }
   1857     }
   1858   }
   1859 
   1860   // If we have a block mangling number, use it.
   1861   unsigned Number = Block->getBlockManglingNumber();
   1862   // Otherwise, just make up a number. It doesn't matter what it is because
   1863   // the symbol in question isn't externally visible.
   1864   if (!Number)
   1865     Number = Context.getBlockId(Block, false);
   1866   else {
   1867     // Stored mangling numbers are 1-based.
   1868     --Number;
   1869   }
   1870   Out << "Ub";
   1871   if (Number > 0)
   1872     Out << Number - 1;
   1873   Out << '_';
   1874 }
   1875 
   1876 // <template-param-decl>
   1877 //   ::= Ty                              # template type parameter
   1878 //   ::= Tn <type>                       # template non-type parameter
   1879 //   ::= Tt <template-param-decl>* E     # template template parameter
   1880 //   ::= Tp <template-param-decl>        # template parameter pack
   1881 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
   1882   if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
   1883     if (Ty->isParameterPack())
   1884       Out << "Tp";
   1885     Out << "Ty";
   1886   } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
   1887     if (Tn->isExpandedParameterPack()) {
   1888       for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
   1889         Out << "Tn";
   1890         mangleType(Tn->getExpansionType(I));
   1891       }
   1892     } else {
   1893       QualType T = Tn->getType();
   1894       if (Tn->isParameterPack()) {
   1895         Out << "Tp";
   1896         if (auto *PackExpansion = T->getAs<PackExpansionType>())
   1897           T = PackExpansion->getPattern();
   1898       }
   1899       Out << "Tn";
   1900       mangleType(T);
   1901     }
   1902   } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
   1903     if (Tt->isExpandedParameterPack()) {
   1904       for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
   1905            ++I) {
   1906         Out << "Tt";
   1907         for (auto *Param : *Tt->getExpansionTemplateParameters(I))
   1908           mangleTemplateParamDecl(Param);
   1909         Out << "E";
   1910       }
   1911     } else {
   1912       if (Tt->isParameterPack())
   1913         Out << "Tp";
   1914       Out << "Tt";
   1915       for (auto *Param : *Tt->getTemplateParameters())
   1916         mangleTemplateParamDecl(Param);
   1917       Out << "E";
   1918     }
   1919   }
   1920 }
   1921 
   1922 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
   1923   // When trying to be ABI-compatibility with clang 12 and before, mangle a
   1924   // <data-member-prefix> now, with no substitutions.
   1925   if (Decl *Context = Lambda->getLambdaContextDecl()) {
   1926     if (getASTContext().getLangOpts().getClangABICompat() <=
   1927             LangOptions::ClangABI::Ver12 &&
   1928         (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
   1929         !isa<ParmVarDecl>(Context)) {
   1930       if (const IdentifierInfo *Name
   1931             = cast<NamedDecl>(Context)->getIdentifier()) {
   1932         mangleSourceName(Name);
   1933         const TemplateArgumentList *TemplateArgs = nullptr;
   1934         if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
   1935           mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
   1936         Out << 'M';
   1937       }
   1938     }
   1939   }
   1940 
   1941   Out << "Ul";
   1942   mangleLambdaSig(Lambda);
   1943   Out << "E";
   1944 
   1945   // The number is omitted for the first closure type with a given
   1946   // <lambda-sig> in a given context; it is n-2 for the nth closure type
   1947   // (in lexical order) with that same <lambda-sig> and context.
   1948   //
   1949   // The AST keeps track of the number for us.
   1950   //
   1951   // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
   1952   // and host-side compilations, an extra device mangle context may be created
   1953   // if the host-side CXX ABI has different numbering for lambda. In such case,
   1954   // if the mangle context is that device-side one, use the device-side lambda
   1955   // mangling number for this lambda.
   1956   unsigned Number = Context.isDeviceMangleContext()
   1957                         ? Lambda->getDeviceLambdaManglingNumber()
   1958                         : Lambda->getLambdaManglingNumber();
   1959   assert(Number > 0 && "Lambda should be mangled as an unnamed class");
   1960   if (Number > 1)
   1961     mangleNumber(Number - 2);
   1962   Out << '_';
   1963 }
   1964 
   1965 void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
   1966   for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
   1967     mangleTemplateParamDecl(D);
   1968   auto *Proto =
   1969       Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();
   1970   mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
   1971                          Lambda->getLambdaStaticInvoker());
   1972 }
   1973 
   1974 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
   1975   switch (qualifier->getKind()) {
   1976   case NestedNameSpecifier::Global:
   1977     // nothing
   1978     return;
   1979 
   1980   case NestedNameSpecifier::Super:
   1981     llvm_unreachable("Can't mangle __super specifier");
   1982 
   1983   case NestedNameSpecifier::Namespace:
   1984     mangleName(qualifier->getAsNamespace());
   1985     return;
   1986 
   1987   case NestedNameSpecifier::NamespaceAlias:
   1988     mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
   1989     return;
   1990 
   1991   case NestedNameSpecifier::TypeSpec:
   1992   case NestedNameSpecifier::TypeSpecWithTemplate:
   1993     manglePrefix(QualType(qualifier->getAsType(), 0));
   1994     return;
   1995 
   1996   case NestedNameSpecifier::Identifier:
   1997     // Member expressions can have these without prefixes, but that
   1998     // should end up in mangleUnresolvedPrefix instead.
   1999     assert(qualifier->getPrefix());
   2000     manglePrefix(qualifier->getPrefix());
   2001 
   2002     mangleSourceName(qualifier->getAsIdentifier());
   2003     return;
   2004   }
   2005 
   2006   llvm_unreachable("unexpected nested name specifier");
   2007 }
   2008 
   2009 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
   2010   //  <prefix> ::= <prefix> <unqualified-name>
   2011   //           ::= <template-prefix> <template-args>
   2012   //           ::= <closure-prefix>
   2013   //           ::= <template-param>
   2014   //           ::= # empty
   2015   //           ::= <substitution>
   2016 
   2017   DC = IgnoreLinkageSpecDecls(DC);
   2018 
   2019   if (DC->isTranslationUnit())
   2020     return;
   2021 
   2022   if (NoFunction && isLocalContainerContext(DC))
   2023     return;
   2024 
   2025   assert(!isLocalContainerContext(DC));
   2026 
   2027   const NamedDecl *ND = cast<NamedDecl>(DC);
   2028   if (mangleSubstitution(ND))
   2029     return;
   2030 
   2031   // Check if we have a template-prefix or a closure-prefix.
   2032   const TemplateArgumentList *TemplateArgs = nullptr;
   2033   if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
   2034     mangleTemplatePrefix(TD);
   2035     mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
   2036   } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
   2037     mangleClosurePrefix(PrefixND, NoFunction);
   2038     mangleUnqualifiedName(ND, nullptr);
   2039   } else {
   2040     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
   2041     mangleUnqualifiedName(ND, nullptr);
   2042   }
   2043 
   2044   addSubstitution(ND);
   2045 }
   2046 
   2047 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
   2048   // <template-prefix> ::= <prefix> <template unqualified-name>
   2049   //                   ::= <template-param>
   2050   //                   ::= <substitution>
   2051   if (TemplateDecl *TD = Template.getAsTemplateDecl())
   2052     return mangleTemplatePrefix(TD);
   2053 
   2054   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
   2055   assert(Dependent && "unexpected template name kind");
   2056 
   2057   // Clang 11 and before mangled the substitution for a dependent template name
   2058   // after already having emitted (a substitution for) the prefix.
   2059   bool Clang11Compat = getASTContext().getLangOpts().getClangABICompat() <=
   2060                        LangOptions::ClangABI::Ver11;
   2061   if (!Clang11Compat && mangleSubstitution(Template))
   2062     return;
   2063 
   2064   if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
   2065     manglePrefix(Qualifier);
   2066 
   2067   if (Clang11Compat && mangleSubstitution(Template))
   2068     return;
   2069 
   2070   if (const IdentifierInfo *Id = Dependent->getIdentifier())
   2071     mangleSourceName(Id);
   2072   else
   2073     mangleOperatorName(Dependent->getOperator(), UnknownArity);
   2074 
   2075   addSubstitution(Template);
   2076 }
   2077 
   2078 void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
   2079                                           bool NoFunction) {
   2080   const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
   2081   // <template-prefix> ::= <prefix> <template unqualified-name>
   2082   //                   ::= <template-param>
   2083   //                   ::= <substitution>
   2084   // <template-template-param> ::= <template-param>
   2085   //                               <substitution>
   2086 
   2087   if (mangleSubstitution(ND))
   2088     return;
   2089 
   2090   // <template-template-param> ::= <template-param>
   2091   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
   2092     mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
   2093   } else {
   2094     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
   2095     if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
   2096       mangleUnqualifiedName(GD, nullptr);
   2097     else
   2098       mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), nullptr);
   2099   }
   2100 
   2101   addSubstitution(ND);
   2102 }
   2103 
   2104 const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
   2105   if (getASTContext().getLangOpts().getClangABICompat() <=
   2106       LangOptions::ClangABI::Ver12)
   2107     return nullptr;
   2108 
   2109   const NamedDecl *Context = nullptr;
   2110   if (auto *Block = dyn_cast<BlockDecl>(ND)) {
   2111     Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
   2112   } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
   2113     if (RD->isLambda())
   2114       Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
   2115   }
   2116   if (!Context)
   2117     return nullptr;
   2118 
   2119   // Only lambdas within the initializer of a non-local variable or non-static
   2120   // data member get a <closure-prefix>.
   2121   if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
   2122       isa<FieldDecl>(Context))
   2123     return Context;
   2124 
   2125   return nullptr;
   2126 }
   2127 
   2128 void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
   2129   //  <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
   2130   //                   ::= <template-prefix> <template-args> M
   2131   if (mangleSubstitution(ND))
   2132     return;
   2133 
   2134   const TemplateArgumentList *TemplateArgs = nullptr;
   2135   if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
   2136     mangleTemplatePrefix(TD, NoFunction);
   2137     mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
   2138   } else {
   2139     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
   2140     mangleUnqualifiedName(ND, nullptr);
   2141   }
   2142 
   2143   Out << 'M';
   2144 
   2145   addSubstitution(ND);
   2146 }
   2147 
   2148 /// Mangles a template name under the production <type>.  Required for
   2149 /// template template arguments.
   2150 ///   <type> ::= <class-enum-type>
   2151 ///          ::= <template-param>
   2152 ///          ::= <substitution>
   2153 void CXXNameMangler::mangleType(TemplateName TN) {
   2154   if (mangleSubstitution(TN))
   2155     return;
   2156 
   2157   TemplateDecl *TD = nullptr;
   2158 
   2159   switch (TN.getKind()) {
   2160   case TemplateName::QualifiedTemplate:
   2161     TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
   2162     goto HaveDecl;
   2163 
   2164   case TemplateName::Template:
   2165     TD = TN.getAsTemplateDecl();
   2166     goto HaveDecl;
   2167 
   2168   HaveDecl:
   2169     if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
   2170       mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
   2171     else
   2172       mangleName(TD);
   2173     break;
   2174 
   2175   case TemplateName::OverloadedTemplate:
   2176   case TemplateName::AssumedTemplate:
   2177     llvm_unreachable("can't mangle an overloaded template name as a <type>");
   2178 
   2179   case TemplateName::DependentTemplate: {
   2180     const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
   2181     assert(Dependent->isIdentifier());
   2182 
   2183     // <class-enum-type> ::= <name>
   2184     // <name> ::= <nested-name>
   2185     mangleUnresolvedPrefix(Dependent->getQualifier());
   2186     mangleSourceName(Dependent->getIdentifier());
   2187     break;
   2188   }
   2189 
   2190   case TemplateName::SubstTemplateTemplateParm: {
   2191     // Substituted template parameters are mangled as the substituted
   2192     // template.  This will check for the substitution twice, which is
   2193     // fine, but we have to return early so that we don't try to *add*
   2194     // the substitution twice.
   2195     SubstTemplateTemplateParmStorage *subst
   2196       = TN.getAsSubstTemplateTemplateParm();
   2197     mangleType(subst->getReplacement());
   2198     return;
   2199   }
   2200 
   2201   case TemplateName::SubstTemplateTemplateParmPack: {
   2202     // FIXME: not clear how to mangle this!
   2203     // template <template <class> class T...> class A {
   2204     //   template <template <class> class U...> void foo(B<T,U> x...);
   2205     // };
   2206     Out << "_SUBSTPACK_";
   2207     break;
   2208   }
   2209   }
   2210 
   2211   addSubstitution(TN);
   2212 }
   2213 
   2214 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
   2215                                                     StringRef Prefix) {
   2216   // Only certain other types are valid as prefixes;  enumerate them.
   2217   switch (Ty->getTypeClass()) {
   2218   case Type::Builtin:
   2219   case Type::Complex:
   2220   case Type::Adjusted:
   2221   case Type::Decayed:
   2222   case Type::Pointer:
   2223   case Type::BlockPointer:
   2224   case Type::LValueReference:
   2225   case Type::RValueReference:
   2226   case Type::MemberPointer:
   2227   case Type::ConstantArray:
   2228   case Type::IncompleteArray:
   2229   case Type::VariableArray:
   2230   case Type::DependentSizedArray:
   2231   case Type::DependentAddressSpace:
   2232   case Type::DependentVector:
   2233   case Type::DependentSizedExtVector:
   2234   case Type::Vector:
   2235   case Type::ExtVector:
   2236   case Type::ConstantMatrix:
   2237   case Type::DependentSizedMatrix:
   2238   case Type::FunctionProto:
   2239   case Type::FunctionNoProto:
   2240   case Type::Paren:
   2241   case Type::Attributed:
   2242   case Type::Auto:
   2243   case Type::DeducedTemplateSpecialization:
   2244   case Type::PackExpansion:
   2245   case Type::ObjCObject:
   2246   case Type::ObjCInterface:
   2247   case Type::ObjCObjectPointer:
   2248   case Type::ObjCTypeParam:
   2249   case Type::Atomic:
   2250   case Type::Pipe:
   2251   case Type::MacroQualified:
   2252   case Type::ExtInt:
   2253   case Type::DependentExtInt:
   2254     llvm_unreachable("type is illegal as a nested name specifier");
   2255 
   2256   case Type::SubstTemplateTypeParmPack:
   2257     // FIXME: not clear how to mangle this!
   2258     // template <class T...> class A {
   2259     //   template <class U...> void foo(decltype(T::foo(U())) x...);
   2260     // };
   2261     Out << "_SUBSTPACK_";
   2262     break;
   2263 
   2264   // <unresolved-type> ::= <template-param>
   2265   //                   ::= <decltype>
   2266   //                   ::= <template-template-param> <template-args>
   2267   // (this last is not official yet)
   2268   case Type::TypeOfExpr:
   2269   case Type::TypeOf:
   2270   case Type::Decltype:
   2271   case Type::TemplateTypeParm:
   2272   case Type::UnaryTransform:
   2273   case Type::SubstTemplateTypeParm:
   2274   unresolvedType:
   2275     // Some callers want a prefix before the mangled type.
   2276     Out << Prefix;
   2277 
   2278     // This seems to do everything we want.  It's not really
   2279     // sanctioned for a substituted template parameter, though.
   2280     mangleType(Ty);
   2281 
   2282     // We never want to print 'E' directly after an unresolved-type,
   2283     // so we return directly.
   2284     return true;
   2285 
   2286   case Type::Typedef:
   2287     mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
   2288     break;
   2289 
   2290   case Type::UnresolvedUsing:
   2291     mangleSourceNameWithAbiTags(
   2292         cast<UnresolvedUsingType>(Ty)->getDecl());
   2293     break;
   2294 
   2295   case Type::Enum:
   2296   case Type::Record:
   2297     mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
   2298     break;
   2299 
   2300   case Type::TemplateSpecialization: {
   2301     const TemplateSpecializationType *TST =
   2302         cast<TemplateSpecializationType>(Ty);
   2303     TemplateName TN = TST->getTemplateName();
   2304     switch (TN.getKind()) {
   2305     case TemplateName::Template:
   2306     case TemplateName::QualifiedTemplate: {
   2307       TemplateDecl *TD = TN.getAsTemplateDecl();
   2308 
   2309       // If the base is a template template parameter, this is an
   2310       // unresolved type.
   2311       assert(TD && "no template for template specialization type");
   2312       if (isa<TemplateTemplateParmDecl>(TD))
   2313         goto unresolvedType;
   2314 
   2315       mangleSourceNameWithAbiTags(TD);
   2316       break;
   2317     }
   2318 
   2319     case TemplateName::OverloadedTemplate:
   2320     case TemplateName::AssumedTemplate:
   2321     case TemplateName::DependentTemplate:
   2322       llvm_unreachable("invalid base for a template specialization type");
   2323 
   2324     case TemplateName::SubstTemplateTemplateParm: {
   2325       SubstTemplateTemplateParmStorage *subst =
   2326           TN.getAsSubstTemplateTemplateParm();
   2327       mangleExistingSubstitution(subst->getReplacement());
   2328       break;
   2329     }
   2330 
   2331     case TemplateName::SubstTemplateTemplateParmPack: {
   2332       // FIXME: not clear how to mangle this!
   2333       // template <template <class U> class T...> class A {
   2334       //   template <class U...> void foo(decltype(T<U>::foo) x...);
   2335       // };
   2336       Out << "_SUBSTPACK_";
   2337       break;
   2338     }
   2339     }
   2340 
   2341     // Note: we don't pass in the template name here. We are mangling the
   2342     // original source-level template arguments, so we shouldn't consider
   2343     // conversions to the corresponding template parameter.
   2344     // FIXME: Other compilers mangle partially-resolved template arguments in
   2345     // unresolved-qualifier-levels.
   2346     mangleTemplateArgs(TemplateName(), TST->getArgs(), TST->getNumArgs());
   2347     break;
   2348   }
   2349 
   2350   case Type::InjectedClassName:
   2351     mangleSourceNameWithAbiTags(
   2352         cast<InjectedClassNameType>(Ty)->getDecl());
   2353     break;
   2354 
   2355   case Type::DependentName:
   2356     mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
   2357     break;
   2358 
   2359   case Type::DependentTemplateSpecialization: {
   2360     const DependentTemplateSpecializationType *DTST =
   2361         cast<DependentTemplateSpecializationType>(Ty);
   2362     TemplateName Template = getASTContext().getDependentTemplateName(
   2363         DTST->getQualifier(), DTST->getIdentifier());
   2364     mangleSourceName(DTST->getIdentifier());
   2365     mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
   2366     break;
   2367   }
   2368 
   2369   case Type::Elaborated:
   2370     return mangleUnresolvedTypeOrSimpleId(
   2371         cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
   2372   }
   2373 
   2374   return false;
   2375 }
   2376 
   2377 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
   2378   switch (Name.getNameKind()) {
   2379   case DeclarationName::CXXConstructorName:
   2380   case DeclarationName::CXXDestructorName:
   2381   case DeclarationName::CXXDeductionGuideName:
   2382   case DeclarationName::CXXUsingDirective:
   2383   case DeclarationName::Identifier:
   2384   case DeclarationName::ObjCMultiArgSelector:
   2385   case DeclarationName::ObjCOneArgSelector:
   2386   case DeclarationName::ObjCZeroArgSelector:
   2387     llvm_unreachable("Not an operator name");
   2388 
   2389   case DeclarationName::CXXConversionFunctionName:
   2390     // <operator-name> ::= cv <type>    # (cast)
   2391     Out << "cv";
   2392     mangleType(Name.getCXXNameType());
   2393     break;
   2394 
   2395   case DeclarationName::CXXLiteralOperatorName:
   2396     Out << "li";
   2397     mangleSourceName(Name.getCXXLiteralIdentifier());
   2398     return;
   2399 
   2400   case DeclarationName::CXXOperatorName:
   2401     mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
   2402     break;
   2403   }
   2404 }
   2405 
   2406 void
   2407 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
   2408   switch (OO) {
   2409   // <operator-name> ::= nw     # new
   2410   case OO_New: Out << "nw"; break;
   2411   //              ::= na        # new[]
   2412   case OO_Array_New: Out << "na"; break;
   2413   //              ::= dl        # delete
   2414   case OO_Delete: Out << "dl"; break;
   2415   //              ::= da        # delete[]
   2416   case OO_Array_Delete: Out << "da"; break;
   2417   //              ::= ps        # + (unary)
   2418   //              ::= pl        # + (binary or unknown)
   2419   case OO_Plus:
   2420     Out << (Arity == 1? "ps" : "pl"); break;
   2421   //              ::= ng        # - (unary)
   2422   //              ::= mi        # - (binary or unknown)
   2423   case OO_Minus:
   2424     Out << (Arity == 1? "ng" : "mi"); break;
   2425   //              ::= ad        # & (unary)
   2426   //              ::= an        # & (binary or unknown)
   2427   case OO_Amp:
   2428     Out << (Arity == 1? "ad" : "an"); break;
   2429   //              ::= de        # * (unary)
   2430   //              ::= ml        # * (binary or unknown)
   2431   case OO_Star:
   2432     // Use binary when unknown.
   2433     Out << (Arity == 1? "de" : "ml"); break;
   2434   //              ::= co        # ~
   2435   case OO_Tilde: Out << "co"; break;
   2436   //              ::= dv        # /
   2437   case OO_Slash: Out << "dv"; break;
   2438   //              ::= rm        # %
   2439   case OO_Percent: Out << "rm"; break;
   2440   //              ::= or        # |
   2441   case OO_Pipe: Out << "or"; break;
   2442   //              ::= eo        # ^
   2443   case OO_Caret: Out << "eo"; break;
   2444   //              ::= aS        # =
   2445   case OO_Equal: Out << "aS"; break;
   2446   //              ::= pL        # +=
   2447   case OO_PlusEqual: Out << "pL"; break;
   2448   //              ::= mI        # -=
   2449   case OO_MinusEqual: Out << "mI"; break;
   2450   //              ::= mL        # *=
   2451   case OO_StarEqual: Out << "mL"; break;
   2452   //              ::= dV        # /=
   2453   case OO_SlashEqual: Out << "dV"; break;
   2454   //              ::= rM        # %=
   2455   case OO_PercentEqual: Out << "rM"; break;
   2456   //              ::= aN        # &=
   2457   case OO_AmpEqual: Out << "aN"; break;
   2458   //              ::= oR        # |=
   2459   case OO_PipeEqual: Out << "oR"; break;
   2460   //              ::= eO        # ^=
   2461   case OO_CaretEqual: Out << "eO"; break;
   2462   //              ::= ls        # <<
   2463   case OO_LessLess: Out << "ls"; break;
   2464   //              ::= rs        # >>
   2465   case OO_GreaterGreater: Out << "rs"; break;
   2466   //              ::= lS        # <<=
   2467   case OO_LessLessEqual: Out << "lS"; break;
   2468   //              ::= rS        # >>=
   2469   case OO_GreaterGreaterEqual: Out << "rS"; break;
   2470   //              ::= eq        # ==
   2471   case OO_EqualEqual: Out << "eq"; break;
   2472   //              ::= ne        # !=
   2473   case OO_ExclaimEqual: Out << "ne"; break;
   2474   //              ::= lt        # <
   2475   case OO_Less: Out << "lt"; break;
   2476   //              ::= gt        # >
   2477   case OO_Greater: Out << "gt"; break;
   2478   //              ::= le        # <=
   2479   case OO_LessEqual: Out << "le"; break;
   2480   //              ::= ge        # >=
   2481   case OO_GreaterEqual: Out << "ge"; break;
   2482   //              ::= nt        # !
   2483   case OO_Exclaim: Out << "nt"; break;
   2484   //              ::= aa        # &&
   2485   case OO_AmpAmp: Out << "aa"; break;
   2486   //              ::= oo        # ||
   2487   case OO_PipePipe: Out << "oo"; break;
   2488   //              ::= pp        # ++
   2489   case OO_PlusPlus: Out << "pp"; break;
   2490   //              ::= mm        # --
   2491   case OO_MinusMinus: Out << "mm"; break;
   2492   //              ::= cm        # ,
   2493   case OO_Comma: Out << "cm"; break;
   2494   //              ::= pm        # ->*
   2495   case OO_ArrowStar: Out << "pm"; break;
   2496   //              ::= pt        # ->
   2497   case OO_Arrow: Out << "pt"; break;
   2498   //              ::= cl        # ()
   2499   case OO_Call: Out << "cl"; break;
   2500   //              ::= ix        # []
   2501   case OO_Subscript: Out << "ix"; break;
   2502 
   2503   //              ::= qu        # ?
   2504   // The conditional operator can't be overloaded, but we still handle it when
   2505   // mangling expressions.
   2506   case OO_Conditional: Out << "qu"; break;
   2507   // Proposal on cxx-abi-dev, 2015-10-21.
   2508   //              ::= aw        # co_await
   2509   case OO_Coawait: Out << "aw"; break;
   2510   // Proposed in cxx-abi github issue 43.
   2511   //              ::= ss        # <=>
   2512   case OO_Spaceship: Out << "ss"; break;
   2513 
   2514   case OO_None:
   2515   case NUM_OVERLOADED_OPERATORS:
   2516     llvm_unreachable("Not an overloaded operator");
   2517   }
   2518 }
   2519 
   2520 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
   2521   // Vendor qualifiers come first and if they are order-insensitive they must
   2522   // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
   2523 
   2524   // <type> ::= U <addrspace-expr>
   2525   if (DAST) {
   2526     Out << "U2ASI";
   2527     mangleExpression(DAST->getAddrSpaceExpr());
   2528     Out << "E";
   2529   }
   2530 
   2531   // Address space qualifiers start with an ordinary letter.
   2532   if (Quals.hasAddressSpace()) {
   2533     // Address space extension:
   2534     //
   2535     //   <type> ::= U <target-addrspace>
   2536     //   <type> ::= U <OpenCL-addrspace>
   2537     //   <type> ::= U <CUDA-addrspace>
   2538 
   2539     SmallString<64> ASString;
   2540     LangAS AS = Quals.getAddressSpace();
   2541 
   2542     if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
   2543       //  <target-addrspace> ::= "AS" <address-space-number>
   2544       unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
   2545       if (TargetAS != 0 ||
   2546           Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
   2547         ASString = "AS" + llvm::utostr(TargetAS);
   2548     } else {
   2549       switch (AS) {
   2550       default: llvm_unreachable("Not a language specific address space");
   2551       //  <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
   2552       //                                "private"| "generic" | "device" |
   2553       //                                "host" ]
   2554       case LangAS::opencl_global:
   2555         ASString = "CLglobal";
   2556         break;
   2557       case LangAS::opencl_global_device:
   2558         ASString = "CLdevice";
   2559         break;
   2560       case LangAS::opencl_global_host:
   2561         ASString = "CLhost";
   2562         break;
   2563       case LangAS::opencl_local:
   2564         ASString = "CLlocal";
   2565         break;
   2566       case LangAS::opencl_constant:
   2567         ASString = "CLconstant";
   2568         break;
   2569       case LangAS::opencl_private:
   2570         ASString = "CLprivate";
   2571         break;
   2572       case LangAS::opencl_generic:
   2573         ASString = "CLgeneric";
   2574         break;
   2575       //  <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
   2576       //                              "device" | "host" ]
   2577       case LangAS::sycl_global:
   2578         ASString = "SYglobal";
   2579         break;
   2580       case LangAS::sycl_global_device:
   2581         ASString = "SYdevice";
   2582         break;
   2583       case LangAS::sycl_global_host:
   2584         ASString = "SYhost";
   2585         break;
   2586       case LangAS::sycl_local:
   2587         ASString = "SYlocal";
   2588         break;
   2589       case LangAS::sycl_private:
   2590         ASString = "SYprivate";
   2591         break;
   2592       //  <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
   2593       case LangAS::cuda_device:
   2594         ASString = "CUdevice";
   2595         break;
   2596       case LangAS::cuda_constant:
   2597         ASString = "CUconstant";
   2598         break;
   2599       case LangAS::cuda_shared:
   2600         ASString = "CUshared";
   2601         break;
   2602       //  <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
   2603       case LangAS::ptr32_sptr:
   2604         ASString = "ptr32_sptr";
   2605         break;
   2606       case LangAS::ptr32_uptr:
   2607         ASString = "ptr32_uptr";
   2608         break;
   2609       case LangAS::ptr64:
   2610         ASString = "ptr64";
   2611         break;
   2612       }
   2613     }
   2614     if (!ASString.empty())
   2615       mangleVendorQualifier(ASString);
   2616   }
   2617 
   2618   // The ARC ownership qualifiers start with underscores.
   2619   // Objective-C ARC Extension:
   2620   //
   2621   //   <type> ::= U "__strong"
   2622   //   <type> ::= U "__weak"
   2623   //   <type> ::= U "__autoreleasing"
   2624   //
   2625   // Note: we emit __weak first to preserve the order as
   2626   // required by the Itanium ABI.
   2627   if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
   2628     mangleVendorQualifier("__weak");
   2629 
   2630   // __unaligned (from -fms-extensions)
   2631   if (Quals.hasUnaligned())
   2632     mangleVendorQualifier("__unaligned");
   2633 
   2634   // Remaining ARC ownership qualifiers.
   2635   switch (Quals.getObjCLifetime()) {
   2636   case Qualifiers::OCL_None:
   2637     break;
   2638 
   2639   case Qualifiers::OCL_Weak:
   2640     // Do nothing as we already handled this case above.
   2641     break;
   2642 
   2643   case Qualifiers::OCL_Strong:
   2644     mangleVendorQualifier("__strong");
   2645     break;
   2646 
   2647   case Qualifiers::OCL_Autoreleasing:
   2648     mangleVendorQualifier("__autoreleasing");
   2649     break;
   2650 
   2651   case Qualifiers::OCL_ExplicitNone:
   2652     // The __unsafe_unretained qualifier is *not* mangled, so that
   2653     // __unsafe_unretained types in ARC produce the same manglings as the
   2654     // equivalent (but, naturally, unqualified) types in non-ARC, providing
   2655     // better ABI compatibility.
   2656     //
   2657     // It's safe to do this because unqualified 'id' won't show up
   2658     // in any type signatures that need to be mangled.
   2659     break;
   2660   }
   2661 
   2662   // <CV-qualifiers> ::= [r] [V] [K]    # restrict (C99), volatile, const
   2663   if (Quals.hasRestrict())
   2664     Out << 'r';
   2665   if (Quals.hasVolatile())
   2666     Out << 'V';
   2667   if (Quals.hasConst())
   2668     Out << 'K';
   2669 }
   2670 
   2671 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
   2672   Out << 'U' << name.size() << name;
   2673 }
   2674 
   2675 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
   2676   // <ref-qualifier> ::= R                # lvalue reference
   2677   //                 ::= O                # rvalue-reference
   2678   switch (RefQualifier) {
   2679   case RQ_None:
   2680     break;
   2681 
   2682   case RQ_LValue:
   2683     Out << 'R';
   2684     break;
   2685 
   2686   case RQ_RValue:
   2687     Out << 'O';
   2688     break;
   2689   }
   2690 }
   2691 
   2692 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
   2693   Context.mangleObjCMethodNameAsSourceName(MD, Out);
   2694 }
   2695 
   2696 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
   2697                                 ASTContext &Ctx) {
   2698   if (Quals)
   2699     return true;
   2700   if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
   2701     return true;
   2702   if (Ty->isOpenCLSpecificType())
   2703     return true;
   2704   if (Ty->isBuiltinType())
   2705     return false;
   2706   // Through to Clang 6.0, we accidentally treated undeduced auto types as
   2707   // substitution candidates.
   2708   if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
   2709       isa<AutoType>(Ty))
   2710     return false;
   2711   // A placeholder type for class template deduction is substitutable with
   2712   // its corresponding template name; this is handled specially when mangling
   2713   // the type.
   2714   if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
   2715     if (DeducedTST->getDeducedType().isNull())
   2716       return false;
   2717   return true;
   2718 }
   2719 
   2720 void CXXNameMangler::mangleType(QualType T) {
   2721   // If our type is instantiation-dependent but not dependent, we mangle
   2722   // it as it was written in the source, removing any top-level sugar.
   2723   // Otherwise, use the canonical type.
   2724   //
   2725   // FIXME: This is an approximation of the instantiation-dependent name
   2726   // mangling rules, since we should really be using the type as written and
   2727   // augmented via semantic analysis (i.e., with implicit conversions and
   2728   // default template arguments) for any instantiation-dependent type.
   2729   // Unfortunately, that requires several changes to our AST:
   2730   //   - Instantiation-dependent TemplateSpecializationTypes will need to be
   2731   //     uniqued, so that we can handle substitutions properly
   2732   //   - Default template arguments will need to be represented in the
   2733   //     TemplateSpecializationType, since they need to be mangled even though
   2734   //     they aren't written.
   2735   //   - Conversions on non-type template arguments need to be expressed, since
   2736   //     they can affect the mangling of sizeof/alignof.
   2737   //
   2738   // FIXME: This is wrong when mapping to the canonical type for a dependent
   2739   // type discards instantiation-dependent portions of the type, such as for:
   2740   //
   2741   //   template<typename T, int N> void f(T (&)[sizeof(N)]);
   2742   //   template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
   2743   //
   2744   // It's also wrong in the opposite direction when instantiation-dependent,
   2745   // canonically-equivalent types differ in some irrelevant portion of inner
   2746   // type sugar. In such cases, we fail to form correct substitutions, eg:
   2747   //
   2748   //   template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
   2749   //
   2750   // We should instead canonicalize the non-instantiation-dependent parts,
   2751   // regardless of whether the type as a whole is dependent or instantiation
   2752   // dependent.
   2753   if (!T->isInstantiationDependentType() || T->isDependentType())
   2754     T = T.getCanonicalType();
   2755   else {
   2756     // Desugar any types that are purely sugar.
   2757     do {
   2758       // Don't desugar through template specialization types that aren't
   2759       // type aliases. We need to mangle the template arguments as written.
   2760       if (const TemplateSpecializationType *TST
   2761                                       = dyn_cast<TemplateSpecializationType>(T))
   2762         if (!TST->isTypeAlias())
   2763           break;
   2764 
   2765       // FIXME: We presumably shouldn't strip off ElaboratedTypes with
   2766       // instantation-dependent qualifiers. See
   2767       // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
   2768 
   2769       QualType Desugared
   2770         = T.getSingleStepDesugaredType(Context.getASTContext());
   2771       if (Desugared == T)
   2772         break;
   2773 
   2774       T = Desugared;
   2775     } while (true);
   2776   }
   2777   SplitQualType split = T.split();
   2778   Qualifiers quals = split.Quals;
   2779   const Type *ty = split.Ty;
   2780 
   2781   bool isSubstitutable =
   2782     isTypeSubstitutable(quals, ty, Context.getASTContext());
   2783   if (isSubstitutable && mangleSubstitution(T))
   2784     return;
   2785 
   2786   // If we're mangling a qualified array type, push the qualifiers to
   2787   // the element type.
   2788   if (quals && isa<ArrayType>(T)) {
   2789     ty = Context.getASTContext().getAsArrayType(T);
   2790     quals = Qualifiers();
   2791 
   2792     // Note that we don't update T: we want to add the
   2793     // substitution at the original type.
   2794   }
   2795 
   2796   if (quals || ty->isDependentAddressSpaceType()) {
   2797     if (const DependentAddressSpaceType *DAST =
   2798         dyn_cast<DependentAddressSpaceType>(ty)) {
   2799       SplitQualType splitDAST = DAST->getPointeeType().split();
   2800       mangleQualifiers(splitDAST.Quals, DAST);
   2801       mangleType(QualType(splitDAST.Ty, 0));
   2802     } else {
   2803       mangleQualifiers(quals);
   2804 
   2805       // Recurse:  even if the qualified type isn't yet substitutable,
   2806       // the unqualified type might be.
   2807       mangleType(QualType(ty, 0));
   2808     }
   2809   } else {
   2810     switch (ty->getTypeClass()) {
   2811 #define ABSTRACT_TYPE(CLASS, PARENT)
   2812 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
   2813     case Type::CLASS: \
   2814       llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
   2815       return;
   2816 #define TYPE(CLASS, PARENT) \
   2817     case Type::CLASS: \
   2818       mangleType(static_cast<const CLASS##Type*>(ty)); \
   2819       break;
   2820 #include "clang/AST/TypeNodes.inc"
   2821     }
   2822   }
   2823 
   2824   // Add the substitution.
   2825   if (isSubstitutable)
   2826     addSubstitution(T);
   2827 }
   2828 
   2829 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
   2830   if (!mangleStandardSubstitution(ND))
   2831     mangleName(ND);
   2832 }
   2833 
   2834 void CXXNameMangler::mangleType(const BuiltinType *T) {
   2835   //  <type>         ::= <builtin-type>
   2836   //  <builtin-type> ::= v  # void
   2837   //                 ::= w  # wchar_t
   2838   //                 ::= b  # bool
   2839   //                 ::= c  # char
   2840   //                 ::= a  # signed char
   2841   //                 ::= h  # unsigned char
   2842   //                 ::= s  # short
   2843   //                 ::= t  # unsigned short
   2844   //                 ::= i  # int
   2845   //                 ::= j  # unsigned int
   2846   //                 ::= l  # long
   2847   //                 ::= m  # unsigned long
   2848   //                 ::= x  # long long, __int64
   2849   //                 ::= y  # unsigned long long, __int64
   2850   //                 ::= n  # __int128
   2851   //                 ::= o  # unsigned __int128
   2852   //                 ::= f  # float
   2853   //                 ::= d  # double
   2854   //                 ::= e  # long double, __float80
   2855   //                 ::= g  # __float128
   2856   // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)
   2857   // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)
   2858   // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)
   2859   //                 ::= Dh # IEEE 754r half-precision floating point (16 bits)
   2860   //                 ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
   2861   //                 ::= Di # char32_t
   2862   //                 ::= Ds # char16_t
   2863   //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
   2864   //                 ::= u <source-name>    # vendor extended type
   2865   std::string type_name;
   2866   switch (T->getKind()) {
   2867   case BuiltinType::Void:
   2868     Out << 'v';
   2869     break;
   2870   case BuiltinType::Bool:
   2871     Out << 'b';
   2872     break;
   2873   case BuiltinType::Char_U:
   2874   case BuiltinType::Char_S:
   2875     Out << 'c';
   2876     break;
   2877   case BuiltinType::UChar:
   2878     Out << 'h';
   2879     break;
   2880   case BuiltinType::UShort:
   2881     Out << 't';
   2882     break;
   2883   case BuiltinType::UInt:
   2884     Out << 'j';
   2885     break;
   2886   case BuiltinType::ULong:
   2887     Out << 'm';
   2888     break;
   2889   case BuiltinType::ULongLong:
   2890     Out << 'y';
   2891     break;
   2892   case BuiltinType::UInt128:
   2893     Out << 'o';
   2894     break;
   2895   case BuiltinType::SChar:
   2896     Out << 'a';
   2897     break;
   2898   case BuiltinType::WChar_S:
   2899   case BuiltinType::WChar_U:
   2900     Out << 'w';
   2901     break;
   2902   case BuiltinType::Char8:
   2903     Out << "Du";
   2904     break;
   2905   case BuiltinType::Char16:
   2906     Out << "Ds";
   2907     break;
   2908   case BuiltinType::Char32:
   2909     Out << "Di";
   2910     break;
   2911   case BuiltinType::Short:
   2912     Out << 's';
   2913     break;
   2914   case BuiltinType::Int:
   2915     Out << 'i';
   2916     break;
   2917   case BuiltinType::Long:
   2918     Out << 'l';
   2919     break;
   2920   case BuiltinType::LongLong:
   2921     Out << 'x';
   2922     break;
   2923   case BuiltinType::Int128:
   2924     Out << 'n';
   2925     break;
   2926   case BuiltinType::Float16:
   2927     Out << "DF16_";
   2928     break;
   2929   case BuiltinType::ShortAccum:
   2930   case BuiltinType::Accum:
   2931   case BuiltinType::LongAccum:
   2932   case BuiltinType::UShortAccum:
   2933   case BuiltinType::UAccum:
   2934   case BuiltinType::ULongAccum:
   2935   case BuiltinType::ShortFract:
   2936   case BuiltinType::Fract:
   2937   case BuiltinType::LongFract:
   2938   case BuiltinType::UShortFract:
   2939   case BuiltinType::UFract:
   2940   case BuiltinType::ULongFract:
   2941   case BuiltinType::SatShortAccum:
   2942   case BuiltinType::SatAccum:
   2943   case BuiltinType::SatLongAccum:
   2944   case BuiltinType::SatUShortAccum:
   2945   case BuiltinType::SatUAccum:
   2946   case BuiltinType::SatULongAccum:
   2947   case BuiltinType::SatShortFract:
   2948   case BuiltinType::SatFract:
   2949   case BuiltinType::SatLongFract:
   2950   case BuiltinType::SatUShortFract:
   2951   case BuiltinType::SatUFract:
   2952   case BuiltinType::SatULongFract:
   2953     llvm_unreachable("Fixed point types are disabled for c++");
   2954   case BuiltinType::Half:
   2955     Out << "Dh";
   2956     break;
   2957   case BuiltinType::Float:
   2958     Out << 'f';
   2959     break;
   2960   case BuiltinType::Double:
   2961     Out << 'd';
   2962     break;
   2963   case BuiltinType::LongDouble: {
   2964     const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
   2965                                    getASTContext().getLangOpts().OpenMPIsDevice
   2966                                ? getASTContext().getAuxTargetInfo()
   2967                                : &getASTContext().getTargetInfo();
   2968     Out << TI->getLongDoubleMangling();
   2969     break;
   2970   }
   2971   case BuiltinType::Float128: {
   2972     const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
   2973                                    getASTContext().getLangOpts().OpenMPIsDevice
   2974                                ? getASTContext().getAuxTargetInfo()
   2975                                : &getASTContext().getTargetInfo();
   2976     Out << TI->getFloat128Mangling();
   2977     break;
   2978   }
   2979   case BuiltinType::BFloat16: {
   2980     const TargetInfo *TI = &getASTContext().getTargetInfo();
   2981     Out << TI->getBFloat16Mangling();
   2982     break;
   2983   }
   2984   case BuiltinType::NullPtr:
   2985     Out << "Dn";
   2986     break;
   2987 
   2988 #define BUILTIN_TYPE(Id, SingletonId)
   2989 #define PLACEHOLDER_TYPE(Id, SingletonId) \
   2990   case BuiltinType::Id:
   2991 #include "clang/AST/BuiltinTypes.def"
   2992   case BuiltinType::Dependent:
   2993     if (!NullOut)
   2994       llvm_unreachable("mangling a placeholder type");
   2995     break;
   2996   case BuiltinType::ObjCId:
   2997     Out << "11objc_object";
   2998     break;
   2999   case BuiltinType::ObjCClass:
   3000     Out << "10objc_class";
   3001     break;
   3002   case BuiltinType::ObjCSel:
   3003     Out << "13objc_selector";
   3004     break;
   3005 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
   3006   case BuiltinType::Id: \
   3007     type_name = "ocl_" #ImgType "_" #Suffix; \
   3008     Out << type_name.size() << type_name; \
   3009     break;
   3010 #include "clang/Basic/OpenCLImageTypes.def"
   3011   case BuiltinType::OCLSampler:
   3012     Out << "11ocl_sampler";
   3013     break;
   3014   case BuiltinType::OCLEvent:
   3015     Out << "9ocl_event";
   3016     break;
   3017   case BuiltinType::OCLClkEvent:
   3018     Out << "12ocl_clkevent";
   3019     break;
   3020   case BuiltinType::OCLQueue:
   3021     Out << "9ocl_queue";
   3022     break;
   3023   case BuiltinType::OCLReserveID:
   3024     Out << "13ocl_reserveid";
   3025     break;
   3026 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
   3027   case BuiltinType::Id: \
   3028     type_name = "ocl_" #ExtType; \
   3029     Out << type_name.size() << type_name; \
   3030     break;
   3031 #include "clang/Basic/OpenCLExtensionTypes.def"
   3032   // The SVE types are effectively target-specific.  The mangling scheme
   3033   // is defined in the appendices to the Procedure Call Standard for the
   3034   // Arm Architecture.
   3035 #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls,    \
   3036                         ElBits, IsSigned, IsFP, IsBF)                          \
   3037   case BuiltinType::Id:                                                        \
   3038     type_name = MangledName;                                                   \
   3039     Out << (type_name == InternalName ? "u" : "") << type_name.size()          \
   3040         << type_name;                                                          \
   3041     break;
   3042 #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
   3043   case BuiltinType::Id:                                                        \
   3044     type_name = MangledName;                                                   \
   3045     Out << (type_name == InternalName ? "u" : "") << type_name.size()          \
   3046         << type_name;                                                          \
   3047     break;
   3048 #include "clang/Basic/AArch64SVEACLETypes.def"
   3049 #define PPC_VECTOR_TYPE(Name, Id, Size) \
   3050   case BuiltinType::Id: \
   3051     type_name = #Name; \
   3052     Out << 'u' << type_name.size() << type_name; \
   3053     break;
   3054 #include "clang/Basic/PPCTypes.def"
   3055     // TODO: Check the mangling scheme for RISC-V V.
   3056 #define RVV_TYPE(Name, Id, SingletonId)                                        \
   3057   case BuiltinType::Id:                                                        \
   3058     type_name = Name;                                                          \
   3059     Out << 'u' << type_name.size() << type_name;                               \
   3060     break;
   3061 #include "clang/Basic/RISCVVTypes.def"
   3062   }
   3063 }
   3064 
   3065 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
   3066   switch (CC) {
   3067   case CC_C:
   3068     return "";
   3069 
   3070   case CC_X86VectorCall:
   3071   case CC_X86Pascal:
   3072   case CC_X86RegCall:
   3073   case CC_AAPCS:
   3074   case CC_AAPCS_VFP:
   3075   case CC_AArch64VectorCall:
   3076   case CC_IntelOclBicc:
   3077   case CC_SpirFunction:
   3078   case CC_OpenCLKernel:
   3079   case CC_PreserveMost:
   3080   case CC_PreserveAll:
   3081     // FIXME: we should be mangling all of the above.
   3082     return "";
   3083 
   3084   case CC_X86ThisCall:
   3085     // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
   3086     // used explicitly. At this point, we don't have that much information in
   3087     // the AST, since clang tends to bake the convention into the canonical
   3088     // function type. thiscall only rarely used explicitly, so don't mangle it
   3089     // for now.
   3090     return "";
   3091 
   3092   case CC_X86StdCall:
   3093     return "stdcall";
   3094   case CC_X86FastCall:
   3095     return "fastcall";
   3096   case CC_X86_64SysV:
   3097     return "sysv_abi";
   3098   case CC_Win64:
   3099     return "ms_abi";
   3100   case CC_Swift:
   3101     return "swiftcall";
   3102   }
   3103   llvm_unreachable("bad calling convention");
   3104 }
   3105 
   3106 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
   3107   // Fast path.
   3108   if (T->getExtInfo() == FunctionType::ExtInfo())
   3109     return;
   3110 
   3111   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
   3112   // This will get more complicated in the future if we mangle other
   3113   // things here; but for now, since we mangle ns_returns_retained as
   3114   // a qualifier on the result type, we can get away with this:
   3115   StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
   3116   if (!CCQualifier.empty())
   3117     mangleVendorQualifier(CCQualifier);
   3118 
   3119   // FIXME: regparm
   3120   // FIXME: noreturn
   3121 }
   3122 
   3123 void
   3124 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
   3125   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
   3126 
   3127   // Note that these are *not* substitution candidates.  Demanglers might
   3128   // have trouble with this if the parameter type is fully substituted.
   3129 
   3130   switch (PI.getABI()) {
   3131   case ParameterABI::Ordinary:
   3132     break;
   3133 
   3134   // All of these start with "swift", so they come before "ns_consumed".
   3135   case ParameterABI::SwiftContext:
   3136   case ParameterABI::SwiftErrorResult:
   3137   case ParameterABI::SwiftIndirectResult:
   3138     mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
   3139     break;
   3140   }
   3141 
   3142   if (PI.isConsumed())
   3143     mangleVendorQualifier("ns_consumed");
   3144 
   3145   if (PI.isNoEscape())
   3146     mangleVendorQualifier("noescape");
   3147 }
   3148 
   3149 // <type>          ::= <function-type>
   3150 // <function-type> ::= [<CV-qualifiers>] F [Y]
   3151 //                      <bare-function-type> [<ref-qualifier>] E
   3152 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
   3153   mangleExtFunctionInfo(T);
   3154 
   3155   // Mangle CV-qualifiers, if present.  These are 'this' qualifiers,
   3156   // e.g. "const" in "int (A::*)() const".
   3157   mangleQualifiers(T->getMethodQuals());
   3158 
   3159   // Mangle instantiation-dependent exception-specification, if present,
   3160   // per cxx-abi-dev proposal on 2016-10-11.
   3161   if (T->hasInstantiationDependentExceptionSpec()) {
   3162     if (isComputedNoexcept(T->getExceptionSpecType())) {
   3163       Out << "DO";
   3164       mangleExpression(T->getNoexceptExpr());
   3165       Out << "E";
   3166     } else {
   3167       assert(T->getExceptionSpecType() == EST_Dynamic);
   3168       Out << "Dw";
   3169       for (auto ExceptTy : T->exceptions())
   3170         mangleType(ExceptTy);
   3171       Out << "E";
   3172     }
   3173   } else if (T->isNothrow()) {
   3174     Out << "Do";
   3175   }
   3176 
   3177   Out << 'F';
   3178 
   3179   // FIXME: We don't have enough information in the AST to produce the 'Y'
   3180   // encoding for extern "C" function types.
   3181   mangleBareFunctionType(T, /*MangleReturnType=*/true);
   3182 
   3183   // Mangle the ref-qualifier, if present.
   3184   mangleRefQualifier(T->getRefQualifier());
   3185 
   3186   Out << 'E';
   3187 }
   3188 
   3189 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
   3190   // Function types without prototypes can arise when mangling a function type
   3191   // within an overloadable function in C. We mangle these as the absence of any
   3192   // parameter types (not even an empty parameter list).
   3193   Out << 'F';
   3194 
   3195   FunctionTypeDepthState saved = FunctionTypeDepth.push();
   3196 
   3197   FunctionTypeDepth.enterResultType();
   3198   mangleType(T->getReturnType());
   3199   FunctionTypeDepth.leaveResultType();
   3200 
   3201   FunctionTypeDepth.pop(saved);
   3202   Out << 'E';
   3203 }
   3204 
   3205 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
   3206                                             bool MangleReturnType,
   3207                                             const FunctionDecl *FD) {
   3208   // Record that we're in a function type.  See mangleFunctionParam
   3209   // for details on what we're trying to achieve here.
   3210   FunctionTypeDepthState saved = FunctionTypeDepth.push();
   3211 
   3212   // <bare-function-type> ::= <signature type>+
   3213   if (MangleReturnType) {
   3214     FunctionTypeDepth.enterResultType();
   3215 
   3216     // Mangle ns_returns_retained as an order-sensitive qualifier here.
   3217     if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
   3218       mangleVendorQualifier("ns_returns_retained");
   3219 
   3220     // Mangle the return type without any direct ARC ownership qualifiers.
   3221     QualType ReturnTy = Proto->getReturnType();
   3222     if (ReturnTy.getObjCLifetime()) {
   3223       auto SplitReturnTy = ReturnTy.split();
   3224       SplitReturnTy.Quals.removeObjCLifetime();
   3225       ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
   3226     }
   3227     mangleType(ReturnTy);
   3228 
   3229     FunctionTypeDepth.leaveResultType();
   3230   }
   3231 
   3232   if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
   3233     //   <builtin-type> ::= v   # void
   3234     Out << 'v';
   3235 
   3236     FunctionTypeDepth.pop(saved);
   3237     return;
   3238   }
   3239 
   3240   assert(!FD || FD->getNumParams() == Proto->getNumParams());
   3241   for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
   3242     // Mangle extended parameter info as order-sensitive qualifiers here.
   3243     if (Proto->hasExtParameterInfos() && FD == nullptr) {
   3244       mangleExtParameterInfo(Proto->getExtParameterInfo(I));
   3245     }
   3246 
   3247     // Mangle the type.
   3248     QualType ParamTy = Proto->getParamType(I);
   3249     mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
   3250 
   3251     if (FD) {
   3252       if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
   3253         // Attr can only take 1 character, so we can hardcode the length below.
   3254         assert(Attr->getType() <= 9 && Attr->getType() >= 0);
   3255         if (Attr->isDynamic())
   3256           Out << "U25pass_dynamic_object_size" << Attr->getType();
   3257         else
   3258           Out << "U17pass_object_size" << Attr->getType();
   3259       }
   3260     }
   3261   }
   3262 
   3263   FunctionTypeDepth.pop(saved);
   3264 
   3265   // <builtin-type>      ::= z  # ellipsis
   3266   if (Proto->isVariadic())
   3267     Out << 'z';
   3268 }
   3269 
   3270 // <type>            ::= <class-enum-type>
   3271 // <class-enum-type> ::= <name>
   3272 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
   3273   mangleName(T->getDecl());
   3274 }
   3275 
   3276 // <type>            ::= <class-enum-type>
   3277 // <class-enum-type> ::= <name>
   3278 void CXXNameMangler::mangleType(const EnumType *T) {
   3279   mangleType(static_cast<const TagType*>(T));
   3280 }
   3281 void CXXNameMangler::mangleType(const RecordType *T) {
   3282   mangleType(static_cast<const TagType*>(T));
   3283 }
   3284 void CXXNameMangler::mangleType(const TagType *T) {
   3285   mangleName(T->getDecl());
   3286 }
   3287 
   3288 // <type>       ::= <array-type>
   3289 // <array-type> ::= A <positive dimension number> _ <element type>
   3290 //              ::= A [<dimension expression>] _ <element type>
   3291 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
   3292   Out << 'A' << T->getSize() << '_';
   3293   mangleType(T->getElementType());
   3294 }
   3295 void CXXNameMangler::mangleType(const VariableArrayType *T) {
   3296   Out << 'A';
   3297   // decayed vla types (size 0) will just be skipped.
   3298   if (T->getSizeExpr())
   3299     mangleExpression(T->getSizeExpr());
   3300   Out << '_';
   3301   mangleType(T->getElementType());
   3302 }
   3303 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
   3304   Out << 'A';
   3305   // A DependentSizedArrayType might not have size expression as below
   3306   //
   3307   // template<int ...N> int arr[] = {N...};
   3308   if (T->getSizeExpr())
   3309     mangleExpression(T->getSizeExpr());
   3310   Out << '_';
   3311   mangleType(T->getElementType());
   3312 }
   3313 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
   3314   Out << "A_";
   3315   mangleType(T->getElementType());
   3316 }
   3317 
   3318 // <type>                   ::= <pointer-to-member-type>
   3319 // <pointer-to-member-type> ::= M <class type> <member type>
   3320 void CXXNameMangler::mangleType(const MemberPointerType *T) {
   3321   Out << 'M';
   3322   mangleType(QualType(T->getClass(), 0));
   3323   QualType PointeeType = T->getPointeeType();
   3324   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
   3325     mangleType(FPT);
   3326 
   3327     // Itanium C++ ABI 5.1.8:
   3328     //
   3329     //   The type of a non-static member function is considered to be different,
   3330     //   for the purposes of substitution, from the type of a namespace-scope or
   3331     //   static member function whose type appears similar. The types of two
   3332     //   non-static member functions are considered to be different, for the
   3333     //   purposes of substitution, if the functions are members of different
   3334     //   classes. In other words, for the purposes of substitution, the class of
   3335     //   which the function is a member is considered part of the type of
   3336     //   function.
   3337 
   3338     // Given that we already substitute member function pointers as a
   3339     // whole, the net effect of this rule is just to unconditionally
   3340     // suppress substitution on the function type in a member pointer.
   3341     // We increment the SeqID here to emulate adding an entry to the
   3342     // substitution table.
   3343     ++SeqID;
   3344   } else
   3345     mangleType(PointeeType);
   3346 }
   3347 
   3348 // <type>           ::= <template-param>
   3349 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
   3350   mangleTemplateParameter(T->getDepth(), T->getIndex());
   3351 }
   3352 
   3353 // <type>           ::= <template-param>
   3354 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
   3355   // FIXME: not clear how to mangle this!
   3356   // template <class T...> class A {
   3357   //   template <class U...> void foo(T(*)(U) x...);
   3358   // };
   3359   Out << "_SUBSTPACK_";
   3360 }
   3361 
   3362 // <type> ::= P <type>   # pointer-to
   3363 void CXXNameMangler::mangleType(const PointerType *T) {
   3364   Out << 'P';
   3365   mangleType(T->getPointeeType());
   3366 }
   3367 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
   3368   Out << 'P';
   3369   mangleType(T->getPointeeType());
   3370 }
   3371 
   3372 // <type> ::= R <type>   # reference-to
   3373 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
   3374   Out << 'R';
   3375   mangleType(T->getPointeeType());
   3376 }
   3377 
   3378 // <type> ::= O <type>   # rvalue reference-to (C++0x)
   3379 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
   3380   Out << 'O';
   3381   mangleType(T->getPointeeType());
   3382 }
   3383 
   3384 // <type> ::= C <type>   # complex pair (C 2000)
   3385 void CXXNameMangler::mangleType(const ComplexType *T) {
   3386   Out << 'C';
   3387   mangleType(T->getElementType());
   3388 }
   3389 
   3390 // ARM's ABI for Neon vector types specifies that they should be mangled as
   3391 // if they are structs (to match ARM's initial implementation).  The
   3392 // vector type must be one of the special types predefined by ARM.
   3393 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
   3394   QualType EltType = T->getElementType();
   3395   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
   3396   const char *EltName = nullptr;
   3397   if (T->getVectorKind() == VectorType::NeonPolyVector) {
   3398     switch (cast<BuiltinType>(EltType)->getKind()) {
   3399     case BuiltinType::SChar:
   3400     case BuiltinType::UChar:
   3401       EltName = "poly8_t";
   3402       break;
   3403     case BuiltinType::Short:
   3404     case BuiltinType::UShort:
   3405       EltName = "poly16_t";
   3406       break;
   3407     case BuiltinType::LongLong:
   3408     case BuiltinType::ULongLong:
   3409       EltName = "poly64_t";
   3410       break;
   3411     default: llvm_unreachable("unexpected Neon polynomial vector element type");
   3412     }
   3413   } else {
   3414     switch (cast<BuiltinType>(EltType)->getKind()) {
   3415     case BuiltinType::SChar:     EltName = "int8_t"; break;
   3416     case BuiltinType::UChar:     EltName = "uint8_t"; break;
   3417     case BuiltinType::Short:     EltName = "int16_t"; break;
   3418     case BuiltinType::UShort:    EltName = "uint16_t"; break;
   3419     case BuiltinType::Int:       EltName = "int32_t"; break;
   3420     case BuiltinType::UInt:      EltName = "uint32_t"; break;
   3421     case BuiltinType::LongLong:  EltName = "int64_t"; break;
   3422     case BuiltinType::ULongLong: EltName = "uint64_t"; break;
   3423     case BuiltinType::Double:    EltName = "float64_t"; break;
   3424     case BuiltinType::Float:     EltName = "float32_t"; break;
   3425     case BuiltinType::Half:      EltName = "float16_t"; break;
   3426     case BuiltinType::BFloat16:  EltName = "bfloat16_t"; break;
   3427     default:
   3428       llvm_unreachable("unexpected Neon vector element type");
   3429     }
   3430   }
   3431   const char *BaseName = nullptr;
   3432   unsigned BitSize = (T->getNumElements() *
   3433                       getASTContext().getTypeSize(EltType));
   3434   if (BitSize == 64)
   3435     BaseName = "__simd64_";
   3436   else {
   3437     assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
   3438     BaseName = "__simd128_";
   3439   }
   3440   Out << strlen(BaseName) + strlen(EltName);
   3441   Out << BaseName << EltName;
   3442 }
   3443 
   3444 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
   3445   DiagnosticsEngine &Diags = Context.getDiags();
   3446   unsigned DiagID = Diags.getCustomDiagID(
   3447       DiagnosticsEngine::Error,
   3448       "cannot mangle this dependent neon vector type yet");
   3449   Diags.Report(T->getAttributeLoc(), DiagID);
   3450 }
   3451 
   3452 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
   3453   switch (EltType->getKind()) {
   3454   case BuiltinType::SChar:
   3455     return "Int8";
   3456   case BuiltinType::Short:
   3457     return "Int16";
   3458   case BuiltinType::Int:
   3459     return "Int32";
   3460   case BuiltinType::Long:
   3461   case BuiltinType::LongLong:
   3462     return "Int64";
   3463   case BuiltinType::UChar:
   3464     return "Uint8";
   3465   case BuiltinType::UShort:
   3466     return "Uint16";
   3467   case BuiltinType::UInt:
   3468     return "Uint32";
   3469   case BuiltinType::ULong:
   3470   case BuiltinType::ULongLong:
   3471     return "Uint64";
   3472   case BuiltinType::Half:
   3473     return "Float16";
   3474   case BuiltinType::Float:
   3475     return "Float32";
   3476   case BuiltinType::Double:
   3477     return "Float64";
   3478   case BuiltinType::BFloat16:
   3479     return "Bfloat16";
   3480   default:
   3481     llvm_unreachable("Unexpected vector element base type");
   3482   }
   3483 }
   3484 
   3485 // AArch64's ABI for Neon vector types specifies that they should be mangled as
   3486 // the equivalent internal name. The vector type must be one of the special
   3487 // types predefined by ARM.
   3488 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
   3489   QualType EltType = T->getElementType();
   3490   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
   3491   unsigned BitSize =
   3492       (T->getNumElements() * getASTContext().getTypeSize(EltType));
   3493   (void)BitSize; // Silence warning.
   3494 
   3495   assert((BitSize == 64 || BitSize == 128) &&
   3496          "Neon vector type not 64 or 128 bits");
   3497 
   3498   StringRef EltName;
   3499   if (T->getVectorKind() == VectorType::NeonPolyVector) {
   3500     switch (cast<BuiltinType>(EltType)->getKind()) {
   3501     case BuiltinType::UChar:
   3502       EltName = "Poly8";
   3503       break;
   3504     case BuiltinType::UShort:
   3505       EltName = "Poly16";
   3506       break;
   3507     case BuiltinType::ULong:
   3508     case BuiltinType::ULongLong:
   3509       EltName = "Poly64";
   3510       break;
   3511     default:
   3512       llvm_unreachable("unexpected Neon polynomial vector element type");
   3513     }
   3514   } else
   3515     EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
   3516 
   3517   std::string TypeName =
   3518       ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
   3519   Out << TypeName.length() << TypeName;
   3520 }
   3521 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
   3522   DiagnosticsEngine &Diags = Context.getDiags();
   3523   unsigned DiagID = Diags.getCustomDiagID(
   3524       DiagnosticsEngine::Error,
   3525       "cannot mangle this dependent neon vector type yet");
   3526   Diags.Report(T->getAttributeLoc(), DiagID);
   3527 }
   3528 
   3529 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
   3530 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
   3531 // type as the sizeless variants.
   3532 //
   3533 // The mangling scheme for VLS types is implemented as a "pseudo" template:
   3534 //
   3535 //   '__SVE_VLS<<type>, <vector length>>'
   3536 //
   3537 // Combining the existing SVE type and a specific vector length (in bits).
   3538 // For example:
   3539 //
   3540 //   typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
   3541 //
   3542 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
   3543 //
   3544 //   "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
   3545 //
   3546 //   i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
   3547 //
   3548 // The latest ACLE specification (00bet5) does not contain details of this
   3549 // mangling scheme, it will be specified in the next revision. The mangling
   3550 // scheme is otherwise defined in the appendices to the Procedure Call Standard
   3551 // for the Arm Architecture, see
   3552 // https://github.com/ARM-software/abi-aa/blob/master/aapcs64/aapcs64.rst#appendix-c-mangling
   3553 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
   3554   assert((T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
   3555           T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) &&
   3556          "expected fixed-length SVE vector!");
   3557 
   3558   QualType EltType = T->getElementType();
   3559   assert(EltType->isBuiltinType() &&
   3560          "expected builtin type for fixed-length SVE vector!");
   3561 
   3562   StringRef TypeName;
   3563   switch (cast<BuiltinType>(EltType)->getKind()) {
   3564   case BuiltinType::SChar:
   3565     TypeName = "__SVInt8_t";
   3566     break;
   3567   case BuiltinType::UChar: {
   3568     if (T->getVectorKind() == VectorType::SveFixedLengthDataVector)
   3569       TypeName = "__SVUint8_t";
   3570     else
   3571       TypeName = "__SVBool_t";
   3572     break;
   3573   }
   3574   case BuiltinType::Short:
   3575     TypeName = "__SVInt16_t";
   3576     break;
   3577   case BuiltinType::UShort:
   3578     TypeName = "__SVUint16_t";
   3579     break;
   3580   case BuiltinType::Int:
   3581     TypeName = "__SVInt32_t";
   3582     break;
   3583   case BuiltinType::UInt:
   3584     TypeName = "__SVUint32_t";
   3585     break;
   3586   case BuiltinType::Long:
   3587     TypeName = "__SVInt64_t";
   3588     break;
   3589   case BuiltinType::ULong:
   3590     TypeName = "__SVUint64_t";
   3591     break;
   3592   case BuiltinType::Half:
   3593     TypeName = "__SVFloat16_t";
   3594     break;
   3595   case BuiltinType::Float:
   3596     TypeName = "__SVFloat32_t";
   3597     break;
   3598   case BuiltinType::Double:
   3599     TypeName = "__SVFloat64_t";
   3600     break;
   3601   case BuiltinType::BFloat16:
   3602     TypeName = "__SVBfloat16_t";
   3603     break;
   3604   default:
   3605     llvm_unreachable("unexpected element type for fixed-length SVE vector!");
   3606   }
   3607 
   3608   unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
   3609 
   3610   if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
   3611     VecSizeInBits *= 8;
   3612 
   3613   Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
   3614       << VecSizeInBits << "EE";
   3615 }
   3616 
   3617 void CXXNameMangler::mangleAArch64FixedSveVectorType(
   3618     const DependentVectorType *T) {
   3619   DiagnosticsEngine &Diags = Context.getDiags();
   3620   unsigned DiagID = Diags.getCustomDiagID(
   3621       DiagnosticsEngine::Error,
   3622       "cannot mangle this dependent fixed-length SVE vector type yet");
   3623   Diags.Report(T->getAttributeLoc(), DiagID);
   3624 }
   3625 
   3626 // GNU extension: vector types
   3627 // <type>                  ::= <vector-type>
   3628 // <vector-type>           ::= Dv <positive dimension number> _
   3629 //                                    <extended element type>
   3630 //                         ::= Dv [<dimension expression>] _ <element type>
   3631 // <extended element type> ::= <element type>
   3632 //                         ::= p # AltiVec vector pixel
   3633 //                         ::= b # Altivec vector bool
   3634 void CXXNameMangler::mangleType(const VectorType *T) {
   3635   if ((T->getVectorKind() == VectorType::NeonVector ||
   3636        T->getVectorKind() == VectorType::NeonPolyVector)) {
   3637     llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
   3638     llvm::Triple::ArchType Arch =
   3639         getASTContext().getTargetInfo().getTriple().getArch();
   3640     if ((Arch == llvm::Triple::aarch64 ||
   3641          Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
   3642       mangleAArch64NeonVectorType(T);
   3643     else
   3644       mangleNeonVectorType(T);
   3645     return;
   3646   } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
   3647              T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
   3648     mangleAArch64FixedSveVectorType(T);
   3649     return;
   3650   }
   3651   Out << "Dv" << T->getNumElements() << '_';
   3652   if (T->getVectorKind() == VectorType::AltiVecPixel)
   3653     Out << 'p';
   3654   else if (T->getVectorKind() == VectorType::AltiVecBool)
   3655     Out << 'b';
   3656   else
   3657     mangleType(T->getElementType());
   3658 }
   3659 
   3660 void CXXNameMangler::mangleType(const DependentVectorType *T) {
   3661   if ((T->getVectorKind() == VectorType::NeonVector ||
   3662        T->getVectorKind() == VectorType::NeonPolyVector)) {
   3663     llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
   3664     llvm::Triple::ArchType Arch =
   3665         getASTContext().getTargetInfo().getTriple().getArch();
   3666     if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
   3667         !Target.isOSDarwin())
   3668       mangleAArch64NeonVectorType(T);
   3669     else
   3670       mangleNeonVectorType(T);
   3671     return;
   3672   } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
   3673              T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
   3674     mangleAArch64FixedSveVectorType(T);
   3675     return;
   3676   }
   3677 
   3678   Out << "Dv";
   3679   mangleExpression(T->getSizeExpr());
   3680   Out << '_';
   3681   if (T->getVectorKind() == VectorType::AltiVecPixel)
   3682     Out << 'p';
   3683   else if (T->getVectorKind() == VectorType::AltiVecBool)
   3684     Out << 'b';
   3685   else
   3686     mangleType(T->getElementType());
   3687 }
   3688 
   3689 void CXXNameMangler::mangleType(const ExtVectorType *T) {
   3690   mangleType(static_cast<const VectorType*>(T));
   3691 }
   3692 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
   3693   Out << "Dv";
   3694   mangleExpression(T->getSizeExpr());
   3695   Out << '_';
   3696   mangleType(T->getElementType());
   3697 }
   3698 
   3699 void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
   3700   // Mangle matrix types as a vendor extended type:
   3701   // u<Len>matrix_typeI<Rows><Columns><element type>E
   3702 
   3703   StringRef VendorQualifier = "matrix_type";
   3704   Out << "u" << VendorQualifier.size() << VendorQualifier;
   3705 
   3706   Out << "I";
   3707   auto &ASTCtx = getASTContext();
   3708   unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
   3709   llvm::APSInt Rows(BitWidth);
   3710   Rows = T->getNumRows();
   3711   mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
   3712   llvm::APSInt Columns(BitWidth);
   3713   Columns = T->getNumColumns();
   3714   mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
   3715   mangleType(T->getElementType());
   3716   Out << "E";
   3717 }
   3718 
   3719 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
   3720   // Mangle matrix types as a vendor extended type:
   3721   // u<Len>matrix_typeI<row expr><column expr><element type>E
   3722   StringRef VendorQualifier = "matrix_type";
   3723   Out << "u" << VendorQualifier.size() << VendorQualifier;
   3724 
   3725   Out << "I";
   3726   mangleTemplateArgExpr(T->getRowExpr());
   3727   mangleTemplateArgExpr(T->getColumnExpr());
   3728   mangleType(T->getElementType());
   3729   Out << "E";
   3730 }
   3731 
   3732 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
   3733   SplitQualType split = T->getPointeeType().split();
   3734   mangleQualifiers(split.Quals, T);
   3735   mangleType(QualType(split.Ty, 0));
   3736 }
   3737 
   3738 void CXXNameMangler::mangleType(const PackExpansionType *T) {
   3739   // <type>  ::= Dp <type>          # pack expansion (C++0x)
   3740   Out << "Dp";
   3741   mangleType(T->getPattern());
   3742 }
   3743 
   3744 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
   3745   mangleSourceName(T->getDecl()->getIdentifier());
   3746 }
   3747 
   3748 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
   3749   // Treat __kindof as a vendor extended type qualifier.
   3750   if (T->isKindOfType())
   3751     Out << "U8__kindof";
   3752 
   3753   if (!T->qual_empty()) {
   3754     // Mangle protocol qualifiers.
   3755     SmallString<64> QualStr;
   3756     llvm::raw_svector_ostream QualOS(QualStr);
   3757     QualOS << "objcproto";
   3758     for (const auto *I : T->quals()) {
   3759       StringRef name = I->getName();
   3760       QualOS << name.size() << name;
   3761     }
   3762     Out << 'U' << QualStr.size() << QualStr;
   3763   }
   3764 
   3765   mangleType(T->getBaseType());
   3766 
   3767   if (T->isSpecialized()) {
   3768     // Mangle type arguments as I <type>+ E
   3769     Out << 'I';
   3770     for (auto typeArg : T->getTypeArgs())
   3771       mangleType(typeArg);
   3772     Out << 'E';
   3773   }
   3774 }
   3775 
   3776 void CXXNameMangler::mangleType(const BlockPointerType *T) {
   3777   Out << "U13block_pointer";
   3778   mangleType(T->getPointeeType());
   3779 }
   3780 
   3781 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
   3782   // Mangle injected class name types as if the user had written the
   3783   // specialization out fully.  It may not actually be possible to see
   3784   // this mangling, though.
   3785   mangleType(T->getInjectedSpecializationType());
   3786 }
   3787 
   3788 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
   3789   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
   3790     mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
   3791   } else {
   3792     if (mangleSubstitution(QualType(T, 0)))
   3793       return;
   3794 
   3795     mangleTemplatePrefix(T->getTemplateName());
   3796 
   3797     // FIXME: GCC does not appear to mangle the template arguments when
   3798     // the template in question is a dependent template name. Should we
   3799     // emulate that badness?
   3800     mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs());
   3801     addSubstitution(QualType(T, 0));
   3802   }
   3803 }
   3804 
   3805 void CXXNameMangler::mangleType(const DependentNameType *T) {
   3806   // Proposal by cxx-abi-dev, 2014-03-26
   3807   // <class-enum-type> ::= <name>    # non-dependent or dependent type name or
   3808   //                                 # dependent elaborated type specifier using
   3809   //                                 # 'typename'
   3810   //                   ::= Ts <name> # dependent elaborated type specifier using
   3811   //                                 # 'struct' or 'class'
   3812   //                   ::= Tu <name> # dependent elaborated type specifier using
   3813   //                                 # 'union'
   3814   //                   ::= Te <name> # dependent elaborated type specifier using
   3815   //                                 # 'enum'
   3816   switch (T->getKeyword()) {
   3817     case ETK_None:
   3818     case ETK_Typename:
   3819       break;
   3820     case ETK_Struct:
   3821     case ETK_Class:
   3822     case ETK_Interface:
   3823       Out << "Ts";
   3824       break;
   3825     case ETK_Union:
   3826       Out << "Tu";
   3827       break;
   3828     case ETK_Enum:
   3829       Out << "Te";
   3830       break;
   3831   }
   3832   // Typename types are always nested
   3833   Out << 'N';
   3834   manglePrefix(T->getQualifier());
   3835   mangleSourceName(T->getIdentifier());
   3836   Out << 'E';
   3837 }
   3838 
   3839 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
   3840   // Dependently-scoped template types are nested if they have a prefix.
   3841   Out << 'N';
   3842 
   3843   // TODO: avoid making this TemplateName.
   3844   TemplateName Prefix =
   3845     getASTContext().getDependentTemplateName(T->getQualifier(),
   3846                                              T->getIdentifier());
   3847   mangleTemplatePrefix(Prefix);
   3848 
   3849   // FIXME: GCC does not appear to mangle the template arguments when
   3850   // the template in question is a dependent template name. Should we
   3851   // emulate that badness?
   3852   mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs());
   3853   Out << 'E';
   3854 }
   3855 
   3856 void CXXNameMangler::mangleType(const TypeOfType *T) {
   3857   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
   3858   // "extension with parameters" mangling.
   3859   Out << "u6typeof";
   3860 }
   3861 
   3862 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
   3863   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
   3864   // "extension with parameters" mangling.
   3865   Out << "u6typeof";
   3866 }
   3867 
   3868 void CXXNameMangler::mangleType(const DecltypeType *T) {
   3869   Expr *E = T->getUnderlyingExpr();
   3870 
   3871   // type ::= Dt <expression> E  # decltype of an id-expression
   3872   //                             #   or class member access
   3873   //      ::= DT <expression> E  # decltype of an expression
   3874 
   3875   // This purports to be an exhaustive list of id-expressions and
   3876   // class member accesses.  Note that we do not ignore parentheses;
   3877   // parentheses change the semantics of decltype for these
   3878   // expressions (and cause the mangler to use the other form).
   3879   if (isa<DeclRefExpr>(E) ||
   3880       isa<MemberExpr>(E) ||
   3881       isa<UnresolvedLookupExpr>(E) ||
   3882       isa<DependentScopeDeclRefExpr>(E) ||
   3883       isa<CXXDependentScopeMemberExpr>(E) ||
   3884       isa<UnresolvedMemberExpr>(E))
   3885     Out << "Dt";
   3886   else
   3887     Out << "DT";
   3888   mangleExpression(E);
   3889   Out << 'E';
   3890 }
   3891 
   3892 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
   3893   // If this is dependent, we need to record that. If not, we simply
   3894   // mangle it as the underlying type since they are equivalent.
   3895   if (T->isDependentType()) {
   3896     Out << 'U';
   3897 
   3898     switch (T->getUTTKind()) {
   3899       case UnaryTransformType::EnumUnderlyingType:
   3900         Out << "3eut";
   3901         break;
   3902     }
   3903   }
   3904 
   3905   mangleType(T->getBaseType());
   3906 }
   3907 
   3908 void CXXNameMangler::mangleType(const AutoType *T) {
   3909   assert(T->getDeducedType().isNull() &&
   3910          "Deduced AutoType shouldn't be handled here!");
   3911   assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
   3912          "shouldn't need to mangle __auto_type!");
   3913   // <builtin-type> ::= Da # auto
   3914   //                ::= Dc # decltype(auto)
   3915   Out << (T->isDecltypeAuto() ? "Dc" : "Da");
   3916 }
   3917 
   3918 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
   3919   QualType Deduced = T->getDeducedType();
   3920   if (!Deduced.isNull())
   3921     return mangleType(Deduced);
   3922 
   3923   TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
   3924   assert(TD && "shouldn't form deduced TST unless we know we have a template");
   3925 
   3926   if (mangleSubstitution(TD))
   3927     return;
   3928 
   3929   mangleName(GlobalDecl(TD));
   3930   addSubstitution(TD);
   3931 }
   3932 
   3933 void CXXNameMangler::mangleType(const AtomicType *T) {
   3934   // <type> ::= U <source-name> <type>  # vendor extended type qualifier
   3935   // (Until there's a standardized mangling...)
   3936   Out << "U7_Atomic";
   3937   mangleType(T->getValueType());
   3938 }
   3939 
   3940 void CXXNameMangler::mangleType(const PipeType *T) {
   3941   // Pipe type mangling rules are described in SPIR 2.0 specification
   3942   // A.1 Data types and A.3 Summary of changes
   3943   // <type> ::= 8ocl_pipe
   3944   Out << "8ocl_pipe";
   3945 }
   3946 
   3947 void CXXNameMangler::mangleType(const ExtIntType *T) {
   3948   Out << "U7_ExtInt";
   3949   llvm::APSInt BW(32, true);
   3950   BW = T->getNumBits();
   3951   TemplateArgument TA(Context.getASTContext(), BW, getASTContext().IntTy);
   3952   mangleTemplateArgs(TemplateName(), &TA, 1);
   3953   if (T->isUnsigned())
   3954     Out << "j";
   3955   else
   3956     Out << "i";
   3957 }
   3958 
   3959 void CXXNameMangler::mangleType(const DependentExtIntType *T) {
   3960   Out << "U7_ExtInt";
   3961   TemplateArgument TA(T->getNumBitsExpr());
   3962   mangleTemplateArgs(TemplateName(), &TA, 1);
   3963   if (T->isUnsigned())
   3964     Out << "j";
   3965   else
   3966     Out << "i";
   3967 }
   3968 
   3969 void CXXNameMangler::mangleIntegerLiteral(QualType T,
   3970                                           const llvm::APSInt &Value) {
   3971   //  <expr-primary> ::= L <type> <value number> E # integer literal
   3972   Out << 'L';
   3973 
   3974   mangleType(T);
   3975   if (T->isBooleanType()) {
   3976     // Boolean values are encoded as 0/1.
   3977     Out << (Value.getBoolValue() ? '1' : '0');
   3978   } else {
   3979     mangleNumber(Value);
   3980   }
   3981   Out << 'E';
   3982 
   3983 }
   3984 
   3985 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
   3986   // Ignore member expressions involving anonymous unions.
   3987   while (const auto *RT = Base->getType()->getAs<RecordType>()) {
   3988     if (!RT->getDecl()->isAnonymousStructOrUnion())
   3989       break;
   3990     const auto *ME = dyn_cast<MemberExpr>(Base);
   3991     if (!ME)
   3992       break;
   3993     Base = ME->getBase();
   3994     IsArrow = ME->isArrow();
   3995   }
   3996 
   3997   if (Base->isImplicitCXXThis()) {
   3998     // Note: GCC mangles member expressions to the implicit 'this' as
   3999     // *this., whereas we represent them as this->. The Itanium C++ ABI
   4000     // does not specify anything here, so we follow GCC.
   4001     Out << "dtdefpT";
   4002   } else {
   4003     Out << (IsArrow ? "pt" : "dt");
   4004     mangleExpression(Base);
   4005   }
   4006 }
   4007 
   4008 /// Mangles a member expression.
   4009 void CXXNameMangler::mangleMemberExpr(const Expr *base,
   4010                                       bool isArrow,
   4011                                       NestedNameSpecifier *qualifier,
   4012                                       NamedDecl *firstQualifierLookup,
   4013                                       DeclarationName member,
   4014                                       const TemplateArgumentLoc *TemplateArgs,
   4015                                       unsigned NumTemplateArgs,
   4016                                       unsigned arity) {
   4017   // <expression> ::= dt <expression> <unresolved-name>
   4018   //              ::= pt <expression> <unresolved-name>
   4019   if (base)
   4020     mangleMemberExprBase(base, isArrow);
   4021   mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
   4022 }
   4023 
   4024 /// Look at the callee of the given call expression and determine if
   4025 /// it's a parenthesized id-expression which would have triggered ADL
   4026 /// otherwise.
   4027 static bool isParenthesizedADLCallee(const CallExpr *call) {
   4028   const Expr *callee = call->getCallee();
   4029   const Expr *fn = callee->IgnoreParens();
   4030 
   4031   // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,
   4032   // too, but for those to appear in the callee, it would have to be
   4033   // parenthesized.
   4034   if (callee == fn) return false;
   4035 
   4036   // Must be an unresolved lookup.
   4037   const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
   4038   if (!lookup) return false;
   4039 
   4040   assert(!lookup->requiresADL());
   4041 
   4042   // Must be an unqualified lookup.
   4043   if (lookup->getQualifier()) return false;
   4044 
   4045   // Must not have found a class member.  Note that if one is a class
   4046   // member, they're all class members.
   4047   if (lookup->getNumDecls() > 0 &&
   4048       (*lookup->decls_begin())->isCXXClassMember())
   4049     return false;
   4050 
   4051   // Otherwise, ADL would have been triggered.
   4052   return true;
   4053 }
   4054 
   4055 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
   4056   const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
   4057   Out << CastEncoding;
   4058   mangleType(ECE->getType());
   4059   mangleExpression(ECE->getSubExpr());
   4060 }
   4061 
   4062 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
   4063   if (auto *Syntactic = InitList->getSyntacticForm())
   4064     InitList = Syntactic;
   4065   for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
   4066     mangleExpression(InitList->getInit(i));
   4067 }
   4068 
   4069 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
   4070                                       bool AsTemplateArg) {
   4071   // <expression> ::= <unary operator-name> <expression>
   4072   //              ::= <binary operator-name> <expression> <expression>
   4073   //              ::= <trinary operator-name> <expression> <expression> <expression>
   4074   //              ::= cv <type> expression           # conversion with one argument
   4075   //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
   4076   //              ::= dc <type> <expression>         # dynamic_cast<type> (expression)
   4077   //              ::= sc <type> <expression>         # static_cast<type> (expression)
   4078   //              ::= cc <type> <expression>         # const_cast<type> (expression)
   4079   //              ::= rc <type> <expression>         # reinterpret_cast<type> (expression)
   4080   //              ::= st <type>                      # sizeof (a type)
   4081   //              ::= at <type>                      # alignof (a type)
   4082   //              ::= <template-param>
   4083   //              ::= <function-param>
   4084   //              ::= fpT                            # 'this' expression (part of <function-param>)
   4085   //              ::= sr <type> <unqualified-name>                   # dependent name
   4086   //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
   4087   //              ::= ds <expression> <expression>                   # expr.*expr
   4088   //              ::= sZ <template-param>                            # size of a parameter pack
   4089   //              ::= sZ <function-param>    # size of a function parameter pack
   4090   //              ::= u <source-name> <template-arg>* E # vendor extended expression
   4091   //              ::= <expr-primary>
   4092   // <expr-primary> ::= L <type> <value number> E    # integer literal
   4093   //                ::= L <type> <value float> E     # floating literal
   4094   //                ::= L <type> <string type> E     # string literal
   4095   //                ::= L <nullptr type> E           # nullptr literal "LDnE"
   4096   //                ::= L <pointer type> 0 E         # null pointer template argument
   4097   //                ::= L <type> <real-part float> _ <imag-part float> E    # complex floating point literal (C99); not used by clang
   4098   //                ::= L <mangled-name> E           # external name
   4099   QualType ImplicitlyConvertedToType;
   4100 
   4101   // A top-level expression that's not <expr-primary> needs to be wrapped in
   4102   // X...E in a template arg.
   4103   bool IsPrimaryExpr = true;
   4104   auto NotPrimaryExpr = [&] {
   4105     if (AsTemplateArg && IsPrimaryExpr)
   4106       Out << 'X';
   4107     IsPrimaryExpr = false;
   4108   };
   4109 
   4110   auto MangleDeclRefExpr = [&](const NamedDecl *D) {
   4111     switch (D->getKind()) {
   4112     default:
   4113       //  <expr-primary> ::= L <mangled-name> E # external name
   4114       Out << 'L';
   4115       mangle(D);
   4116       Out << 'E';
   4117       break;
   4118 
   4119     case Decl::ParmVar:
   4120       NotPrimaryExpr();
   4121       mangleFunctionParam(cast<ParmVarDecl>(D));
   4122       break;
   4123 
   4124     case Decl::EnumConstant: {
   4125       // <expr-primary>
   4126       const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
   4127       mangleIntegerLiteral(ED->getType(), ED->getInitVal());
   4128       break;
   4129     }
   4130 
   4131     case Decl::NonTypeTemplateParm:
   4132       NotPrimaryExpr();
   4133       const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
   4134       mangleTemplateParameter(PD->getDepth(), PD->getIndex());
   4135       break;
   4136     }
   4137   };
   4138 
   4139   // 'goto recurse' is used when handling a simple "unwrapping" node which
   4140   // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
   4141   // to be preserved.
   4142 recurse:
   4143   switch (E->getStmtClass()) {
   4144   case Expr::NoStmtClass:
   4145 #define ABSTRACT_STMT(Type)
   4146 #define EXPR(Type, Base)
   4147 #define STMT(Type, Base) \
   4148   case Expr::Type##Class:
   4149 #include "clang/AST/StmtNodes.inc"
   4150     // fallthrough
   4151 
   4152   // These all can only appear in local or variable-initialization
   4153   // contexts and so should never appear in a mangling.
   4154   case Expr::AddrLabelExprClass:
   4155   case Expr::DesignatedInitUpdateExprClass:
   4156   case Expr::ImplicitValueInitExprClass:
   4157   case Expr::ArrayInitLoopExprClass:
   4158   case Expr::ArrayInitIndexExprClass:
   4159   case Expr::NoInitExprClass:
   4160   case Expr::ParenListExprClass:
   4161   case Expr::LambdaExprClass:
   4162   case Expr::MSPropertyRefExprClass:
   4163   case Expr::MSPropertySubscriptExprClass:
   4164   case Expr::TypoExprClass: // This should no longer exist in the AST by now.
   4165   case Expr::RecoveryExprClass:
   4166   case Expr::OMPArraySectionExprClass:
   4167   case Expr::OMPArrayShapingExprClass:
   4168   case Expr::OMPIteratorExprClass:
   4169   case Expr::CXXInheritedCtorInitExprClass:
   4170     llvm_unreachable("unexpected statement kind");
   4171 
   4172   case Expr::ConstantExprClass:
   4173     E = cast<ConstantExpr>(E)->getSubExpr();
   4174     goto recurse;
   4175 
   4176   // FIXME: invent manglings for all these.
   4177   case Expr::BlockExprClass:
   4178   case Expr::ChooseExprClass:
   4179   case Expr::CompoundLiteralExprClass:
   4180   case Expr::ExtVectorElementExprClass:
   4181   case Expr::GenericSelectionExprClass:
   4182   case Expr::ObjCEncodeExprClass:
   4183   case Expr::ObjCIsaExprClass:
   4184   case Expr::ObjCIvarRefExprClass:
   4185   case Expr::ObjCMessageExprClass:
   4186   case Expr::ObjCPropertyRefExprClass:
   4187   case Expr::ObjCProtocolExprClass:
   4188   case Expr::ObjCSelectorExprClass:
   4189   case Expr::ObjCStringLiteralClass:
   4190   case Expr::ObjCBoxedExprClass:
   4191   case Expr::ObjCArrayLiteralClass:
   4192   case Expr::ObjCDictionaryLiteralClass:
   4193   case Expr::ObjCSubscriptRefExprClass:
   4194   case Expr::ObjCIndirectCopyRestoreExprClass:
   4195   case Expr::ObjCAvailabilityCheckExprClass:
   4196   case Expr::OffsetOfExprClass:
   4197   case Expr::PredefinedExprClass:
   4198   case Expr::ShuffleVectorExprClass:
   4199   case Expr::ConvertVectorExprClass:
   4200   case Expr::StmtExprClass:
   4201   case Expr::TypeTraitExprClass:
   4202   case Expr::RequiresExprClass:
   4203   case Expr::ArrayTypeTraitExprClass:
   4204   case Expr::ExpressionTraitExprClass:
   4205   case Expr::VAArgExprClass:
   4206   case Expr::CUDAKernelCallExprClass:
   4207   case Expr::AsTypeExprClass:
   4208   case Expr::PseudoObjectExprClass:
   4209   case Expr::AtomicExprClass:
   4210   case Expr::SourceLocExprClass:
   4211   case Expr::BuiltinBitCastExprClass:
   4212   {
   4213     NotPrimaryExpr();
   4214     if (!NullOut) {
   4215       // As bad as this diagnostic is, it's better than crashing.
   4216       DiagnosticsEngine &Diags = Context.getDiags();
   4217       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   4218                                        "cannot yet mangle expression type %0");
   4219       Diags.Report(E->getExprLoc(), DiagID)
   4220         << E->getStmtClassName() << E->getSourceRange();
   4221       return;
   4222     }
   4223     break;
   4224   }
   4225 
   4226   case Expr::CXXUuidofExprClass: {
   4227     NotPrimaryExpr();
   4228     const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
   4229     // As of clang 12, uuidof uses the vendor extended expression
   4230     // mangling. Previously, it used a special-cased nonstandard extension.
   4231     if (Context.getASTContext().getLangOpts().getClangABICompat() >
   4232         LangOptions::ClangABI::Ver11) {
   4233       Out << "u8__uuidof";
   4234       if (UE->isTypeOperand())
   4235         mangleType(UE->getTypeOperand(Context.getASTContext()));
   4236       else
   4237         mangleTemplateArgExpr(UE->getExprOperand());
   4238       Out << 'E';
   4239     } else {
   4240       if (UE->isTypeOperand()) {
   4241         QualType UuidT = UE->getTypeOperand(Context.getASTContext());
   4242         Out << "u8__uuidoft";
   4243         mangleType(UuidT);
   4244       } else {
   4245         Expr *UuidExp = UE->getExprOperand();
   4246         Out << "u8__uuidofz";
   4247         mangleExpression(UuidExp);
   4248       }
   4249     }
   4250     break;
   4251   }
   4252 
   4253   // Even gcc-4.5 doesn't mangle this.
   4254   case Expr::BinaryConditionalOperatorClass: {
   4255     NotPrimaryExpr();
   4256     DiagnosticsEngine &Diags = Context.getDiags();
   4257     unsigned DiagID =
   4258       Diags.getCustomDiagID(DiagnosticsEngine::Error,
   4259                 "?: operator with omitted middle operand cannot be mangled");
   4260     Diags.Report(E->getExprLoc(), DiagID)
   4261       << E->getStmtClassName() << E->getSourceRange();
   4262     return;
   4263   }
   4264 
   4265   // These are used for internal purposes and cannot be meaningfully mangled.
   4266   case Expr::OpaqueValueExprClass:
   4267     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
   4268 
   4269   case Expr::InitListExprClass: {
   4270     NotPrimaryExpr();
   4271     Out << "il";
   4272     mangleInitListElements(cast<InitListExpr>(E));
   4273     Out << "E";
   4274     break;
   4275   }
   4276 
   4277   case Expr::DesignatedInitExprClass: {
   4278     NotPrimaryExpr();
   4279     auto *DIE = cast<DesignatedInitExpr>(E);
   4280     for (const auto &Designator : DIE->designators()) {
   4281       if (Designator.isFieldDesignator()) {
   4282         Out << "di";
   4283         mangleSourceName(Designator.getFieldName());
   4284       } else if (Designator.isArrayDesignator()) {
   4285         Out << "dx";
   4286         mangleExpression(DIE->getArrayIndex(Designator));
   4287       } else {
   4288         assert(Designator.isArrayRangeDesignator() &&
   4289                "unknown designator kind");
   4290         Out << "dX";
   4291         mangleExpression(DIE->getArrayRangeStart(Designator));
   4292         mangleExpression(DIE->getArrayRangeEnd(Designator));
   4293       }
   4294     }
   4295     mangleExpression(DIE->getInit());
   4296     break;
   4297   }
   4298 
   4299   case Expr::CXXDefaultArgExprClass:
   4300     E = cast<CXXDefaultArgExpr>(E)->getExpr();
   4301     goto recurse;
   4302 
   4303   case Expr::CXXDefaultInitExprClass:
   4304     E = cast<CXXDefaultInitExpr>(E)->getExpr();
   4305     goto recurse;
   4306 
   4307   case Expr::CXXStdInitializerListExprClass:
   4308     E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
   4309     goto recurse;
   4310 
   4311   case Expr::SubstNonTypeTemplateParmExprClass:
   4312     E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
   4313     goto recurse;
   4314 
   4315   case Expr::UserDefinedLiteralClass:
   4316     // We follow g++'s approach of mangling a UDL as a call to the literal
   4317     // operator.
   4318   case Expr::CXXMemberCallExprClass: // fallthrough
   4319   case Expr::CallExprClass: {
   4320     NotPrimaryExpr();
   4321     const CallExpr *CE = cast<CallExpr>(E);
   4322 
   4323     // <expression> ::= cp <simple-id> <expression>* E
   4324     // We use this mangling only when the call would use ADL except
   4325     // for being parenthesized.  Per discussion with David
   4326     // Vandervoorde, 2011.04.25.
   4327     if (isParenthesizedADLCallee(CE)) {
   4328       Out << "cp";
   4329       // The callee here is a parenthesized UnresolvedLookupExpr with
   4330       // no qualifier and should always get mangled as a <simple-id>
   4331       // anyway.
   4332 
   4333     // <expression> ::= cl <expression>* E
   4334     } else {
   4335       Out << "cl";
   4336     }
   4337 
   4338     unsigned CallArity = CE->getNumArgs();
   4339     for (const Expr *Arg : CE->arguments())
   4340       if (isa<PackExpansionExpr>(Arg))
   4341         CallArity = UnknownArity;
   4342 
   4343     mangleExpression(CE->getCallee(), CallArity);
   4344     for (const Expr *Arg : CE->arguments())
   4345       mangleExpression(Arg);
   4346     Out << 'E';
   4347     break;
   4348   }
   4349 
   4350   case Expr::CXXNewExprClass: {
   4351     NotPrimaryExpr();
   4352     const CXXNewExpr *New = cast<CXXNewExpr>(E);
   4353     if (New->isGlobalNew()) Out << "gs";
   4354     Out << (New->isArray() ? "na" : "nw");
   4355     for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
   4356            E = New->placement_arg_end(); I != E; ++I)
   4357       mangleExpression(*I);
   4358     Out << '_';
   4359     mangleType(New->getAllocatedType());
   4360     if (New->hasInitializer()) {
   4361       if (New->getInitializationStyle() == CXXNewExpr::ListInit)
   4362         Out << "il";
   4363       else
   4364         Out << "pi";
   4365       const Expr *Init = New->getInitializer();
   4366       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
   4367         // Directly inline the initializers.
   4368         for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
   4369                                                   E = CCE->arg_end();
   4370              I != E; ++I)
   4371           mangleExpression(*I);
   4372       } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
   4373         for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
   4374           mangleExpression(PLE->getExpr(i));
   4375       } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
   4376                  isa<InitListExpr>(Init)) {
   4377         // Only take InitListExprs apart for list-initialization.
   4378         mangleInitListElements(cast<InitListExpr>(Init));
   4379       } else
   4380         mangleExpression(Init);
   4381     }
   4382     Out << 'E';
   4383     break;
   4384   }
   4385 
   4386   case Expr::CXXPseudoDestructorExprClass: {
   4387     NotPrimaryExpr();
   4388     const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
   4389     if (const Expr *Base = PDE->getBase())
   4390       mangleMemberExprBase(Base, PDE->isArrow());
   4391     NestedNameSpecifier *Qualifier = PDE->getQualifier();
   4392     if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
   4393       if (Qualifier) {
   4394         mangleUnresolvedPrefix(Qualifier,
   4395                                /*recursive=*/true);
   4396         mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
   4397         Out << 'E';
   4398       } else {
   4399         Out << "sr";
   4400         if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
   4401           Out << 'E';
   4402       }
   4403     } else if (Qualifier) {
   4404       mangleUnresolvedPrefix(Qualifier);
   4405     }
   4406     // <base-unresolved-name> ::= dn <destructor-name>
   4407     Out << "dn";
   4408     QualType DestroyedType = PDE->getDestroyedType();
   4409     mangleUnresolvedTypeOrSimpleId(DestroyedType);
   4410     break;
   4411   }
   4412 
   4413   case Expr::MemberExprClass: {
   4414     NotPrimaryExpr();
   4415     const MemberExpr *ME = cast<MemberExpr>(E);
   4416     mangleMemberExpr(ME->getBase(), ME->isArrow(),
   4417                      ME->getQualifier(), nullptr,
   4418                      ME->getMemberDecl()->getDeclName(),
   4419                      ME->getTemplateArgs(), ME->getNumTemplateArgs(),
   4420                      Arity);
   4421     break;
   4422   }
   4423 
   4424   case Expr::UnresolvedMemberExprClass: {
   4425     NotPrimaryExpr();
   4426     const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
   4427     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
   4428                      ME->isArrow(), ME->getQualifier(), nullptr,
   4429                      ME->getMemberName(),
   4430                      ME->getTemplateArgs(), ME->getNumTemplateArgs(),
   4431                      Arity);
   4432     break;
   4433   }
   4434 
   4435   case Expr::CXXDependentScopeMemberExprClass: {
   4436     NotPrimaryExpr();
   4437     const CXXDependentScopeMemberExpr *ME
   4438       = cast<CXXDependentScopeMemberExpr>(E);
   4439     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
   4440                      ME->isArrow(), ME->getQualifier(),
   4441                      ME->getFirstQualifierFoundInScope(),
   4442                      ME->getMember(),
   4443                      ME->getTemplateArgs(), ME->getNumTemplateArgs(),
   4444                      Arity);
   4445     break;
   4446   }
   4447 
   4448   case Expr::UnresolvedLookupExprClass: {
   4449     NotPrimaryExpr();
   4450     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
   4451     mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
   4452                          ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
   4453                          Arity);
   4454     break;
   4455   }
   4456 
   4457   case Expr::CXXUnresolvedConstructExprClass: {
   4458     NotPrimaryExpr();
   4459     const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
   4460     unsigned N = CE->getNumArgs();
   4461 
   4462     if (CE->isListInitialization()) {
   4463       assert(N == 1 && "unexpected form for list initialization");
   4464       auto *IL = cast<InitListExpr>(CE->getArg(0));
   4465       Out << "tl";
   4466       mangleType(CE->getType());
   4467       mangleInitListElements(IL);
   4468       Out << "E";
   4469       break;
   4470     }
   4471 
   4472     Out << "cv";
   4473     mangleType(CE->getType());
   4474     if (N != 1) Out << '_';
   4475     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
   4476     if (N != 1) Out << 'E';
   4477     break;
   4478   }
   4479 
   4480   case Expr::CXXConstructExprClass: {
   4481     // An implicit cast is silent, thus may contain <expr-primary>.
   4482     const auto *CE = cast<CXXConstructExpr>(E);
   4483     if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
   4484       assert(
   4485           CE->getNumArgs() >= 1 &&
   4486           (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
   4487           "implicit CXXConstructExpr must have one argument");
   4488       E = cast<CXXConstructExpr>(E)->getArg(0);
   4489       goto recurse;
   4490     }
   4491     NotPrimaryExpr();
   4492     Out << "il";
   4493     for (auto *E : CE->arguments())
   4494       mangleExpression(E);
   4495     Out << "E";
   4496     break;
   4497   }
   4498 
   4499   case Expr::CXXTemporaryObjectExprClass: {
   4500     NotPrimaryExpr();
   4501     const auto *CE = cast<CXXTemporaryObjectExpr>(E);
   4502     unsigned N = CE->getNumArgs();
   4503     bool List = CE->isListInitialization();
   4504 
   4505     if (List)
   4506       Out << "tl";
   4507     else
   4508       Out << "cv";
   4509     mangleType(CE->getType());
   4510     if (!List && N != 1)
   4511       Out << '_';
   4512     if (CE->isStdInitListInitialization()) {
   4513       // We implicitly created a std::initializer_list<T> for the first argument
   4514       // of a constructor of type U in an expression of the form U{a, b, c}.
   4515       // Strip all the semantic gunk off the initializer list.
   4516       auto *SILE =
   4517           cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
   4518       auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
   4519       mangleInitListElements(ILE);
   4520     } else {
   4521       for (auto *E : CE->arguments())
   4522         mangleExpression(E);
   4523     }
   4524     if (List || N != 1)
   4525       Out << 'E';
   4526     break;
   4527   }
   4528 
   4529   case Expr::CXXScalarValueInitExprClass:
   4530     NotPrimaryExpr();
   4531     Out << "cv";
   4532     mangleType(E->getType());
   4533     Out << "_E";
   4534     break;
   4535 
   4536   case Expr::CXXNoexceptExprClass:
   4537     NotPrimaryExpr();
   4538     Out << "nx";
   4539     mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
   4540     break;
   4541 
   4542   case Expr::UnaryExprOrTypeTraitExprClass: {
   4543     // Non-instantiation-dependent traits are an <expr-primary> integer literal.
   4544     const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
   4545 
   4546     if (!SAE->isInstantiationDependent()) {
   4547       // Itanium C++ ABI:
   4548       //   If the operand of a sizeof or alignof operator is not
   4549       //   instantiation-dependent it is encoded as an integer literal
   4550       //   reflecting the result of the operator.
   4551       //
   4552       //   If the result of the operator is implicitly converted to a known
   4553       //   integer type, that type is used for the literal; otherwise, the type
   4554       //   of std::size_t or std::ptrdiff_t is used.
   4555       QualType T = (ImplicitlyConvertedToType.isNull() ||
   4556                     !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
   4557                                                     : ImplicitlyConvertedToType;
   4558       llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
   4559       mangleIntegerLiteral(T, V);
   4560       break;
   4561     }
   4562 
   4563     NotPrimaryExpr(); // But otherwise, they are not.
   4564 
   4565     auto MangleAlignofSizeofArg = [&] {
   4566       if (SAE->isArgumentType()) {
   4567         Out << 't';
   4568         mangleType(SAE->getArgumentType());
   4569       } else {
   4570         Out << 'z';
   4571         mangleExpression(SAE->getArgumentExpr());
   4572       }
   4573     };
   4574 
   4575     switch(SAE->getKind()) {
   4576     case UETT_SizeOf:
   4577       Out << 's';
   4578       MangleAlignofSizeofArg();
   4579       break;
   4580     case UETT_PreferredAlignOf:
   4581       // As of clang 12, we mangle __alignof__ differently than alignof. (They
   4582       // have acted differently since Clang 8, but were previously mangled the
   4583       // same.)
   4584       if (Context.getASTContext().getLangOpts().getClangABICompat() >
   4585           LangOptions::ClangABI::Ver11) {
   4586         Out << "u11__alignof__";
   4587         if (SAE->isArgumentType())
   4588           mangleType(SAE->getArgumentType());
   4589         else
   4590           mangleTemplateArgExpr(SAE->getArgumentExpr());
   4591         Out << 'E';
   4592         break;
   4593       }
   4594       LLVM_FALLTHROUGH;
   4595     case UETT_AlignOf:
   4596       Out << 'a';
   4597       MangleAlignofSizeofArg();
   4598       break;
   4599     case UETT_VecStep: {
   4600       DiagnosticsEngine &Diags = Context.getDiags();
   4601       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   4602                                      "cannot yet mangle vec_step expression");
   4603       Diags.Report(DiagID);
   4604       return;
   4605     }
   4606     case UETT_OpenMPRequiredSimdAlign: {
   4607       DiagnosticsEngine &Diags = Context.getDiags();
   4608       unsigned DiagID = Diags.getCustomDiagID(
   4609           DiagnosticsEngine::Error,
   4610           "cannot yet mangle __builtin_omp_required_simd_align expression");
   4611       Diags.Report(DiagID);
   4612       return;
   4613     }
   4614     }
   4615     break;
   4616   }
   4617 
   4618   case Expr::CXXThrowExprClass: {
   4619     NotPrimaryExpr();
   4620     const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
   4621     //  <expression> ::= tw <expression>  # throw expression
   4622     //               ::= tr               # rethrow
   4623     if (TE->getSubExpr()) {
   4624       Out << "tw";
   4625       mangleExpression(TE->getSubExpr());
   4626     } else {
   4627       Out << "tr";
   4628     }
   4629     break;
   4630   }
   4631 
   4632   case Expr::CXXTypeidExprClass: {
   4633     NotPrimaryExpr();
   4634     const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
   4635     //  <expression> ::= ti <type>        # typeid (type)
   4636     //               ::= te <expression>  # typeid (expression)
   4637     if (TIE->isTypeOperand()) {
   4638       Out << "ti";
   4639       mangleType(TIE->getTypeOperand(Context.getASTContext()));
   4640     } else {
   4641       Out << "te";
   4642       mangleExpression(TIE->getExprOperand());
   4643     }
   4644     break;
   4645   }
   4646 
   4647   case Expr::CXXDeleteExprClass: {
   4648     NotPrimaryExpr();
   4649     const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
   4650     //  <expression> ::= [gs] dl <expression>  # [::] delete expr
   4651     //               ::= [gs] da <expression>  # [::] delete [] expr
   4652     if (DE->isGlobalDelete()) Out << "gs";
   4653     Out << (DE->isArrayForm() ? "da" : "dl");
   4654     mangleExpression(DE->getArgument());
   4655     break;
   4656   }
   4657 
   4658   case Expr::UnaryOperatorClass: {
   4659     NotPrimaryExpr();
   4660     const UnaryOperator *UO = cast<UnaryOperator>(E);
   4661     mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
   4662                        /*Arity=*/1);
   4663     mangleExpression(UO->getSubExpr());
   4664     break;
   4665   }
   4666 
   4667   case Expr::ArraySubscriptExprClass: {
   4668     NotPrimaryExpr();
   4669     const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
   4670 
   4671     // Array subscript is treated as a syntactically weird form of
   4672     // binary operator.
   4673     Out << "ix";
   4674     mangleExpression(AE->getLHS());
   4675     mangleExpression(AE->getRHS());
   4676     break;
   4677   }
   4678 
   4679   case Expr::MatrixSubscriptExprClass: {
   4680     NotPrimaryExpr();
   4681     const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
   4682     Out << "ixix";
   4683     mangleExpression(ME->getBase());
   4684     mangleExpression(ME->getRowIdx());
   4685     mangleExpression(ME->getColumnIdx());
   4686     break;
   4687   }
   4688 
   4689   case Expr::CompoundAssignOperatorClass: // fallthrough
   4690   case Expr::BinaryOperatorClass: {
   4691     NotPrimaryExpr();
   4692     const BinaryOperator *BO = cast<BinaryOperator>(E);
   4693     if (BO->getOpcode() == BO_PtrMemD)
   4694       Out << "ds";
   4695     else
   4696       mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
   4697                          /*Arity=*/2);
   4698     mangleExpression(BO->getLHS());
   4699     mangleExpression(BO->getRHS());
   4700     break;
   4701   }
   4702 
   4703   case Expr::CXXRewrittenBinaryOperatorClass: {
   4704     NotPrimaryExpr();
   4705     // The mangled form represents the original syntax.
   4706     CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
   4707         cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
   4708     mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
   4709                        /*Arity=*/2);
   4710     mangleExpression(Decomposed.LHS);
   4711     mangleExpression(Decomposed.RHS);
   4712     break;
   4713   }
   4714 
   4715   case Expr::ConditionalOperatorClass: {
   4716     NotPrimaryExpr();
   4717     const ConditionalOperator *CO = cast<ConditionalOperator>(E);
   4718     mangleOperatorName(OO_Conditional, /*Arity=*/3);
   4719     mangleExpression(CO->getCond());
   4720     mangleExpression(CO->getLHS(), Arity);
   4721     mangleExpression(CO->getRHS(), Arity);
   4722     break;
   4723   }
   4724 
   4725   case Expr::ImplicitCastExprClass: {
   4726     ImplicitlyConvertedToType = E->getType();
   4727     E = cast<ImplicitCastExpr>(E)->getSubExpr();
   4728     goto recurse;
   4729   }
   4730 
   4731   case Expr::ObjCBridgedCastExprClass: {
   4732     NotPrimaryExpr();
   4733     // Mangle ownership casts as a vendor extended operator __bridge,
   4734     // __bridge_transfer, or __bridge_retain.
   4735     StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
   4736     Out << "v1U" << Kind.size() << Kind;
   4737     mangleCastExpression(E, "cv");
   4738     break;
   4739   }
   4740 
   4741   case Expr::CStyleCastExprClass:
   4742     NotPrimaryExpr();
   4743     mangleCastExpression(E, "cv");
   4744     break;
   4745 
   4746   case Expr::CXXFunctionalCastExprClass: {
   4747     NotPrimaryExpr();
   4748     auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
   4749     // FIXME: Add isImplicit to CXXConstructExpr.
   4750     if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
   4751       if (CCE->getParenOrBraceRange().isInvalid())
   4752         Sub = CCE->getArg(0)->IgnoreImplicit();
   4753     if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
   4754       Sub = StdInitList->getSubExpr()->IgnoreImplicit();
   4755     if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
   4756       Out << "tl";
   4757       mangleType(E->getType());
   4758       mangleInitListElements(IL);
   4759       Out << "E";
   4760     } else {
   4761       mangleCastExpression(E, "cv");
   4762     }
   4763     break;
   4764   }
   4765 
   4766   case Expr::CXXStaticCastExprClass:
   4767     NotPrimaryExpr();
   4768     mangleCastExpression(E, "sc");
   4769     break;
   4770   case Expr::CXXDynamicCastExprClass:
   4771     NotPrimaryExpr();
   4772     mangleCastExpression(E, "dc");
   4773     break;
   4774   case Expr::CXXReinterpretCastExprClass:
   4775     NotPrimaryExpr();
   4776     mangleCastExpression(E, "rc");
   4777     break;
   4778   case Expr::CXXConstCastExprClass:
   4779     NotPrimaryExpr();
   4780     mangleCastExpression(E, "cc");
   4781     break;
   4782   case Expr::CXXAddrspaceCastExprClass:
   4783     NotPrimaryExpr();
   4784     mangleCastExpression(E, "ac");
   4785     break;
   4786 
   4787   case Expr::CXXOperatorCallExprClass: {
   4788     NotPrimaryExpr();
   4789     const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
   4790     unsigned NumArgs = CE->getNumArgs();
   4791     // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
   4792     // (the enclosing MemberExpr covers the syntactic portion).
   4793     if (CE->getOperator() != OO_Arrow)
   4794       mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
   4795     // Mangle the arguments.
   4796     for (unsigned i = 0; i != NumArgs; ++i)
   4797       mangleExpression(CE->getArg(i));
   4798     break;
   4799   }
   4800 
   4801   case Expr::ParenExprClass:
   4802     E = cast<ParenExpr>(E)->getSubExpr();
   4803     goto recurse;
   4804 
   4805   case Expr::ConceptSpecializationExprClass: {
   4806     //  <expr-primary> ::= L <mangled-name> E # external name
   4807     Out << "L_Z";
   4808     auto *CSE = cast<ConceptSpecializationExpr>(E);
   4809     mangleTemplateName(CSE->getNamedConcept(),
   4810                        CSE->getTemplateArguments().data(),
   4811                        CSE->getTemplateArguments().size());
   4812     Out << 'E';
   4813     break;
   4814   }
   4815 
   4816   case Expr::DeclRefExprClass:
   4817     // MangleDeclRefExpr helper handles primary-vs-nonprimary
   4818     MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
   4819     break;
   4820 
   4821   case Expr::SubstNonTypeTemplateParmPackExprClass:
   4822     NotPrimaryExpr();
   4823     // FIXME: not clear how to mangle this!
   4824     // template <unsigned N...> class A {
   4825     //   template <class U...> void foo(U (&x)[N]...);
   4826     // };
   4827     Out << "_SUBSTPACK_";
   4828     break;
   4829 
   4830   case Expr::FunctionParmPackExprClass: {
   4831     NotPrimaryExpr();
   4832     // FIXME: not clear how to mangle this!
   4833     const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
   4834     Out << "v110_SUBSTPACK";
   4835     MangleDeclRefExpr(FPPE->getParameterPack());
   4836     break;
   4837   }
   4838 
   4839   case Expr::DependentScopeDeclRefExprClass: {
   4840     NotPrimaryExpr();
   4841     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
   4842     mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
   4843                          DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
   4844                          Arity);
   4845     break;
   4846   }
   4847 
   4848   case Expr::CXXBindTemporaryExprClass:
   4849     E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
   4850     goto recurse;
   4851 
   4852   case Expr::ExprWithCleanupsClass:
   4853     E = cast<ExprWithCleanups>(E)->getSubExpr();
   4854     goto recurse;
   4855 
   4856   case Expr::FloatingLiteralClass: {
   4857     // <expr-primary>
   4858     const FloatingLiteral *FL = cast<FloatingLiteral>(E);
   4859     mangleFloatLiteral(FL->getType(), FL->getValue());
   4860     break;
   4861   }
   4862 
   4863   case Expr::FixedPointLiteralClass:
   4864     // Currently unimplemented -- might be <expr-primary> in future?
   4865     mangleFixedPointLiteral();
   4866     break;
   4867 
   4868   case Expr::CharacterLiteralClass:
   4869     // <expr-primary>
   4870     Out << 'L';
   4871     mangleType(E->getType());
   4872     Out << cast<CharacterLiteral>(E)->getValue();
   4873     Out << 'E';
   4874     break;
   4875 
   4876   // FIXME. __objc_yes/__objc_no are mangled same as true/false
   4877   case Expr::ObjCBoolLiteralExprClass:
   4878     // <expr-primary>
   4879     Out << "Lb";
   4880     Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
   4881     Out << 'E';
   4882     break;
   4883 
   4884   case Expr::CXXBoolLiteralExprClass:
   4885     // <expr-primary>
   4886     Out << "Lb";
   4887     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
   4888     Out << 'E';
   4889     break;
   4890 
   4891   case Expr::IntegerLiteralClass: {
   4892     // <expr-primary>
   4893     llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
   4894     if (E->getType()->isSignedIntegerType())
   4895       Value.setIsSigned(true);
   4896     mangleIntegerLiteral(E->getType(), Value);
   4897     break;
   4898   }
   4899 
   4900   case Expr::ImaginaryLiteralClass: {
   4901     // <expr-primary>
   4902     const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
   4903     // Mangle as if a complex literal.
   4904     // Proposal from David Vandevoorde, 2010.06.30.
   4905     Out << 'L';
   4906     mangleType(E->getType());
   4907     if (const FloatingLiteral *Imag =
   4908           dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
   4909       // Mangle a floating-point zero of the appropriate type.
   4910       mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
   4911       Out << '_';
   4912       mangleFloat(Imag->getValue());
   4913     } else {
   4914       Out << "0_";
   4915       llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
   4916       if (IE->getSubExpr()->getType()->isSignedIntegerType())
   4917         Value.setIsSigned(true);
   4918       mangleNumber(Value);
   4919     }
   4920     Out << 'E';
   4921     break;
   4922   }
   4923 
   4924   case Expr::StringLiteralClass: {
   4925     // <expr-primary>
   4926     // Revised proposal from David Vandervoorde, 2010.07.15.
   4927     Out << 'L';
   4928     assert(isa<ConstantArrayType>(E->getType()));
   4929     mangleType(E->getType());
   4930     Out << 'E';
   4931     break;
   4932   }
   4933 
   4934   case Expr::GNUNullExprClass:
   4935     // <expr-primary>
   4936     // Mangle as if an integer literal 0.
   4937     mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
   4938     break;
   4939 
   4940   case Expr::CXXNullPtrLiteralExprClass: {
   4941     // <expr-primary>
   4942     Out << "LDnE";
   4943     break;
   4944   }
   4945 
   4946   case Expr::PackExpansionExprClass:
   4947     NotPrimaryExpr();
   4948     Out << "sp";
   4949     mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
   4950     break;
   4951 
   4952   case Expr::SizeOfPackExprClass: {
   4953     NotPrimaryExpr();
   4954     auto *SPE = cast<SizeOfPackExpr>(E);
   4955     if (SPE->isPartiallySubstituted()) {
   4956       Out << "sP";
   4957       for (const auto &A : SPE->getPartialArguments())
   4958         mangleTemplateArg(A, false);
   4959       Out << "E";
   4960       break;
   4961     }
   4962 
   4963     Out << "sZ";
   4964     const NamedDecl *Pack = SPE->getPack();
   4965     if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
   4966       mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
   4967     else if (const NonTypeTemplateParmDecl *NTTP
   4968                 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
   4969       mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
   4970     else if (const TemplateTemplateParmDecl *TempTP
   4971                                     = dyn_cast<TemplateTemplateParmDecl>(Pack))
   4972       mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
   4973     else
   4974       mangleFunctionParam(cast<ParmVarDecl>(Pack));
   4975     break;
   4976   }
   4977 
   4978   case Expr::MaterializeTemporaryExprClass:
   4979     E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
   4980     goto recurse;
   4981 
   4982   case Expr::CXXFoldExprClass: {
   4983     NotPrimaryExpr();
   4984     auto *FE = cast<CXXFoldExpr>(E);
   4985     if (FE->isLeftFold())
   4986       Out << (FE->getInit() ? "fL" : "fl");
   4987     else
   4988       Out << (FE->getInit() ? "fR" : "fr");
   4989 
   4990     if (FE->getOperator() == BO_PtrMemD)
   4991       Out << "ds";
   4992     else
   4993       mangleOperatorName(
   4994           BinaryOperator::getOverloadedOperator(FE->getOperator()),
   4995           /*Arity=*/2);
   4996 
   4997     if (FE->getLHS())
   4998       mangleExpression(FE->getLHS());
   4999     if (FE->getRHS())
   5000       mangleExpression(FE->getRHS());
   5001     break;
   5002   }
   5003 
   5004   case Expr::CXXThisExprClass:
   5005     NotPrimaryExpr();
   5006     Out << "fpT";
   5007     break;
   5008 
   5009   case Expr::CoawaitExprClass:
   5010     // FIXME: Propose a non-vendor mangling.
   5011     NotPrimaryExpr();
   5012     Out << "v18co_await";
   5013     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
   5014     break;
   5015 
   5016   case Expr::DependentCoawaitExprClass:
   5017     // FIXME: Propose a non-vendor mangling.
   5018     NotPrimaryExpr();
   5019     Out << "v18co_await";
   5020     mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
   5021     break;
   5022 
   5023   case Expr::CoyieldExprClass:
   5024     // FIXME: Propose a non-vendor mangling.
   5025     NotPrimaryExpr();
   5026     Out << "v18co_yield";
   5027     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
   5028     break;
   5029   }
   5030 
   5031   if (AsTemplateArg && !IsPrimaryExpr)
   5032     Out << 'E';
   5033 }
   5034 
   5035 /// Mangle an expression which refers to a parameter variable.
   5036 ///
   5037 /// <expression>     ::= <function-param>
   5038 /// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 0
   5039 /// <function-param> ::= fp <top-level CV-qualifiers>
   5040 ///                      <parameter-2 non-negative number> _ # L == 0, I > 0
   5041 /// <function-param> ::= fL <L-1 non-negative number>
   5042 ///                      p <top-level CV-qualifiers> _       # L > 0, I == 0
   5043 /// <function-param> ::= fL <L-1 non-negative number>
   5044 ///                      p <top-level CV-qualifiers>
   5045 ///                      <I-1 non-negative number> _         # L > 0, I > 0
   5046 ///
   5047 /// L is the nesting depth of the parameter, defined as 1 if the
   5048 /// parameter comes from the innermost function prototype scope
   5049 /// enclosing the current context, 2 if from the next enclosing
   5050 /// function prototype scope, and so on, with one special case: if
   5051 /// we've processed the full parameter clause for the innermost
   5052 /// function type, then L is one less.  This definition conveniently
   5053 /// makes it irrelevant whether a function's result type was written
   5054 /// trailing or leading, but is otherwise overly complicated; the
   5055 /// numbering was first designed without considering references to
   5056 /// parameter in locations other than return types, and then the
   5057 /// mangling had to be generalized without changing the existing
   5058 /// manglings.
   5059 ///
   5060 /// I is the zero-based index of the parameter within its parameter
   5061 /// declaration clause.  Note that the original ABI document describes
   5062 /// this using 1-based ordinals.
   5063 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
   5064   unsigned parmDepth = parm->getFunctionScopeDepth();
   5065   unsigned parmIndex = parm->getFunctionScopeIndex();
   5066 
   5067   // Compute 'L'.
   5068   // parmDepth does not include the declaring function prototype.
   5069   // FunctionTypeDepth does account for that.
   5070   assert(parmDepth < FunctionTypeDepth.getDepth());
   5071   unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
   5072   if (FunctionTypeDepth.isInResultType())
   5073     nestingDepth--;
   5074 
   5075   if (nestingDepth == 0) {
   5076     Out << "fp";
   5077   } else {
   5078     Out << "fL" << (nestingDepth - 1) << 'p';
   5079   }
   5080 
   5081   // Top-level qualifiers.  We don't have to worry about arrays here,
   5082   // because parameters declared as arrays should already have been
   5083   // transformed to have pointer type. FIXME: apparently these don't
   5084   // get mangled if used as an rvalue of a known non-class type?
   5085   assert(!parm->getType()->isArrayType()
   5086          && "parameter's type is still an array type?");
   5087 
   5088   if (const DependentAddressSpaceType *DAST =
   5089       dyn_cast<DependentAddressSpaceType>(parm->getType())) {
   5090     mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
   5091   } else {
   5092     mangleQualifiers(parm->getType().getQualifiers());
   5093   }
   5094 
   5095   // Parameter index.
   5096   if (parmIndex != 0) {
   5097     Out << (parmIndex - 1);
   5098   }
   5099   Out << '_';
   5100 }
   5101 
   5102 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
   5103                                        const CXXRecordDecl *InheritedFrom) {
   5104   // <ctor-dtor-name> ::= C1  # complete object constructor
   5105   //                  ::= C2  # base object constructor
   5106   //                  ::= CI1 <type> # complete inheriting constructor
   5107   //                  ::= CI2 <type> # base inheriting constructor
   5108   //
   5109   // In addition, C5 is a comdat name with C1 and C2 in it.
   5110   Out << 'C';
   5111   if (InheritedFrom)
   5112     Out << 'I';
   5113   switch (T) {
   5114   case Ctor_Complete:
   5115     Out << '1';
   5116     break;
   5117   case Ctor_Base:
   5118     Out << '2';
   5119     break;
   5120   case Ctor_Comdat:
   5121     Out << '5';
   5122     break;
   5123   case Ctor_DefaultClosure:
   5124   case Ctor_CopyingClosure:
   5125     llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
   5126   }
   5127   if (InheritedFrom)
   5128     mangleName(InheritedFrom);
   5129 }
   5130 
   5131 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
   5132   // <ctor-dtor-name> ::= D0  # deleting destructor
   5133   //                  ::= D1  # complete object destructor
   5134   //                  ::= D2  # base object destructor
   5135   //
   5136   // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
   5137   switch (T) {
   5138   case Dtor_Deleting:
   5139     Out << "D0";
   5140     break;
   5141   case Dtor_Complete:
   5142     Out << "D1";
   5143     break;
   5144   case Dtor_Base:
   5145     Out << "D2";
   5146     break;
   5147   case Dtor_Comdat:
   5148     Out << "D5";
   5149     break;
   5150   }
   5151 }
   5152 
   5153 namespace {
   5154 // Helper to provide ancillary information on a template used to mangle its
   5155 // arguments.
   5156 struct TemplateArgManglingInfo {
   5157   TemplateDecl *ResolvedTemplate = nullptr;
   5158   bool SeenPackExpansionIntoNonPack = false;
   5159   const NamedDecl *UnresolvedExpandedPack = nullptr;
   5160 
   5161   TemplateArgManglingInfo(TemplateName TN) {
   5162     if (TemplateDecl *TD = TN.getAsTemplateDecl())
   5163       ResolvedTemplate = TD;
   5164   }
   5165 
   5166   /// Do we need to mangle template arguments with exactly correct types?
   5167   ///
   5168   /// This should be called exactly once for each parameter / argument pair, in
   5169   /// order.
   5170   bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) {
   5171     // We need correct types when the template-name is unresolved or when it
   5172     // names a template that is able to be overloaded.
   5173     if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
   5174       return true;
   5175 
   5176     // Move to the next parameter.
   5177     const NamedDecl *Param = UnresolvedExpandedPack;
   5178     if (!Param) {
   5179       assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
   5180              "no parameter for argument");
   5181       Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
   5182 
   5183       // If we reach an expanded parameter pack whose argument isn't in pack
   5184       // form, that means Sema couldn't figure out which arguments belonged to
   5185       // it, because it contains a pack expansion. Track the expanded pack for
   5186       // all further template arguments until we hit that pack expansion.
   5187       if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
   5188         assert(getExpandedPackSize(Param) &&
   5189                "failed to form pack argument for parameter pack");
   5190         UnresolvedExpandedPack = Param;
   5191       }
   5192     }
   5193 
   5194     // If we encounter a pack argument that is expanded into a non-pack
   5195     // parameter, we can no longer track parameter / argument correspondence,
   5196     // and need to use exact types from this point onwards.
   5197     if (Arg.isPackExpansion() &&
   5198         (!Param->isParameterPack() || UnresolvedExpandedPack)) {
   5199       SeenPackExpansionIntoNonPack = true;
   5200       return true;
   5201     }
   5202 
   5203     // We need exact types for function template arguments because they might be
   5204     // overloaded on template parameter type. As a special case, a member
   5205     // function template of a generic lambda is not overloadable.
   5206     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) {
   5207       auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
   5208       if (!RD || !RD->isGenericLambda())
   5209         return true;
   5210     }
   5211 
   5212     // Otherwise, we only need a correct type if the parameter has a deduced
   5213     // type.
   5214     //
   5215     // Note: for an expanded parameter pack, getType() returns the type prior
   5216     // to expansion. We could ask for the expanded type with getExpansionType(),
   5217     // but it doesn't matter because substitution and expansion don't affect
   5218     // whether a deduced type appears in the type.
   5219     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
   5220     return NTTP && NTTP->getType()->getContainedDeducedType();
   5221   }
   5222 };
   5223 }
   5224 
   5225 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
   5226                                         const TemplateArgumentLoc *TemplateArgs,
   5227                                         unsigned NumTemplateArgs) {
   5228   // <template-args> ::= I <template-arg>+ E
   5229   Out << 'I';
   5230   TemplateArgManglingInfo Info(TN);
   5231   for (unsigned i = 0; i != NumTemplateArgs; ++i)
   5232     mangleTemplateArg(TemplateArgs[i].getArgument(),
   5233                       Info.needExactType(i, TemplateArgs[i].getArgument()));
   5234   Out << 'E';
   5235 }
   5236 
   5237 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
   5238                                         const TemplateArgumentList &AL) {
   5239   // <template-args> ::= I <template-arg>+ E
   5240   Out << 'I';
   5241   TemplateArgManglingInfo Info(TN);
   5242   for (unsigned i = 0, e = AL.size(); i != e; ++i)
   5243     mangleTemplateArg(AL[i], Info.needExactType(i, AL[i]));
   5244   Out << 'E';
   5245 }
   5246 
   5247 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
   5248                                         const TemplateArgument *TemplateArgs,
   5249                                         unsigned NumTemplateArgs) {
   5250   // <template-args> ::= I <template-arg>+ E
   5251   Out << 'I';
   5252   TemplateArgManglingInfo Info(TN);
   5253   for (unsigned i = 0; i != NumTemplateArgs; ++i)
   5254     mangleTemplateArg(TemplateArgs[i], Info.needExactType(i, TemplateArgs[i]));
   5255   Out << 'E';
   5256 }
   5257 
   5258 void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
   5259   // <template-arg> ::= <type>              # type or template
   5260   //                ::= X <expression> E    # expression
   5261   //                ::= <expr-primary>      # simple expressions
   5262   //                ::= J <template-arg>* E # argument pack
   5263   if (!A.isInstantiationDependent() || A.isDependent())
   5264     A = Context.getASTContext().getCanonicalTemplateArgument(A);
   5265 
   5266   switch (A.getKind()) {
   5267   case TemplateArgument::Null:
   5268     llvm_unreachable("Cannot mangle NULL template argument");
   5269 
   5270   case TemplateArgument::Type:
   5271     mangleType(A.getAsType());
   5272     break;
   5273   case TemplateArgument::Template:
   5274     // This is mangled as <type>.
   5275     mangleType(A.getAsTemplate());
   5276     break;
   5277   case TemplateArgument::TemplateExpansion:
   5278     // <type>  ::= Dp <type>          # pack expansion (C++0x)
   5279     Out << "Dp";
   5280     mangleType(A.getAsTemplateOrTemplatePattern());
   5281     break;
   5282   case TemplateArgument::Expression:
   5283     mangleTemplateArgExpr(A.getAsExpr());
   5284     break;
   5285   case TemplateArgument::Integral:
   5286     mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
   5287     break;
   5288   case TemplateArgument::Declaration: {
   5289     //  <expr-primary> ::= L <mangled-name> E # external name
   5290     ValueDecl *D = A.getAsDecl();
   5291 
   5292     // Template parameter objects are modeled by reproducing a source form
   5293     // produced as if by aggregate initialization.
   5294     if (A.getParamTypeForDecl()->isRecordType()) {
   5295       auto *TPO = cast<TemplateParamObjectDecl>(D);
   5296       mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
   5297                                TPO->getValue(), /*TopLevel=*/true,
   5298                                NeedExactType);
   5299       break;
   5300     }
   5301 
   5302     ASTContext &Ctx = Context.getASTContext();
   5303     APValue Value;
   5304     if (D->isCXXInstanceMember())
   5305       // Simple pointer-to-member with no conversion.
   5306       Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
   5307     else if (D->getType()->isArrayType() &&
   5308              Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),
   5309                                 A.getParamTypeForDecl()) &&
   5310              Ctx.getLangOpts().getClangABICompat() >
   5311                  LangOptions::ClangABI::Ver11)
   5312       // Build a value corresponding to this implicit array-to-pointer decay.
   5313       Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
   5314                       {APValue::LValuePathEntry::ArrayIndex(0)},
   5315                       /*OnePastTheEnd=*/false);
   5316     else
   5317       // Regular pointer or reference to a declaration.
   5318       Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
   5319                       ArrayRef<APValue::LValuePathEntry>(),
   5320                       /*OnePastTheEnd=*/false);
   5321     mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
   5322                              NeedExactType);
   5323     break;
   5324   }
   5325   case TemplateArgument::NullPtr: {
   5326     mangleNullPointer(A.getNullPtrType());
   5327     break;
   5328   }
   5329   case TemplateArgument::Pack: {
   5330     //  <template-arg> ::= J <template-arg>* E
   5331     Out << 'J';
   5332     for (const auto &P : A.pack_elements())
   5333       mangleTemplateArg(P, NeedExactType);
   5334     Out << 'E';
   5335   }
   5336   }
   5337 }
   5338 
   5339 void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
   5340   ASTContext &Ctx = Context.getASTContext();
   5341   if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver11) {
   5342     mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
   5343     return;
   5344   }
   5345 
   5346   // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
   5347   // correctly in cases where the template argument was
   5348   // constructed from an expression rather than an already-evaluated
   5349   // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
   5350   // 'Li0E'.
   5351   //
   5352   // We did special-case DeclRefExpr to attempt to DTRT for that one
   5353   // expression-kind, but while doing so, unfortunately handled ParmVarDecl
   5354   // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
   5355   // the proper 'Xfp_E'.
   5356   E = E->IgnoreParenImpCasts();
   5357   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
   5358     const ValueDecl *D = DRE->getDecl();
   5359     if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
   5360       Out << 'L';
   5361       mangle(D);
   5362       Out << 'E';
   5363       return;
   5364     }
   5365   }
   5366   Out << 'X';
   5367   mangleExpression(E);
   5368   Out << 'E';
   5369 }
   5370 
   5371 /// Determine whether a given value is equivalent to zero-initialization for
   5372 /// the purpose of discarding a trailing portion of a 'tl' mangling.
   5373 ///
   5374 /// Note that this is not in general equivalent to determining whether the
   5375 /// value has an all-zeroes bit pattern.
   5376 static bool isZeroInitialized(QualType T, const APValue &V) {
   5377   // FIXME: mangleValueInTemplateArg has quadratic time complexity in
   5378   // pathological cases due to using this, but it's a little awkward
   5379   // to do this in linear time in general.
   5380   switch (V.getKind()) {
   5381   case APValue::None:
   5382   case APValue::Indeterminate:
   5383   case APValue::AddrLabelDiff:
   5384     return false;
   5385 
   5386   case APValue::Struct: {
   5387     const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
   5388     assert(RD && "unexpected type for record value");
   5389     unsigned I = 0;
   5390     for (const CXXBaseSpecifier &BS : RD->bases()) {
   5391       if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
   5392         return false;
   5393       ++I;
   5394     }
   5395     I = 0;
   5396     for (const FieldDecl *FD : RD->fields()) {
   5397       if (!FD->isUnnamedBitfield() &&
   5398           !isZeroInitialized(FD->getType(), V.getStructField(I)))
   5399         return false;
   5400       ++I;
   5401     }
   5402     return true;
   5403   }
   5404 
   5405   case APValue::Union: {
   5406     const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
   5407     assert(RD && "unexpected type for union value");
   5408     // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
   5409     for (const FieldDecl *FD : RD->fields()) {
   5410       if (!FD->isUnnamedBitfield())
   5411         return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
   5412                isZeroInitialized(FD->getType(), V.getUnionValue());
   5413     }
   5414     // If there are no fields (other than unnamed bitfields), the value is
   5415     // necessarily zero-initialized.
   5416     return true;
   5417   }
   5418 
   5419   case APValue::Array: {
   5420     QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
   5421     for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
   5422       if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
   5423         return false;
   5424     return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
   5425   }
   5426 
   5427   case APValue::Vector: {
   5428     const VectorType *VT = T->castAs<VectorType>();
   5429     for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
   5430       if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
   5431         return false;
   5432     return true;
   5433   }
   5434 
   5435   case APValue::Int:
   5436     return !V.getInt();
   5437 
   5438   case APValue::Float:
   5439     return V.getFloat().isPosZero();
   5440 
   5441   case APValue::FixedPoint:
   5442     return !V.getFixedPoint().getValue();
   5443 
   5444   case APValue::ComplexFloat:
   5445     return V.getComplexFloatReal().isPosZero() &&
   5446            V.getComplexFloatImag().isPosZero();
   5447 
   5448   case APValue::ComplexInt:
   5449     return !V.getComplexIntReal() && !V.getComplexIntImag();
   5450 
   5451   case APValue::LValue:
   5452     return V.isNullPointer();
   5453 
   5454   case APValue::MemberPointer:
   5455     return !V.getMemberPointerDecl();
   5456   }
   5457 
   5458   llvm_unreachable("Unhandled APValue::ValueKind enum");
   5459 }
   5460 
   5461 static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
   5462   QualType T = LV.getLValueBase().getType();
   5463   for (APValue::LValuePathEntry E : LV.getLValuePath()) {
   5464     if (const ArrayType *AT = Ctx.getAsArrayType(T))
   5465       T = AT->getElementType();
   5466     else if (const FieldDecl *FD =
   5467                  dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
   5468       T = FD->getType();
   5469     else
   5470       T = Ctx.getRecordType(
   5471           cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
   5472   }
   5473   return T;
   5474 }
   5475 
   5476 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
   5477                                               bool TopLevel,
   5478                                               bool NeedExactType) {
   5479   // Ignore all top-level cv-qualifiers, to match GCC.
   5480   Qualifiers Quals;
   5481   T = getASTContext().getUnqualifiedArrayType(T, Quals);
   5482 
   5483   // A top-level expression that's not a primary expression is wrapped in X...E.
   5484   bool IsPrimaryExpr = true;
   5485   auto NotPrimaryExpr = [&] {
   5486     if (TopLevel && IsPrimaryExpr)
   5487       Out << 'X';
   5488     IsPrimaryExpr = false;
   5489   };
   5490 
   5491   // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
   5492   switch (V.getKind()) {
   5493   case APValue::None:
   5494   case APValue::Indeterminate:
   5495     Out << 'L';
   5496     mangleType(T);
   5497     Out << 'E';
   5498     break;
   5499 
   5500   case APValue::AddrLabelDiff:
   5501     llvm_unreachable("unexpected value kind in template argument");
   5502 
   5503   case APValue::Struct: {
   5504     const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
   5505     assert(RD && "unexpected type for record value");
   5506 
   5507     // Drop trailing zero-initialized elements.
   5508     llvm::SmallVector<const FieldDecl *, 16> Fields(RD->field_begin(),
   5509                                                     RD->field_end());
   5510     while (
   5511         !Fields.empty() &&
   5512         (Fields.back()->isUnnamedBitfield() ||
   5513          isZeroInitialized(Fields.back()->getType(),
   5514                            V.getStructField(Fields.back()->getFieldIndex())))) {
   5515       Fields.pop_back();
   5516     }
   5517     llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
   5518     if (Fields.empty()) {
   5519       while (!Bases.empty() &&
   5520              isZeroInitialized(Bases.back().getType(),
   5521                                V.getStructBase(Bases.size() - 1)))
   5522         Bases = Bases.drop_back();
   5523     }
   5524 
   5525     // <expression> ::= tl <type> <braced-expression>* E
   5526     NotPrimaryExpr();
   5527     Out << "tl";
   5528     mangleType(T);
   5529     for (unsigned I = 0, N = Bases.size(); I != N; ++I)
   5530       mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
   5531     for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
   5532       if (Fields[I]->isUnnamedBitfield())
   5533         continue;
   5534       mangleValueInTemplateArg(Fields[I]->getType(),
   5535                                V.getStructField(Fields[I]->getFieldIndex()),
   5536                                false);
   5537     }
   5538     Out << 'E';
   5539     break;
   5540   }
   5541 
   5542   case APValue::Union: {
   5543     assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
   5544     const FieldDecl *FD = V.getUnionField();
   5545 
   5546     if (!FD) {
   5547       Out << 'L';
   5548       mangleType(T);
   5549       Out << 'E';
   5550       break;
   5551     }
   5552 
   5553     // <braced-expression> ::= di <field source-name> <braced-expression>
   5554     NotPrimaryExpr();
   5555     Out << "tl";
   5556     mangleType(T);
   5557     if (!isZeroInitialized(T, V)) {
   5558       Out << "di";
   5559       mangleSourceName(FD->getIdentifier());
   5560       mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
   5561     }
   5562     Out << 'E';
   5563     break;
   5564   }
   5565 
   5566   case APValue::Array: {
   5567     QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
   5568 
   5569     NotPrimaryExpr();
   5570     Out << "tl";
   5571     mangleType(T);
   5572 
   5573     // Drop trailing zero-initialized elements.
   5574     unsigned N = V.getArraySize();
   5575     if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
   5576       N = V.getArrayInitializedElts();
   5577       while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
   5578         --N;
   5579     }
   5580 
   5581     for (unsigned I = 0; I != N; ++I) {
   5582       const APValue &Elem = I < V.getArrayInitializedElts()
   5583                                 ? V.getArrayInitializedElt(I)
   5584                                 : V.getArrayFiller();
   5585       mangleValueInTemplateArg(ElemT, Elem, false);
   5586     }
   5587     Out << 'E';
   5588     break;
   5589   }
   5590 
   5591   case APValue::Vector: {
   5592     const VectorType *VT = T->castAs<VectorType>();
   5593 
   5594     NotPrimaryExpr();
   5595     Out << "tl";
   5596     mangleType(T);
   5597     unsigned N = V.getVectorLength();
   5598     while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
   5599       --N;
   5600     for (unsigned I = 0; I != N; ++I)
   5601       mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
   5602     Out << 'E';
   5603     break;
   5604   }
   5605 
   5606   case APValue::Int:
   5607     mangleIntegerLiteral(T, V.getInt());
   5608     break;
   5609 
   5610   case APValue::Float:
   5611     mangleFloatLiteral(T, V.getFloat());
   5612     break;
   5613 
   5614   case APValue::FixedPoint:
   5615     mangleFixedPointLiteral();
   5616     break;
   5617 
   5618   case APValue::ComplexFloat: {
   5619     const ComplexType *CT = T->castAs<ComplexType>();
   5620     NotPrimaryExpr();
   5621     Out << "tl";
   5622     mangleType(T);
   5623     if (!V.getComplexFloatReal().isPosZero() ||
   5624         !V.getComplexFloatImag().isPosZero())
   5625       mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
   5626     if (!V.getComplexFloatImag().isPosZero())
   5627       mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
   5628     Out << 'E';
   5629     break;
   5630   }
   5631 
   5632   case APValue::ComplexInt: {
   5633     const ComplexType *CT = T->castAs<ComplexType>();
   5634     NotPrimaryExpr();
   5635     Out << "tl";
   5636     mangleType(T);
   5637     if (V.getComplexIntReal().getBoolValue() ||
   5638         V.getComplexIntImag().getBoolValue())
   5639       mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
   5640     if (V.getComplexIntImag().getBoolValue())
   5641       mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
   5642     Out << 'E';
   5643     break;
   5644   }
   5645 
   5646   case APValue::LValue: {
   5647     // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
   5648     assert((T->isPointerType() || T->isReferenceType()) &&
   5649            "unexpected type for LValue template arg");
   5650 
   5651     if (V.isNullPointer()) {
   5652       mangleNullPointer(T);
   5653       break;
   5654     }
   5655 
   5656     APValue::LValueBase B = V.getLValueBase();
   5657     if (!B) {
   5658       // Non-standard mangling for integer cast to a pointer; this can only
   5659       // occur as an extension.
   5660       CharUnits Offset = V.getLValueOffset();
   5661       if (Offset.isZero()) {
   5662         // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
   5663         // a cast, because L <type> 0 E means something else.
   5664         NotPrimaryExpr();
   5665         Out << "rc";
   5666         mangleType(T);
   5667         Out << "Li0E";
   5668         if (TopLevel)
   5669           Out << 'E';
   5670       } else {
   5671         Out << "L";
   5672         mangleType(T);
   5673         Out << Offset.getQuantity() << 'E';
   5674       }
   5675       break;
   5676     }
   5677 
   5678     ASTContext &Ctx = Context.getASTContext();
   5679 
   5680     enum { Base, Offset, Path } Kind;
   5681     if (!V.hasLValuePath()) {
   5682       // Mangle as (T*)((char*)&base + N).
   5683       if (T->isReferenceType()) {
   5684         NotPrimaryExpr();
   5685         Out << "decvP";
   5686         mangleType(T->getPointeeType());
   5687       } else {
   5688         NotPrimaryExpr();
   5689         Out << "cv";
   5690         mangleType(T);
   5691       }
   5692       Out << "plcvPcad";
   5693       Kind = Offset;
   5694     } else {
   5695       if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) {
   5696         NotPrimaryExpr();
   5697         // A final conversion to the template parameter's type is usually
   5698         // folded into the 'so' mangling, but we can't do that for 'void*'
   5699         // parameters without introducing collisions.
   5700         if (NeedExactType && T->isVoidPointerType()) {
   5701           Out << "cv";
   5702           mangleType(T);
   5703         }
   5704         if (T->isPointerType())
   5705           Out << "ad";
   5706         Out << "so";
   5707         mangleType(T->isVoidPointerType()
   5708                        ? getLValueType(Ctx, V).getUnqualifiedType()
   5709                        : T->getPointeeType());
   5710         Kind = Path;
   5711       } else {
   5712         if (NeedExactType &&
   5713             !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
   5714             Ctx.getLangOpts().getClangABICompat() >
   5715                 LangOptions::ClangABI::Ver11) {
   5716           NotPrimaryExpr();
   5717           Out << "cv";
   5718           mangleType(T);
   5719         }
   5720         if (T->isPointerType()) {
   5721           NotPrimaryExpr();
   5722           Out << "ad";
   5723         }
   5724         Kind = Base;
   5725       }
   5726     }
   5727 
   5728     QualType TypeSoFar = B.getType();
   5729     if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
   5730       Out << 'L';
   5731       mangle(VD);
   5732       Out << 'E';
   5733     } else if (auto *E = B.dyn_cast<const Expr*>()) {
   5734       NotPrimaryExpr();
   5735       mangleExpression(E);
   5736     } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
   5737       NotPrimaryExpr();
   5738       Out << "ti";
   5739       mangleType(QualType(TI.getType(), 0));
   5740     } else {
   5741       // We should never see dynamic allocations here.
   5742       llvm_unreachable("unexpected lvalue base kind in template argument");
   5743     }
   5744 
   5745     switch (Kind) {
   5746     case Base:
   5747       break;
   5748 
   5749     case Offset:
   5750       Out << 'L';
   5751       mangleType(Ctx.getPointerDiffType());
   5752       mangleNumber(V.getLValueOffset().getQuantity());
   5753       Out << 'E';
   5754       break;
   5755 
   5756     case Path:
   5757       // <expression> ::= so <referent type> <expr> [<offset number>]
   5758       //                  <union-selector>* [p] E
   5759       if (!V.getLValueOffset().isZero())
   5760         mangleNumber(V.getLValueOffset().getQuantity());
   5761 
   5762       // We model a past-the-end array pointer as array indexing with index N,
   5763       // not with the "past the end" flag. Compensate for that.
   5764       bool OnePastTheEnd = V.isLValueOnePastTheEnd();
   5765 
   5766       for (APValue::LValuePathEntry E : V.getLValuePath()) {
   5767         if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
   5768           if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
   5769             OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
   5770           TypeSoFar = AT->getElementType();
   5771         } else {
   5772           const Decl *D = E.getAsBaseOrMember().getPointer();
   5773           if (auto *FD = dyn_cast<FieldDecl>(D)) {
   5774             // <union-selector> ::= _ <number>
   5775             if (FD->getParent()->isUnion()) {
   5776               Out << '_';
   5777               if (FD->getFieldIndex())
   5778                 Out << (FD->getFieldIndex() - 1);
   5779             }
   5780             TypeSoFar = FD->getType();
   5781           } else {
   5782             TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));
   5783           }
   5784         }
   5785       }
   5786 
   5787       if (OnePastTheEnd)
   5788         Out << 'p';
   5789       Out << 'E';
   5790       break;
   5791     }
   5792 
   5793     break;
   5794   }
   5795 
   5796   case APValue::MemberPointer:
   5797     // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
   5798     if (!V.getMemberPointerDecl()) {
   5799       mangleNullPointer(T);
   5800       break;
   5801     }
   5802 
   5803     ASTContext &Ctx = Context.getASTContext();
   5804 
   5805     NotPrimaryExpr();
   5806     if (!V.getMemberPointerPath().empty()) {
   5807       Out << "mc";
   5808       mangleType(T);
   5809     } else if (NeedExactType &&
   5810                !Ctx.hasSameType(
   5811                    T->castAs<MemberPointerType>()->getPointeeType(),
   5812                    V.getMemberPointerDecl()->getType()) &&
   5813                Ctx.getLangOpts().getClangABICompat() >
   5814                    LangOptions::ClangABI::Ver11) {
   5815       Out << "cv";
   5816       mangleType(T);
   5817     }
   5818     Out << "adL";
   5819     mangle(V.getMemberPointerDecl());
   5820     Out << 'E';
   5821     if (!V.getMemberPointerPath().empty()) {
   5822       CharUnits Offset =
   5823           Context.getASTContext().getMemberPointerPathAdjustment(V);
   5824       if (!Offset.isZero())
   5825         mangleNumber(Offset.getQuantity());
   5826       Out << 'E';
   5827     }
   5828     break;
   5829   }
   5830 
   5831   if (TopLevel && !IsPrimaryExpr)
   5832     Out << 'E';
   5833 }
   5834 
   5835 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
   5836   // <template-param> ::= T_    # first template parameter
   5837   //                  ::= T <parameter-2 non-negative number> _
   5838   //                  ::= TL <L-1 non-negative number> __
   5839   //                  ::= TL <L-1 non-negative number> _
   5840   //                         <parameter-2 non-negative number> _
   5841   //
   5842   // The latter two manglings are from a proposal here:
   5843   // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
   5844   Out << 'T';
   5845   if (Depth != 0)
   5846     Out << 'L' << (Depth - 1) << '_';
   5847   if (Index != 0)
   5848     Out << (Index - 1);
   5849   Out << '_';
   5850 }
   5851 
   5852 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
   5853   if (SeqID == 1)
   5854     Out << '0';
   5855   else if (SeqID > 1) {
   5856     SeqID--;
   5857 
   5858     // <seq-id> is encoded in base-36, using digits and upper case letters.
   5859     char Buffer[7]; // log(2**32) / log(36) ~= 7
   5860     MutableArrayRef<char> BufferRef(Buffer);
   5861     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
   5862 
   5863     for (; SeqID != 0; SeqID /= 36) {
   5864       unsigned C = SeqID % 36;
   5865       *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
   5866     }
   5867 
   5868     Out.write(I.base(), I - BufferRef.rbegin());
   5869   }
   5870   Out << '_';
   5871 }
   5872 
   5873 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
   5874   bool result = mangleSubstitution(tname);
   5875   assert(result && "no existing substitution for template name");
   5876   (void) result;
   5877 }
   5878 
   5879 // <substitution> ::= S <seq-id> _
   5880 //                ::= S_
   5881 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
   5882   // Try one of the standard substitutions first.
   5883   if (mangleStandardSubstitution(ND))
   5884     return true;
   5885 
   5886   ND = cast<NamedDecl>(ND->getCanonicalDecl());
   5887   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
   5888 }
   5889 
   5890 /// Determine whether the given type has any qualifiers that are relevant for
   5891 /// substitutions.
   5892 static bool hasMangledSubstitutionQualifiers(QualType T) {
   5893   Qualifiers Qs = T.getQualifiers();
   5894   return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
   5895 }
   5896 
   5897 bool CXXNameMangler::mangleSubstitution(QualType T) {
   5898   if (!hasMangledSubstitutionQualifiers(T)) {
   5899     if (const RecordType *RT = T->getAs<RecordType>())
   5900       return mangleSubstitution(RT->getDecl());
   5901   }
   5902 
   5903   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
   5904 
   5905   return mangleSubstitution(TypePtr);
   5906 }
   5907 
   5908 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
   5909   if (TemplateDecl *TD = Template.getAsTemplateDecl())
   5910     return mangleSubstitution(TD);
   5911 
   5912   Template = Context.getASTContext().getCanonicalTemplateName(Template);
   5913   return mangleSubstitution(
   5914                       reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
   5915 }
   5916 
   5917 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
   5918   llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
   5919   if (I == Substitutions.end())
   5920     return false;
   5921 
   5922   unsigned SeqID = I->second;
   5923   Out << 'S';
   5924   mangleSeqID(SeqID);
   5925 
   5926   return true;
   5927 }
   5928 
   5929 static bool isCharType(QualType T) {
   5930   if (T.isNull())
   5931     return false;
   5932 
   5933   return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
   5934     T->isSpecificBuiltinType(BuiltinType::Char_U);
   5935 }
   5936 
   5937 /// Returns whether a given type is a template specialization of a given name
   5938 /// with a single argument of type char.
   5939 static bool isCharSpecialization(QualType T, const char *Name) {
   5940   if (T.isNull())
   5941     return false;
   5942 
   5943   const RecordType *RT = T->getAs<RecordType>();
   5944   if (!RT)
   5945     return false;
   5946 
   5947   const ClassTemplateSpecializationDecl *SD =
   5948     dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
   5949   if (!SD)
   5950     return false;
   5951 
   5952   if (!isStdNamespace(getEffectiveDeclContext(SD)))
   5953     return false;
   5954 
   5955   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
   5956   if (TemplateArgs.size() != 1)
   5957     return false;
   5958 
   5959   if (!isCharType(TemplateArgs[0].getAsType()))
   5960     return false;
   5961 
   5962   return SD->getIdentifier()->getName() == Name;
   5963 }
   5964 
   5965 template <std::size_t StrLen>
   5966 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
   5967                                        const char (&Str)[StrLen]) {
   5968   if (!SD->getIdentifier()->isStr(Str))
   5969     return false;
   5970 
   5971   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
   5972   if (TemplateArgs.size() != 2)
   5973     return false;
   5974 
   5975   if (!isCharType(TemplateArgs[0].getAsType()))
   5976     return false;
   5977 
   5978   if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
   5979     return false;
   5980 
   5981   return true;
   5982 }
   5983 
   5984 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
   5985   // <substitution> ::= St # ::std::
   5986   if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
   5987     if (isStd(NS)) {
   5988       Out << "St";
   5989       return true;
   5990     }
   5991   }
   5992 
   5993   if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
   5994     if (!isStdNamespace(getEffectiveDeclContext(TD)))
   5995       return false;
   5996 
   5997     // <substitution> ::= Sa # ::std::allocator
   5998     if (TD->getIdentifier()->isStr("allocator")) {
   5999       Out << "Sa";
   6000       return true;
   6001     }
   6002 
   6003     // <<substitution> ::= Sb # ::std::basic_string
   6004     if (TD->getIdentifier()->isStr("basic_string")) {
   6005       Out << "Sb";
   6006       return true;
   6007     }
   6008   }
   6009 
   6010   if (const ClassTemplateSpecializationDecl *SD =
   6011         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
   6012     if (!isStdNamespace(getEffectiveDeclContext(SD)))
   6013       return false;
   6014 
   6015     //    <substitution> ::= Ss # ::std::basic_string<char,
   6016     //                            ::std::char_traits<char>,
   6017     //                            ::std::allocator<char> >
   6018     if (SD->getIdentifier()->isStr("basic_string")) {
   6019       const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
   6020 
   6021       if (TemplateArgs.size() != 3)
   6022         return false;
   6023 
   6024       if (!isCharType(TemplateArgs[0].getAsType()))
   6025         return false;
   6026 
   6027       if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
   6028         return false;
   6029 
   6030       if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
   6031         return false;
   6032 
   6033       Out << "Ss";
   6034       return true;
   6035     }
   6036 
   6037     //    <substitution> ::= Si # ::std::basic_istream<char,
   6038     //                            ::std::char_traits<char> >
   6039     if (isStreamCharSpecialization(SD, "basic_istream")) {
   6040       Out << "Si";
   6041       return true;
   6042     }
   6043 
   6044     //    <substitution> ::= So # ::std::basic_ostream<char,
   6045     //                            ::std::char_traits<char> >
   6046     if (isStreamCharSpecialization(SD, "basic_ostream")) {
   6047       Out << "So";
   6048       return true;
   6049     }
   6050 
   6051     //    <substitution> ::= Sd # ::std::basic_iostream<char,
   6052     //                            ::std::char_traits<char> >
   6053     if (isStreamCharSpecialization(SD, "basic_iostream")) {
   6054       Out << "Sd";
   6055       return true;
   6056     }
   6057   }
   6058   return false;
   6059 }
   6060 
   6061 void CXXNameMangler::addSubstitution(QualType T) {
   6062   if (!hasMangledSubstitutionQualifiers(T)) {
   6063     if (const RecordType *RT = T->getAs<RecordType>()) {
   6064       addSubstitution(RT->getDecl());
   6065       return;
   6066     }
   6067   }
   6068 
   6069   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
   6070   addSubstitution(TypePtr);
   6071 }
   6072 
   6073 void CXXNameMangler::addSubstitution(TemplateName Template) {
   6074   if (TemplateDecl *TD = Template.getAsTemplateDecl())
   6075     return addSubstitution(TD);
   6076 
   6077   Template = Context.getASTContext().getCanonicalTemplateName(Template);
   6078   addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
   6079 }
   6080 
   6081 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
   6082   assert(!Substitutions.count(Ptr) && "Substitution already exists!");
   6083   Substitutions[Ptr] = SeqID++;
   6084 }
   6085 
   6086 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
   6087   assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
   6088   if (Other->SeqID > SeqID) {
   6089     Substitutions.swap(Other->Substitutions);
   6090     SeqID = Other->SeqID;
   6091   }
   6092 }
   6093 
   6094 CXXNameMangler::AbiTagList
   6095 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
   6096   // When derived abi tags are disabled there is no need to make any list.
   6097   if (DisableDerivedAbiTags)
   6098     return AbiTagList();
   6099 
   6100   llvm::raw_null_ostream NullOutStream;
   6101   CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
   6102   TrackReturnTypeTags.disableDerivedAbiTags();
   6103 
   6104   const FunctionProtoType *Proto =
   6105       cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
   6106   FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
   6107   TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
   6108   TrackReturnTypeTags.mangleType(Proto->getReturnType());
   6109   TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
   6110   TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
   6111 
   6112   return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
   6113 }
   6114 
   6115 CXXNameMangler::AbiTagList
   6116 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
   6117   // When derived abi tags are disabled there is no need to make any list.
   6118   if (DisableDerivedAbiTags)
   6119     return AbiTagList();
   6120 
   6121   llvm::raw_null_ostream NullOutStream;
   6122   CXXNameMangler TrackVariableType(*this, NullOutStream);
   6123   TrackVariableType.disableDerivedAbiTags();
   6124 
   6125   TrackVariableType.mangleType(VD->getType());
   6126 
   6127   return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
   6128 }
   6129 
   6130 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
   6131                                        const VarDecl *VD) {
   6132   llvm::raw_null_ostream NullOutStream;
   6133   CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
   6134   TrackAbiTags.mangle(VD);
   6135   return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
   6136 }
   6137 
   6138 //
   6139 
   6140 /// Mangles the name of the declaration D and emits that name to the given
   6141 /// output stream.
   6142 ///
   6143 /// If the declaration D requires a mangled name, this routine will emit that
   6144 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
   6145 /// and this routine will return false. In this case, the caller should just
   6146 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
   6147 /// name.
   6148 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
   6149                                              raw_ostream &Out) {
   6150   const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
   6151   assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&
   6152          "Invalid mangleName() call, argument is not a variable or function!");
   6153 
   6154   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
   6155                                  getASTContext().getSourceManager(),
   6156                                  "Mangling declaration");
   6157 
   6158   if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
   6159     auto Type = GD.getCtorType();
   6160     CXXNameMangler Mangler(*this, Out, CD, Type);
   6161     return Mangler.mangle(GlobalDecl(CD, Type));
   6162   }
   6163 
   6164   if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
   6165     auto Type = GD.getDtorType();
   6166     CXXNameMangler Mangler(*this, Out, DD, Type);
   6167     return Mangler.mangle(GlobalDecl(DD, Type));
   6168   }
   6169 
   6170   CXXNameMangler Mangler(*this, Out, D);
   6171   Mangler.mangle(GD);
   6172 }
   6173 
   6174 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
   6175                                                    raw_ostream &Out) {
   6176   CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
   6177   Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
   6178 }
   6179 
   6180 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
   6181                                                    raw_ostream &Out) {
   6182   CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
   6183   Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
   6184 }
   6185 
   6186 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
   6187                                            const ThunkInfo &Thunk,
   6188                                            raw_ostream &Out) {
   6189   //  <special-name> ::= T <call-offset> <base encoding>
   6190   //                      # base is the nominal target function of thunk
   6191   //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
   6192   //                      # base is the nominal target function of thunk
   6193   //                      # first call-offset is 'this' adjustment
   6194   //                      # second call-offset is result adjustment
   6195 
   6196   assert(!isa<CXXDestructorDecl>(MD) &&
   6197          "Use mangleCXXDtor for destructor decls!");
   6198   CXXNameMangler Mangler(*this, Out);
   6199   Mangler.getStream() << "_ZT";
   6200   if (!Thunk.Return.isEmpty())
   6201     Mangler.getStream() << 'c';
   6202 
   6203   // Mangle the 'this' pointer adjustment.
   6204   Mangler.mangleCallOffset(Thunk.This.NonVirtual,
   6205                            Thunk.This.Virtual.Itanium.VCallOffsetOffset);
   6206 
   6207   // Mangle the return pointer adjustment if there is one.
   6208   if (!Thunk.Return.isEmpty())
   6209     Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
   6210                              Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
   6211 
   6212   Mangler.mangleFunctionEncoding(MD);
   6213 }
   6214 
   6215 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
   6216     const CXXDestructorDecl *DD, CXXDtorType Type,
   6217     const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
   6218   //  <special-name> ::= T <call-offset> <base encoding>
   6219   //                      # base is the nominal target function of thunk
   6220   CXXNameMangler Mangler(*this, Out, DD, Type);
   6221   Mangler.getStream() << "_ZT";
   6222 
   6223   // Mangle the 'this' pointer adjustment.
   6224   Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
   6225                            ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
   6226 
   6227   Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
   6228 }
   6229 
   6230 /// Returns the mangled name for a guard variable for the passed in VarDecl.
   6231 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
   6232                                                          raw_ostream &Out) {
   6233   //  <special-name> ::= GV <object name>       # Guard variable for one-time
   6234   //                                            # initialization
   6235   CXXNameMangler Mangler(*this, Out);
   6236   // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
   6237   // be a bug that is fixed in trunk.
   6238   Mangler.getStream() << "_ZGV";
   6239   Mangler.mangleName(D);
   6240 }
   6241 
   6242 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
   6243                                                         raw_ostream &Out) {
   6244   // These symbols are internal in the Itanium ABI, so the names don't matter.
   6245   // Clang has traditionally used this symbol and allowed LLVM to adjust it to
   6246   // avoid duplicate symbols.
   6247   Out << "__cxx_global_var_init";
   6248 }
   6249 
   6250 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
   6251                                                              raw_ostream &Out) {
   6252   // Prefix the mangling of D with __dtor_.
   6253   CXXNameMangler Mangler(*this, Out);
   6254   Mangler.getStream() << "__dtor_";
   6255   if (shouldMangleDeclName(D))
   6256     Mangler.mangle(D);
   6257   else
   6258     Mangler.getStream() << D->getName();
   6259 }
   6260 
   6261 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
   6262                                                            raw_ostream &Out) {
   6263   // Clang generates these internal-linkage functions as part of its
   6264   // implementation of the XL ABI.
   6265   CXXNameMangler Mangler(*this, Out);
   6266   Mangler.getStream() << "__finalize_";
   6267   if (shouldMangleDeclName(D))
   6268     Mangler.mangle(D);
   6269   else
   6270     Mangler.getStream() << D->getName();
   6271 }
   6272 
   6273 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
   6274     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
   6275   CXXNameMangler Mangler(*this, Out);
   6276   Mangler.getStream() << "__filt_";
   6277   if (shouldMangleDeclName(EnclosingDecl))
   6278     Mangler.mangle(EnclosingDecl);
   6279   else
   6280     Mangler.getStream() << EnclosingDecl->getName();
   6281 }
   6282 
   6283 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
   6284     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
   6285   CXXNameMangler Mangler(*this, Out);
   6286   Mangler.getStream() << "__fin_";
   6287   if (shouldMangleDeclName(EnclosingDecl))
   6288     Mangler.mangle(EnclosingDecl);
   6289   else
   6290     Mangler.getStream() << EnclosingDecl->getName();
   6291 }
   6292 
   6293 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
   6294                                                             raw_ostream &Out) {
   6295   //  <special-name> ::= TH <object name>
   6296   CXXNameMangler Mangler(*this, Out);
   6297   Mangler.getStream() << "_ZTH";
   6298   Mangler.mangleName(D);
   6299 }
   6300 
   6301 void
   6302 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
   6303                                                           raw_ostream &Out) {
   6304   //  <special-name> ::= TW <object name>
   6305   CXXNameMangler Mangler(*this, Out);
   6306   Mangler.getStream() << "_ZTW";
   6307   Mangler.mangleName(D);
   6308 }
   6309 
   6310 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
   6311                                                         unsigned ManglingNumber,
   6312                                                         raw_ostream &Out) {
   6313   // We match the GCC mangling here.
   6314   //  <special-name> ::= GR <object name>
   6315   CXXNameMangler Mangler(*this, Out);
   6316   Mangler.getStream() << "_ZGR";
   6317   Mangler.mangleName(D);
   6318   assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
   6319   Mangler.mangleSeqID(ManglingNumber - 1);
   6320 }
   6321 
   6322 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
   6323                                                raw_ostream &Out) {
   6324   // <special-name> ::= TV <type>  # virtual table
   6325   CXXNameMangler Mangler(*this, Out);
   6326   Mangler.getStream() << "_ZTV";
   6327   Mangler.mangleNameOrStandardSubstitution(RD);
   6328 }
   6329 
   6330 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
   6331                                             raw_ostream &Out) {
   6332   // <special-name> ::= TT <type>  # VTT structure
   6333   CXXNameMangler Mangler(*this, Out);
   6334   Mangler.getStream() << "_ZTT";
   6335   Mangler.mangleNameOrStandardSubstitution(RD);
   6336 }
   6337 
   6338 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
   6339                                                    int64_t Offset,
   6340                                                    const CXXRecordDecl *Type,
   6341                                                    raw_ostream &Out) {
   6342   // <special-name> ::= TC <type> <offset number> _ <base type>
   6343   CXXNameMangler Mangler(*this, Out);
   6344   Mangler.getStream() << "_ZTC";
   6345   Mangler.mangleNameOrStandardSubstitution(RD);
   6346   Mangler.getStream() << Offset;
   6347   Mangler.getStream() << '_';
   6348   Mangler.mangleNameOrStandardSubstitution(Type);
   6349 }
   6350 
   6351 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
   6352   // <special-name> ::= TI <type>  # typeinfo structure
   6353   assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
   6354   CXXNameMangler Mangler(*this, Out);
   6355   Mangler.getStream() << "_ZTI";
   6356   Mangler.mangleType(Ty);
   6357 }
   6358 
   6359 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
   6360                                                  raw_ostream &Out) {
   6361   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
   6362   CXXNameMangler Mangler(*this, Out);
   6363   Mangler.getStream() << "_ZTS";
   6364   Mangler.mangleType(Ty);
   6365 }
   6366 
   6367 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
   6368   mangleCXXRTTIName(Ty, Out);
   6369 }
   6370 
   6371 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
   6372   llvm_unreachable("Can't mangle string literals");
   6373 }
   6374 
   6375 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
   6376                                                raw_ostream &Out) {
   6377   CXXNameMangler Mangler(*this, Out);
   6378   Mangler.mangleLambdaSig(Lambda);
   6379 }
   6380 
   6381 ItaniumMangleContext *
   6382 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
   6383   return new ItaniumMangleContextImpl(Context, Diags);
   6384 }
   6385