xref: /freebsd/contrib/llvm-project/clang/lib/AST/ItaniumMangle.cpp (revision 36b606ae6aa4b24061096ba18582e0a08ccd5dba)
10b57cec5SDimitry Andric //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Implements C++ name mangling according to the Itanium C++ ABI,
100b57cec5SDimitry Andric // which is used in GCC 3.2 and newer (and many compilers that are
110b57cec5SDimitry Andric // ABI-compatible with GCC):
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //   http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
165ffd83dbSDimitry Andric 
170b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
180b57cec5SDimitry Andric #include "clang/AST/Attr.h"
190b57cec5SDimitry Andric #include "clang/AST/Decl.h"
200b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
210b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
220b57cec5SDimitry Andric #include "clang/AST/DeclOpenMP.h"
230b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
240b57cec5SDimitry Andric #include "clang/AST/Expr.h"
250b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
26fe6060f1SDimitry Andric #include "clang/AST/ExprConcepts.h"
270b57cec5SDimitry Andric #include "clang/AST/ExprObjC.h"
28fe6060f1SDimitry Andric #include "clang/AST/Mangle.h"
290b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
300b57cec5SDimitry Andric #include "clang/Basic/ABI.h"
315f757f3fSDimitry Andric #include "clang/Basic/DiagnosticAST.h"
325ffd83dbSDimitry Andric #include "clang/Basic/Module.h"
330b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
340b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
35fe6060f1SDimitry Andric #include "clang/Basic/Thunk.h"
360b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
370b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
380b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
3906c3fb27SDimitry Andric #include "llvm/TargetParser/RISCVTargetParser.h"
40bdd1243dSDimitry Andric #include <optional>
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric using namespace clang;
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric namespace {
450b57cec5SDimitry Andric 
isLocalContainerContext(const DeclContext * DC)460b57cec5SDimitry Andric static bool isLocalContainerContext(const DeclContext *DC) {
470b57cec5SDimitry Andric   return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
480b57cec5SDimitry Andric }
490b57cec5SDimitry Andric 
getStructor(const FunctionDecl * fn)500b57cec5SDimitry Andric static const FunctionDecl *getStructor(const FunctionDecl *fn) {
510b57cec5SDimitry Andric   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
520b57cec5SDimitry Andric     return ftd->getTemplatedDecl();
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric   return fn;
550b57cec5SDimitry Andric }
560b57cec5SDimitry Andric 
getStructor(const NamedDecl * decl)570b57cec5SDimitry Andric static const NamedDecl *getStructor(const NamedDecl *decl) {
580b57cec5SDimitry Andric   const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
590b57cec5SDimitry Andric   return (fn ? getStructor(fn) : decl);
600b57cec5SDimitry Andric }
610b57cec5SDimitry Andric 
isLambda(const NamedDecl * ND)620b57cec5SDimitry Andric static bool isLambda(const NamedDecl *ND) {
630b57cec5SDimitry Andric   const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
640b57cec5SDimitry Andric   if (!Record)
650b57cec5SDimitry Andric     return false;
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric   return Record->isLambda();
680b57cec5SDimitry Andric }
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric static const unsigned UnknownArity = ~0U;
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric class ItaniumMangleContextImpl : public ItaniumMangleContext {
730b57cec5SDimitry Andric   typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
740b57cec5SDimitry Andric   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
750b57cec5SDimitry Andric   llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
76fe6060f1SDimitry Andric   const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
772a66634dSDimitry Andric   NamespaceDecl *StdNamespace = nullptr;
780b57cec5SDimitry Andric 
79fe6060f1SDimitry Andric   bool NeedsUniqueInternalLinkageNames = false;
80d409305fSDimitry Andric 
810b57cec5SDimitry Andric public:
ItaniumMangleContextImpl(ASTContext & Context,DiagnosticsEngine & Diags,DiscriminatorOverrideTy DiscriminatorOverride,bool IsAux=false)82fe6060f1SDimitry Andric   explicit ItaniumMangleContextImpl(
83fe6060f1SDimitry Andric       ASTContext &Context, DiagnosticsEngine &Diags,
8481ad6265SDimitry Andric       DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
8581ad6265SDimitry Andric       : ItaniumMangleContext(Context, Diags, IsAux),
86fe6060f1SDimitry Andric         DiscriminatorOverride(DiscriminatorOverride) {}
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric   /// @name Mangler Entry Points
890b57cec5SDimitry Andric   /// @{
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   bool shouldMangleCXXName(const NamedDecl *D) override;
shouldMangleStringLiteral(const StringLiteral *)920b57cec5SDimitry Andric   bool shouldMangleStringLiteral(const StringLiteral *) override {
930b57cec5SDimitry Andric     return false;
940b57cec5SDimitry Andric   }
95d409305fSDimitry Andric 
96fe6060f1SDimitry Andric   bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
needsUniqueInternalLinkageNames()97fe6060f1SDimitry Andric   void needsUniqueInternalLinkageNames() override {
98fe6060f1SDimitry Andric     NeedsUniqueInternalLinkageNames = true;
99fe6060f1SDimitry Andric   }
100d409305fSDimitry Andric 
1015ffd83dbSDimitry Andric   void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
1020fca6ea1SDimitry Andric   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, bool,
1030b57cec5SDimitry Andric                    raw_ostream &) override;
1040b57cec5SDimitry Andric   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
1050fca6ea1SDimitry Andric                           const ThunkInfo &Thunk, bool, raw_ostream &) override;
1060b57cec5SDimitry Andric   void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
1070b57cec5SDimitry Andric                                 raw_ostream &) override;
1080b57cec5SDimitry Andric   void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
1090b57cec5SDimitry Andric   void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
1100b57cec5SDimitry Andric   void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
1110b57cec5SDimitry Andric                            const CXXRecordDecl *Type, raw_ostream &) override;
1120b57cec5SDimitry Andric   void mangleCXXRTTI(QualType T, raw_ostream &) override;
11306c3fb27SDimitry Andric   void mangleCXXRTTIName(QualType T, raw_ostream &,
11406c3fb27SDimitry Andric                          bool NormalizeIntegers) override;
1155f757f3fSDimitry Andric   void mangleCanonicalTypeName(QualType T, raw_ostream &,
11606c3fb27SDimitry Andric                                bool NormalizeIntegers) override;
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
1190b57cec5SDimitry Andric   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
1200b57cec5SDimitry Andric   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
1210b57cec5SDimitry Andric   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
1220b57cec5SDimitry Andric   void mangleDynamicAtExitDestructor(const VarDecl *D,
1230b57cec5SDimitry Andric                                      raw_ostream &Out) override;
1245ffd83dbSDimitry Andric   void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
125bdd1243dSDimitry Andric   void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
1260b57cec5SDimitry Andric                                  raw_ostream &Out) override;
127bdd1243dSDimitry Andric   void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
1280b57cec5SDimitry Andric                              raw_ostream &Out) override;
1290b57cec5SDimitry Andric   void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
1300b57cec5SDimitry Andric   void mangleItaniumThreadLocalWrapper(const VarDecl *D,
1310b57cec5SDimitry Andric                                        raw_ostream &) override;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
1340b57cec5SDimitry Andric 
135a7dea167SDimitry Andric   void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
136a7dea167SDimitry Andric 
13781ad6265SDimitry Andric   void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
13881ad6265SDimitry Andric 
getNextDiscriminator(const NamedDecl * ND,unsigned & disc)1390b57cec5SDimitry Andric   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
1400b57cec5SDimitry Andric     // Lambda closure types are already numbered.
1410b57cec5SDimitry Andric     if (isLambda(ND))
1420b57cec5SDimitry Andric       return false;
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric     // Anonymous tags are already numbered.
1450b57cec5SDimitry Andric     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
1460b57cec5SDimitry Andric       if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
1470b57cec5SDimitry Andric         return false;
1480b57cec5SDimitry Andric     }
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric     // Use the canonical number for externally visible decls.
1510b57cec5SDimitry Andric     if (ND->isExternallyVisible()) {
15281ad6265SDimitry Andric       unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
1530b57cec5SDimitry Andric       if (discriminator == 1)
1540b57cec5SDimitry Andric         return false;
1550b57cec5SDimitry Andric       disc = discriminator - 2;
1560b57cec5SDimitry Andric       return true;
1570b57cec5SDimitry Andric     }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric     // Make up a reasonable number for internal decls.
1600b57cec5SDimitry Andric     unsigned &discriminator = Uniquifier[ND];
1610b57cec5SDimitry Andric     if (!discriminator) {
1620b57cec5SDimitry Andric       const DeclContext *DC = getEffectiveDeclContext(ND);
1630b57cec5SDimitry Andric       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
1640b57cec5SDimitry Andric     }
1650b57cec5SDimitry Andric     if (discriminator == 1)
1660b57cec5SDimitry Andric       return false;
1670b57cec5SDimitry Andric     disc = discriminator-2;
1680b57cec5SDimitry Andric     return true;
1690b57cec5SDimitry Andric   }
170fe6060f1SDimitry Andric 
getLambdaString(const CXXRecordDecl * Lambda)171fe6060f1SDimitry Andric   std::string getLambdaString(const CXXRecordDecl *Lambda) override {
172fe6060f1SDimitry Andric     // This function matches the one in MicrosoftMangle, which returns
173fe6060f1SDimitry Andric     // the string that is used in lambda mangled names.
174fe6060f1SDimitry Andric     assert(Lambda->isLambda() && "RD must be a lambda!");
175fe6060f1SDimitry Andric     std::string Name("<lambda");
176fe6060f1SDimitry Andric     Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
177fe6060f1SDimitry Andric     unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
178fe6060f1SDimitry Andric     unsigned LambdaId;
179fe6060f1SDimitry Andric     const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
180fe6060f1SDimitry Andric     const FunctionDecl *Func =
181fe6060f1SDimitry Andric         Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
182fe6060f1SDimitry Andric 
183fe6060f1SDimitry Andric     if (Func) {
184fe6060f1SDimitry Andric       unsigned DefaultArgNo =
185fe6060f1SDimitry Andric           Func->getNumParams() - Parm->getFunctionScopeIndex();
186fe6060f1SDimitry Andric       Name += llvm::utostr(DefaultArgNo);
187fe6060f1SDimitry Andric       Name += "_";
188fe6060f1SDimitry Andric     }
189fe6060f1SDimitry Andric 
190fe6060f1SDimitry Andric     if (LambdaManglingNumber)
191fe6060f1SDimitry Andric       LambdaId = LambdaManglingNumber;
192fe6060f1SDimitry Andric     else
193fe6060f1SDimitry Andric       LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
194fe6060f1SDimitry Andric 
195fe6060f1SDimitry Andric     Name += llvm::utostr(LambdaId);
196fe6060f1SDimitry Andric     Name += '>';
197fe6060f1SDimitry Andric     return Name;
198fe6060f1SDimitry Andric   }
199fe6060f1SDimitry Andric 
getDiscriminatorOverride() const200fe6060f1SDimitry Andric   DiscriminatorOverrideTy getDiscriminatorOverride() const override {
201fe6060f1SDimitry Andric     return DiscriminatorOverride;
202fe6060f1SDimitry Andric   }
203fe6060f1SDimitry Andric 
2042a66634dSDimitry Andric   NamespaceDecl *getStdNamespace();
2052a66634dSDimitry Andric 
2062a66634dSDimitry Andric   const DeclContext *getEffectiveDeclContext(const Decl *D);
getEffectiveParentContext(const DeclContext * DC)2072a66634dSDimitry Andric   const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
2082a66634dSDimitry Andric     return getEffectiveDeclContext(cast<Decl>(DC));
2092a66634dSDimitry Andric   }
2102a66634dSDimitry Andric 
2112a66634dSDimitry Andric   bool isInternalLinkageDecl(const NamedDecl *ND);
2122a66634dSDimitry Andric 
2130b57cec5SDimitry Andric   /// @}
2140b57cec5SDimitry Andric };
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric /// Manage the mangling of a single name.
2170b57cec5SDimitry Andric class CXXNameMangler {
2180b57cec5SDimitry Andric   ItaniumMangleContextImpl &Context;
2190b57cec5SDimitry Andric   raw_ostream &Out;
22006c3fb27SDimitry Andric   /// Normalize integer types for cross-language CFI support with other
22106c3fb27SDimitry Andric   /// languages that can't represent and encode C/C++ integer types.
22206c3fb27SDimitry Andric   bool NormalizeIntegers = false;
22306c3fb27SDimitry Andric 
2240b57cec5SDimitry Andric   bool NullOut = false;
2250b57cec5SDimitry Andric   /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
2260b57cec5SDimitry Andric   /// This mode is used when mangler creates another mangler recursively to
2270b57cec5SDimitry Andric   /// calculate ABI tags for the function return value or the variable type.
2280b57cec5SDimitry Andric   /// Also it is required to avoid infinite recursion in some cases.
2290b57cec5SDimitry Andric   bool DisableDerivedAbiTags = false;
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric   /// The "structor" is the top-level declaration being mangled, if
2320b57cec5SDimitry Andric   /// that's not a template specialization; otherwise it's the pattern
2330b57cec5SDimitry Andric   /// for that specialization.
2340b57cec5SDimitry Andric   const NamedDecl *Structor;
23581ad6265SDimitry Andric   unsigned StructorType = 0;
2360b57cec5SDimitry Andric 
2375f757f3fSDimitry Andric   // An offset to add to all template parameter depths while mangling. Used
2385f757f3fSDimitry Andric   // when mangling a template parameter list to see if it matches a template
2395f757f3fSDimitry Andric   // template parameter exactly.
2405f757f3fSDimitry Andric   unsigned TemplateDepthOffset = 0;
2415f757f3fSDimitry Andric 
2420b57cec5SDimitry Andric   /// The next substitution sequence number.
24381ad6265SDimitry Andric   unsigned SeqID = 0;
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   class FunctionTypeDepthState {
2465f757f3fSDimitry Andric     unsigned Bits = 0;
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric     enum { InResultTypeMask = 1 };
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric   public:
2515f757f3fSDimitry Andric     FunctionTypeDepthState() = default;
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric     /// The number of function types we're inside.
getDepth() const2540b57cec5SDimitry Andric     unsigned getDepth() const {
2550b57cec5SDimitry Andric       return Bits >> 1;
2560b57cec5SDimitry Andric     }
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric     /// True if we're in the return type of the innermost function type.
isInResultType() const2590b57cec5SDimitry Andric     bool isInResultType() const {
2600b57cec5SDimitry Andric       return Bits & InResultTypeMask;
2610b57cec5SDimitry Andric     }
2620b57cec5SDimitry Andric 
push()2630b57cec5SDimitry Andric     FunctionTypeDepthState push() {
2640b57cec5SDimitry Andric       FunctionTypeDepthState tmp = *this;
2650b57cec5SDimitry Andric       Bits = (Bits & ~InResultTypeMask) + 2;
2660b57cec5SDimitry Andric       return tmp;
2670b57cec5SDimitry Andric     }
2680b57cec5SDimitry Andric 
enterResultType()2690b57cec5SDimitry Andric     void enterResultType() {
2700b57cec5SDimitry Andric       Bits |= InResultTypeMask;
2710b57cec5SDimitry Andric     }
2720b57cec5SDimitry Andric 
leaveResultType()2730b57cec5SDimitry Andric     void leaveResultType() {
2740b57cec5SDimitry Andric       Bits &= ~InResultTypeMask;
2750b57cec5SDimitry Andric     }
2760b57cec5SDimitry Andric 
pop(FunctionTypeDepthState saved)2770b57cec5SDimitry Andric     void pop(FunctionTypeDepthState saved) {
2780b57cec5SDimitry Andric       assert(getDepth() == saved.getDepth() + 1);
2790b57cec5SDimitry Andric       Bits = saved.Bits;
2800b57cec5SDimitry Andric     }
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   } FunctionTypeDepth;
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric   // abi_tag is a gcc attribute, taking one or more strings called "tags".
2850b57cec5SDimitry Andric   // The goal is to annotate against which version of a library an object was
2860b57cec5SDimitry Andric   // built and to be able to provide backwards compatibility ("dual abi").
2870b57cec5SDimitry Andric   // For more information see docs/ItaniumMangleAbiTags.rst.
2880b57cec5SDimitry Andric   typedef SmallVector<StringRef, 4> AbiTagList;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   // State to gather all implicit and explicit tags used in a mangled name.
2910b57cec5SDimitry Andric   // Must always have an instance of this while emitting any name to keep
2920b57cec5SDimitry Andric   // track.
2930b57cec5SDimitry Andric   class AbiTagState final {
2940b57cec5SDimitry Andric   public:
AbiTagState(AbiTagState * & Head)2950b57cec5SDimitry Andric     explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
2960b57cec5SDimitry Andric       Parent = LinkHead;
2970b57cec5SDimitry Andric       LinkHead = this;
2980b57cec5SDimitry Andric     }
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric     // No copy, no move.
3010b57cec5SDimitry Andric     AbiTagState(const AbiTagState &) = delete;
3020b57cec5SDimitry Andric     AbiTagState &operator=(const AbiTagState &) = delete;
3030b57cec5SDimitry Andric 
~AbiTagState()3040b57cec5SDimitry Andric     ~AbiTagState() { pop(); }
3050b57cec5SDimitry Andric 
write(raw_ostream & Out,const NamedDecl * ND,const AbiTagList * AdditionalAbiTags)3060b57cec5SDimitry Andric     void write(raw_ostream &Out, const NamedDecl *ND,
3070b57cec5SDimitry Andric                const AbiTagList *AdditionalAbiTags) {
3080b57cec5SDimitry Andric       ND = cast<NamedDecl>(ND->getCanonicalDecl());
3090b57cec5SDimitry Andric       if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
3100b57cec5SDimitry Andric         assert(
3110b57cec5SDimitry Andric             !AdditionalAbiTags &&
3120b57cec5SDimitry Andric             "only function and variables need a list of additional abi tags");
3130b57cec5SDimitry Andric         if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
3140b57cec5SDimitry Andric           if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
3150b57cec5SDimitry Andric             UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
3160b57cec5SDimitry Andric                                AbiTag->tags().end());
3170b57cec5SDimitry Andric           }
3180b57cec5SDimitry Andric           // Don't emit abi tags for namespaces.
3190b57cec5SDimitry Andric           return;
3200b57cec5SDimitry Andric         }
3210b57cec5SDimitry Andric       }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric       AbiTagList TagList;
3240b57cec5SDimitry Andric       if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
3250b57cec5SDimitry Andric         UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
3260b57cec5SDimitry Andric                            AbiTag->tags().end());
3270b57cec5SDimitry Andric         TagList.insert(TagList.end(), AbiTag->tags().begin(),
3280b57cec5SDimitry Andric                        AbiTag->tags().end());
3290b57cec5SDimitry Andric       }
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric       if (AdditionalAbiTags) {
3320b57cec5SDimitry Andric         UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
3330b57cec5SDimitry Andric                            AdditionalAbiTags->end());
3340b57cec5SDimitry Andric         TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
3350b57cec5SDimitry Andric                        AdditionalAbiTags->end());
3360b57cec5SDimitry Andric       }
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric       llvm::sort(TagList);
3390b57cec5SDimitry Andric       TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric       writeSortedUniqueAbiTags(Out, TagList);
3420b57cec5SDimitry Andric     }
3430b57cec5SDimitry Andric 
getUsedAbiTags() const3440b57cec5SDimitry Andric     const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
setUsedAbiTags(const AbiTagList & AbiTags)3450b57cec5SDimitry Andric     void setUsedAbiTags(const AbiTagList &AbiTags) {
3460b57cec5SDimitry Andric       UsedAbiTags = AbiTags;
3470b57cec5SDimitry Andric     }
3480b57cec5SDimitry Andric 
getEmittedAbiTags() const3490b57cec5SDimitry Andric     const AbiTagList &getEmittedAbiTags() const {
3500b57cec5SDimitry Andric       return EmittedAbiTags;
3510b57cec5SDimitry Andric     }
3520b57cec5SDimitry Andric 
getSortedUniqueUsedAbiTags()3530b57cec5SDimitry Andric     const AbiTagList &getSortedUniqueUsedAbiTags() {
3540b57cec5SDimitry Andric       llvm::sort(UsedAbiTags);
3550b57cec5SDimitry Andric       UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
3560b57cec5SDimitry Andric                         UsedAbiTags.end());
3570b57cec5SDimitry Andric       return UsedAbiTags;
3580b57cec5SDimitry Andric     }
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   private:
3610b57cec5SDimitry Andric     //! All abi tags used implicitly or explicitly.
3620b57cec5SDimitry Andric     AbiTagList UsedAbiTags;
3630b57cec5SDimitry Andric     //! All explicit abi tags (i.e. not from namespace).
3640b57cec5SDimitry Andric     AbiTagList EmittedAbiTags;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric     AbiTagState *&LinkHead;
3670b57cec5SDimitry Andric     AbiTagState *Parent = nullptr;
3680b57cec5SDimitry Andric 
pop()3690b57cec5SDimitry Andric     void pop() {
3700b57cec5SDimitry Andric       assert(LinkHead == this &&
3710b57cec5SDimitry Andric              "abi tag link head must point to us on destruction");
3720b57cec5SDimitry Andric       if (Parent) {
3730b57cec5SDimitry Andric         Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
3740b57cec5SDimitry Andric                                    UsedAbiTags.begin(), UsedAbiTags.end());
3750b57cec5SDimitry Andric         Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
3760b57cec5SDimitry Andric                                       EmittedAbiTags.begin(),
3770b57cec5SDimitry Andric                                       EmittedAbiTags.end());
3780b57cec5SDimitry Andric       }
3790b57cec5SDimitry Andric       LinkHead = Parent;
3800b57cec5SDimitry Andric     }
3810b57cec5SDimitry Andric 
writeSortedUniqueAbiTags(raw_ostream & Out,const AbiTagList & AbiTags)3820b57cec5SDimitry Andric     void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
3830b57cec5SDimitry Andric       for (const auto &Tag : AbiTags) {
3840b57cec5SDimitry Andric         EmittedAbiTags.push_back(Tag);
3850b57cec5SDimitry Andric         Out << "B";
3860b57cec5SDimitry Andric         Out << Tag.size();
3870b57cec5SDimitry Andric         Out << Tag;
3880b57cec5SDimitry Andric       }
3890b57cec5SDimitry Andric     }
3900b57cec5SDimitry Andric   };
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   AbiTagState *AbiTags = nullptr;
3930b57cec5SDimitry Andric   AbiTagState AbiTagsRoot;
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   llvm::DenseMap<uintptr_t, unsigned> Substitutions;
3960b57cec5SDimitry Andric   llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
3970b57cec5SDimitry Andric 
getASTContext() const3980b57cec5SDimitry Andric   ASTContext &getASTContext() const { return Context.getASTContext(); }
3990b57cec5SDimitry Andric 
isCompatibleWith(LangOptions::ClangABI Ver)4005f757f3fSDimitry Andric   bool isCompatibleWith(LangOptions::ClangABI Ver) {
4015f757f3fSDimitry Andric     return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver;
4025f757f3fSDimitry Andric   }
4035f757f3fSDimitry Andric 
4042a66634dSDimitry Andric   bool isStd(const NamespaceDecl *NS);
4052a66634dSDimitry Andric   bool isStdNamespace(const DeclContext *DC);
4062a66634dSDimitry Andric 
4072a66634dSDimitry Andric   const RecordDecl *GetLocalClassDecl(const Decl *D);
4082a66634dSDimitry Andric   bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
4092a66634dSDimitry Andric   bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
4102a66634dSDimitry Andric                                llvm::StringRef Name, bool HasAllocator);
4112a66634dSDimitry Andric 
4120b57cec5SDimitry Andric public:
CXXNameMangler(ItaniumMangleContextImpl & C,raw_ostream & Out_,const NamedDecl * D=nullptr,bool NullOut_=false)4130b57cec5SDimitry Andric   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
4140b57cec5SDimitry Andric                  const NamedDecl *D = nullptr, bool NullOut_ = false)
4150b57cec5SDimitry Andric       : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
41681ad6265SDimitry Andric         AbiTagsRoot(AbiTags) {
4170b57cec5SDimitry Andric     // These can't be mangled without a ctor type or dtor type.
4180b57cec5SDimitry Andric     assert(!D || (!isa<CXXDestructorDecl>(D) &&
4190b57cec5SDimitry Andric                   !isa<CXXConstructorDecl>(D)));
4200b57cec5SDimitry Andric   }
CXXNameMangler(ItaniumMangleContextImpl & C,raw_ostream & Out_,const CXXConstructorDecl * D,CXXCtorType Type)4210b57cec5SDimitry Andric   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
4220b57cec5SDimitry Andric                  const CXXConstructorDecl *D, CXXCtorType Type)
4230b57cec5SDimitry Andric       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
42481ad6265SDimitry Andric         AbiTagsRoot(AbiTags) {}
CXXNameMangler(ItaniumMangleContextImpl & C,raw_ostream & Out_,const CXXDestructorDecl * D,CXXDtorType Type)4250b57cec5SDimitry Andric   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
4260b57cec5SDimitry Andric                  const CXXDestructorDecl *D, CXXDtorType Type)
4270b57cec5SDimitry Andric       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
42881ad6265SDimitry Andric         AbiTagsRoot(AbiTags) {}
4290b57cec5SDimitry Andric 
CXXNameMangler(ItaniumMangleContextImpl & C,raw_ostream & Out_,bool NormalizeIntegers_)43006c3fb27SDimitry Andric   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
43106c3fb27SDimitry Andric                  bool NormalizeIntegers_)
43206c3fb27SDimitry Andric       : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),
43306c3fb27SDimitry Andric         NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}
CXXNameMangler(CXXNameMangler & Outer,raw_ostream & Out_)4340b57cec5SDimitry Andric   CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
43581ad6265SDimitry Andric       : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
43681ad6265SDimitry Andric         StructorType(Outer.StructorType), SeqID(Outer.SeqID),
43781ad6265SDimitry Andric         FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
43881ad6265SDimitry Andric         Substitutions(Outer.Substitutions),
43981ad6265SDimitry Andric         ModuleSubstitutions(Outer.ModuleSubstitutions) {}
4400b57cec5SDimitry Andric 
CXXNameMangler(CXXNameMangler & Outer,llvm::raw_null_ostream & Out_)4410b57cec5SDimitry Andric   CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
44281ad6265SDimitry Andric       : CXXNameMangler(Outer, (raw_ostream &)Out_) {
44381ad6265SDimitry Andric     NullOut = true;
44481ad6265SDimitry Andric   }
4450b57cec5SDimitry Andric 
4465f757f3fSDimitry Andric   struct WithTemplateDepthOffset { unsigned Offset; };
CXXNameMangler(ItaniumMangleContextImpl & C,raw_ostream & Out,WithTemplateDepthOffset Offset)4475f757f3fSDimitry Andric   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out,
4485f757f3fSDimitry Andric                  WithTemplateDepthOffset Offset)
4495f757f3fSDimitry Andric       : CXXNameMangler(C, Out) {
4505f757f3fSDimitry Andric     TemplateDepthOffset = Offset.Offset;
4515f757f3fSDimitry Andric   }
4525f757f3fSDimitry Andric 
getStream()4530b57cec5SDimitry Andric   raw_ostream &getStream() { return Out; }
4540b57cec5SDimitry Andric 
disableDerivedAbiTags()4550b57cec5SDimitry Andric   void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
4560b57cec5SDimitry Andric   static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
4570b57cec5SDimitry Andric 
4585ffd83dbSDimitry Andric   void mangle(GlobalDecl GD);
4590b57cec5SDimitry Andric   void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
4600b57cec5SDimitry Andric   void mangleNumber(const llvm::APSInt &I);
4610b57cec5SDimitry Andric   void mangleNumber(int64_t Number);
4620b57cec5SDimitry Andric   void mangleFloat(const llvm::APFloat &F);
4635ffd83dbSDimitry Andric   void mangleFunctionEncoding(GlobalDecl GD);
4640b57cec5SDimitry Andric   void mangleSeqID(unsigned SeqID);
4655ffd83dbSDimitry Andric   void mangleName(GlobalDecl GD);
4660b57cec5SDimitry Andric   void mangleType(QualType T);
4670b57cec5SDimitry Andric   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
468a7dea167SDimitry Andric   void mangleLambdaSig(const CXXRecordDecl *Lambda);
46981ad6265SDimitry Andric   void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
4700fca6ea1SDimitry Andric   void mangleVendorQualifier(StringRef Name);
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric private:
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   bool mangleSubstitution(const NamedDecl *ND);
47581ad6265SDimitry Andric   bool mangleSubstitution(NestedNameSpecifier *NNS);
4760b57cec5SDimitry Andric   bool mangleSubstitution(QualType T);
4770b57cec5SDimitry Andric   bool mangleSubstitution(TemplateName Template);
4780b57cec5SDimitry Andric   bool mangleSubstitution(uintptr_t Ptr);
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   void mangleExistingSubstitution(TemplateName name);
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   bool mangleStandardSubstitution(const NamedDecl *ND);
4830b57cec5SDimitry Andric 
addSubstitution(const NamedDecl * ND)4840b57cec5SDimitry Andric   void addSubstitution(const NamedDecl *ND) {
4850b57cec5SDimitry Andric     ND = cast<NamedDecl>(ND->getCanonicalDecl());
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric     addSubstitution(reinterpret_cast<uintptr_t>(ND));
4880b57cec5SDimitry Andric   }
addSubstitution(NestedNameSpecifier * NNS)48981ad6265SDimitry Andric   void addSubstitution(NestedNameSpecifier *NNS) {
49081ad6265SDimitry Andric     NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
49181ad6265SDimitry Andric 
49281ad6265SDimitry Andric     addSubstitution(reinterpret_cast<uintptr_t>(NNS));
49381ad6265SDimitry Andric   }
4940b57cec5SDimitry Andric   void addSubstitution(QualType T);
4950b57cec5SDimitry Andric   void addSubstitution(TemplateName Template);
4960b57cec5SDimitry Andric   void addSubstitution(uintptr_t Ptr);
4970b57cec5SDimitry Andric   // Destructive copy substitutions from other mangler.
4980b57cec5SDimitry Andric   void extendSubstitutions(CXXNameMangler* Other);
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
5010b57cec5SDimitry Andric                               bool recursive = false);
5020b57cec5SDimitry Andric   void mangleUnresolvedName(NestedNameSpecifier *qualifier,
5030b57cec5SDimitry Andric                             DeclarationName name,
5040b57cec5SDimitry Andric                             const TemplateArgumentLoc *TemplateArgs,
5050b57cec5SDimitry Andric                             unsigned NumTemplateArgs,
5060b57cec5SDimitry Andric                             unsigned KnownArity = UnknownArity);
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   void mangleFunctionEncodingBareType(const FunctionDecl *FD);
5090b57cec5SDimitry Andric 
5105ffd83dbSDimitry Andric   void mangleNameWithAbiTags(GlobalDecl GD,
5110b57cec5SDimitry Andric                              const AbiTagList *AdditionalAbiTags);
51281ad6265SDimitry Andric   void mangleModuleName(const NamedDecl *ND);
5130b57cec5SDimitry Andric   void mangleTemplateName(const TemplateDecl *TD,
514bdd1243dSDimitry Andric                           ArrayRef<TemplateArgument> Args);
mangleUnqualifiedName(GlobalDecl GD,const DeclContext * DC,const AbiTagList * AdditionalAbiTags)51581ad6265SDimitry Andric   void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
5160b57cec5SDimitry Andric                              const AbiTagList *AdditionalAbiTags) {
51781ad6265SDimitry Andric     mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
51881ad6265SDimitry Andric                           UnknownArity, AdditionalAbiTags);
5190b57cec5SDimitry Andric   }
5205ffd83dbSDimitry Andric   void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
52181ad6265SDimitry Andric                              const DeclContext *DC, unsigned KnownArity,
5220b57cec5SDimitry Andric                              const AbiTagList *AdditionalAbiTags);
52381ad6265SDimitry Andric   void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
5240b57cec5SDimitry Andric                           const AbiTagList *AdditionalAbiTags);
52581ad6265SDimitry Andric   void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
5260b57cec5SDimitry Andric                                   const AbiTagList *AdditionalAbiTags);
5270b57cec5SDimitry Andric   void mangleSourceName(const IdentifierInfo *II);
5280b57cec5SDimitry Andric   void mangleRegCallName(const IdentifierInfo *II);
5295ffd83dbSDimitry Andric   void mangleDeviceStubName(const IdentifierInfo *II);
5300b57cec5SDimitry Andric   void mangleSourceNameWithAbiTags(
5310b57cec5SDimitry Andric       const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
5325ffd83dbSDimitry Andric   void mangleLocalName(GlobalDecl GD,
5330b57cec5SDimitry Andric                        const AbiTagList *AdditionalAbiTags);
5340b57cec5SDimitry Andric   void mangleBlockForPrefix(const BlockDecl *Block);
5350b57cec5SDimitry Andric   void mangleUnqualifiedBlock(const BlockDecl *Block);
5360b57cec5SDimitry Andric   void mangleTemplateParamDecl(const NamedDecl *Decl);
5375f757f3fSDimitry Andric   void mangleTemplateParameterList(const TemplateParameterList *Params);
5385f757f3fSDimitry Andric   void mangleTypeConstraint(const ConceptDecl *Concept,
5395f757f3fSDimitry Andric                             ArrayRef<TemplateArgument> Arguments);
5405f757f3fSDimitry Andric   void mangleTypeConstraint(const TypeConstraint *Constraint);
5415f757f3fSDimitry Andric   void mangleRequiresClause(const Expr *RequiresClause);
5420b57cec5SDimitry Andric   void mangleLambda(const CXXRecordDecl *Lambda);
5435ffd83dbSDimitry Andric   void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
5440b57cec5SDimitry Andric                         const AbiTagList *AdditionalAbiTags,
5450b57cec5SDimitry Andric                         bool NoFunction=false);
5460b57cec5SDimitry Andric   void mangleNestedName(const TemplateDecl *TD,
547bdd1243dSDimitry Andric                         ArrayRef<TemplateArgument> Args);
548fe6060f1SDimitry Andric   void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
549fe6060f1SDimitry Andric                                          const NamedDecl *PrefixND,
550fe6060f1SDimitry Andric                                          const AbiTagList *AdditionalAbiTags);
5510b57cec5SDimitry Andric   void manglePrefix(NestedNameSpecifier *qualifier);
5520b57cec5SDimitry Andric   void manglePrefix(const DeclContext *DC, bool NoFunction=false);
5530b57cec5SDimitry Andric   void manglePrefix(QualType type);
5545ffd83dbSDimitry Andric   void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
5550b57cec5SDimitry Andric   void mangleTemplatePrefix(TemplateName Template);
556fe6060f1SDimitry Andric   const NamedDecl *getClosurePrefix(const Decl *ND);
557fe6060f1SDimitry Andric   void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
5580b57cec5SDimitry Andric   bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
5590b57cec5SDimitry Andric                                       StringRef Prefix = "");
5600b57cec5SDimitry Andric   void mangleOperatorName(DeclarationName Name, unsigned Arity);
5610b57cec5SDimitry Andric   void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
5620b57cec5SDimitry Andric   void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
5630b57cec5SDimitry Andric   void mangleRefQualifier(RefQualifierKind RefQualifier);
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   void mangleObjCMethodName(const ObjCMethodDecl *MD);
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric   // Declare manglers for every type class.
5680b57cec5SDimitry Andric #define ABSTRACT_TYPE(CLASS, PARENT)
5690b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(CLASS, PARENT)
5700b57cec5SDimitry Andric #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
571a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   void mangleType(const TagType*);
5740b57cec5SDimitry Andric   void mangleType(TemplateName);
5750b57cec5SDimitry Andric   static StringRef getCallingConvQualifierName(CallingConv CC);
5760b57cec5SDimitry Andric   void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
5770b57cec5SDimitry Andric   void mangleExtFunctionInfo(const FunctionType *T);
5780b57cec5SDimitry Andric   void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
5790b57cec5SDimitry Andric                               const FunctionDecl *FD = nullptr);
5800b57cec5SDimitry Andric   void mangleNeonVectorType(const VectorType *T);
5810b57cec5SDimitry Andric   void mangleNeonVectorType(const DependentVectorType *T);
5820b57cec5SDimitry Andric   void mangleAArch64NeonVectorType(const VectorType *T);
5830b57cec5SDimitry Andric   void mangleAArch64NeonVectorType(const DependentVectorType *T);
584e8d8bef9SDimitry Andric   void mangleAArch64FixedSveVectorType(const VectorType *T);
585e8d8bef9SDimitry Andric   void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
58606c3fb27SDimitry Andric   void mangleRISCVFixedRVVVectorType(const VectorType *T);
58706c3fb27SDimitry Andric   void mangleRISCVFixedRVVVectorType(const DependentVectorType *T);
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
590e8d8bef9SDimitry Andric   void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
591e8d8bef9SDimitry Andric   void mangleFixedPointLiteral();
592e8d8bef9SDimitry Andric   void mangleNullPointer(QualType T);
593e8d8bef9SDimitry Andric 
5940b57cec5SDimitry Andric   void mangleMemberExprBase(const Expr *base, bool isArrow);
5950b57cec5SDimitry Andric   void mangleMemberExpr(const Expr *base, bool isArrow,
5960b57cec5SDimitry Andric                         NestedNameSpecifier *qualifier,
5970b57cec5SDimitry Andric                         NamedDecl *firstQualifierLookup,
5980b57cec5SDimitry Andric                         DeclarationName name,
5990b57cec5SDimitry Andric                         const TemplateArgumentLoc *TemplateArgs,
6000b57cec5SDimitry Andric                         unsigned NumTemplateArgs,
6010b57cec5SDimitry Andric                         unsigned knownArity);
6020b57cec5SDimitry Andric   void mangleCastExpression(const Expr *E, StringRef CastEncoding);
6030b57cec5SDimitry Andric   void mangleInitListElements(const InitListExpr *InitList);
6045f757f3fSDimitry Andric   void mangleRequirement(SourceLocation RequiresExprLoc,
6055f757f3fSDimitry Andric                          const concepts::Requirement *Req);
606d409305fSDimitry Andric   void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
607d409305fSDimitry Andric                         bool AsTemplateArg = false);
6080b57cec5SDimitry Andric   void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
6090b57cec5SDimitry Andric   void mangleCXXDtorType(CXXDtorType T);
6100b57cec5SDimitry Andric 
6115f757f3fSDimitry Andric   struct TemplateArgManglingInfo;
612e8d8bef9SDimitry Andric   void mangleTemplateArgs(TemplateName TN,
613e8d8bef9SDimitry Andric                           const TemplateArgumentLoc *TemplateArgs,
6140b57cec5SDimitry Andric                           unsigned NumTemplateArgs);
615bdd1243dSDimitry Andric   void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);
616e8d8bef9SDimitry Andric   void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
6175f757f3fSDimitry Andric   void mangleTemplateArg(TemplateArgManglingInfo &Info, unsigned Index,
6185f757f3fSDimitry Andric                          TemplateArgument A);
619e8d8bef9SDimitry Andric   void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
620d409305fSDimitry Andric   void mangleTemplateArgExpr(const Expr *E);
621e8d8bef9SDimitry Andric   void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
622e8d8bef9SDimitry Andric                                 bool NeedExactType = false);
6230b57cec5SDimitry Andric 
624a7dea167SDimitry Andric   void mangleTemplateParameter(unsigned Depth, unsigned Index);
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   void mangleFunctionParam(const ParmVarDecl *parm);
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   void writeAbiTags(const NamedDecl *ND,
6290b57cec5SDimitry Andric                     const AbiTagList *AdditionalAbiTags);
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric   // Returns sorted unique list of ABI tags.
6320b57cec5SDimitry Andric   AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
6330b57cec5SDimitry Andric   // Returns sorted unique list of ABI tags.
6340b57cec5SDimitry Andric   AbiTagList makeVariableTypeTags(const VarDecl *VD);
6350b57cec5SDimitry Andric };
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric }
6380b57cec5SDimitry Andric 
getStdNamespace()6392a66634dSDimitry Andric NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
6402a66634dSDimitry Andric   if (!StdNamespace) {
6412a66634dSDimitry Andric     StdNamespace = NamespaceDecl::Create(
6422a66634dSDimitry Andric         getASTContext(), getASTContext().getTranslationUnitDecl(),
643bdd1243dSDimitry Andric         /*Inline=*/false, SourceLocation(), SourceLocation(),
6442a66634dSDimitry Andric         &getASTContext().Idents.get("std"),
645bdd1243dSDimitry Andric         /*PrevDecl=*/nullptr, /*Nested=*/false);
6462a66634dSDimitry Andric     StdNamespace->setImplicit();
6472a66634dSDimitry Andric   }
6482a66634dSDimitry Andric   return StdNamespace;
6492a66634dSDimitry Andric }
6502a66634dSDimitry Andric 
6512a66634dSDimitry Andric /// Retrieve the declaration context that should be used when mangling the given
6522a66634dSDimitry Andric /// declaration.
6532a66634dSDimitry Andric const DeclContext *
getEffectiveDeclContext(const Decl * D)6542a66634dSDimitry Andric ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
6552a66634dSDimitry Andric   // The ABI assumes that lambda closure types that occur within
6562a66634dSDimitry Andric   // default arguments live in the context of the function. However, due to
6572a66634dSDimitry Andric   // the way in which Clang parses and creates function declarations, this is
6582a66634dSDimitry Andric   // not the case: the lambda closure type ends up living in the context
6592a66634dSDimitry Andric   // where the function itself resides, because the function declaration itself
6602a66634dSDimitry Andric   // had not yet been created. Fix the context here.
6612a66634dSDimitry Andric   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
6622a66634dSDimitry Andric     if (RD->isLambda())
6632a66634dSDimitry Andric       if (ParmVarDecl *ContextParam =
6642a66634dSDimitry Andric               dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
6652a66634dSDimitry Andric         return ContextParam->getDeclContext();
6662a66634dSDimitry Andric   }
6672a66634dSDimitry Andric 
6682a66634dSDimitry Andric   // Perform the same check for block literals.
6692a66634dSDimitry Andric   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
6702a66634dSDimitry Andric     if (ParmVarDecl *ContextParam =
6712a66634dSDimitry Andric             dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
6722a66634dSDimitry Andric       return ContextParam->getDeclContext();
6732a66634dSDimitry Andric   }
6742a66634dSDimitry Andric 
6752a66634dSDimitry Andric   // On ARM and AArch64, the va_list tag is always mangled as if in the std
6762a66634dSDimitry Andric   // namespace. We do not represent va_list as actually being in the std
6772a66634dSDimitry Andric   // namespace in C because this would result in incorrect debug info in C,
6782a66634dSDimitry Andric   // among other things. It is important for both languages to have the same
6792a66634dSDimitry Andric   // mangling in order for -fsanitize=cfi-icall to work.
6802a66634dSDimitry Andric   if (D == getASTContext().getVaListTagDecl()) {
6812a66634dSDimitry Andric     const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
6822a66634dSDimitry Andric     if (T.isARM() || T.isThumb() || T.isAArch64())
6832a66634dSDimitry Andric       return getStdNamespace();
6842a66634dSDimitry Andric   }
6852a66634dSDimitry Andric 
6862a66634dSDimitry Andric   const DeclContext *DC = D->getDeclContext();
6872a66634dSDimitry Andric   if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
6882a66634dSDimitry Andric       isa<OMPDeclareMapperDecl>(DC)) {
6892a66634dSDimitry Andric     return getEffectiveDeclContext(cast<Decl>(DC));
6902a66634dSDimitry Andric   }
6912a66634dSDimitry Andric 
6922a66634dSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
6932a66634dSDimitry Andric     if (VD->isExternC())
6942a66634dSDimitry Andric       return getASTContext().getTranslationUnitDecl();
6952a66634dSDimitry Andric 
6965f757f3fSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
6972a66634dSDimitry Andric     if (FD->isExternC())
6982a66634dSDimitry Andric       return getASTContext().getTranslationUnitDecl();
6995f757f3fSDimitry Andric     // Member-like constrained friends are mangled as if they were members of
7005f757f3fSDimitry Andric     // the enclosing class.
7015f757f3fSDimitry Andric     if (FD->isMemberLikeConstrainedFriend() &&
7025f757f3fSDimitry Andric         getASTContext().getLangOpts().getClangABICompat() >
7035f757f3fSDimitry Andric             LangOptions::ClangABI::Ver17)
7045f757f3fSDimitry Andric       return D->getLexicalDeclContext()->getRedeclContext();
7055f757f3fSDimitry Andric   }
7062a66634dSDimitry Andric 
7072a66634dSDimitry Andric   return DC->getRedeclContext();
7082a66634dSDimitry Andric }
7092a66634dSDimitry Andric 
isInternalLinkageDecl(const NamedDecl * ND)7102a66634dSDimitry Andric bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
7115f757f3fSDimitry Andric   if (ND && ND->getFormalLinkage() == Linkage::Internal &&
712fe6060f1SDimitry Andric       !ND->isExternallyVisible() &&
713fe6060f1SDimitry Andric       getEffectiveDeclContext(ND)->isFileContext() &&
714fe6060f1SDimitry Andric       !ND->isInAnonymousNamespace())
715fe6060f1SDimitry Andric     return true;
716fe6060f1SDimitry Andric   return false;
717fe6060f1SDimitry Andric }
718fe6060f1SDimitry Andric 
719fe6060f1SDimitry Andric // Check if this Function Decl needs a unique internal linkage name.
isUniqueInternalLinkageDecl(const NamedDecl * ND)720fe6060f1SDimitry Andric bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
721fe6060f1SDimitry Andric     const NamedDecl *ND) {
722fe6060f1SDimitry Andric   if (!NeedsUniqueInternalLinkageNames || !ND)
723fe6060f1SDimitry Andric     return false;
724fe6060f1SDimitry Andric 
725fe6060f1SDimitry Andric   const auto *FD = dyn_cast<FunctionDecl>(ND);
726fe6060f1SDimitry Andric   if (!FD)
727fe6060f1SDimitry Andric     return false;
728fe6060f1SDimitry Andric 
729fe6060f1SDimitry Andric   // For C functions without prototypes, return false as their
730fe6060f1SDimitry Andric   // names should not be mangled.
731fe6060f1SDimitry Andric   if (!FD->getType()->getAs<FunctionProtoType>())
732fe6060f1SDimitry Andric     return false;
733fe6060f1SDimitry Andric 
734fe6060f1SDimitry Andric   if (isInternalLinkageDecl(ND))
735fe6060f1SDimitry Andric     return true;
736fe6060f1SDimitry Andric 
737fe6060f1SDimitry Andric   return false;
738fe6060f1SDimitry Andric }
739fe6060f1SDimitry Andric 
shouldMangleCXXName(const NamedDecl * D)7400b57cec5SDimitry Andric bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
74104eeddc0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7420b57cec5SDimitry Andric     LanguageLinkage L = FD->getLanguageLinkage();
7430b57cec5SDimitry Andric     // Overloadable functions need mangling.
7440b57cec5SDimitry Andric     if (FD->hasAttr<OverloadableAttr>())
7450b57cec5SDimitry Andric       return true;
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric     // "main" is not mangled.
7480b57cec5SDimitry Andric     if (FD->isMain())
7490b57cec5SDimitry Andric       return false;
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric     // The Windows ABI expects that we would never mangle "typical"
7520b57cec5SDimitry Andric     // user-defined entry points regardless of visibility or freestanding-ness.
7530b57cec5SDimitry Andric     //
7540b57cec5SDimitry Andric     // N.B. This is distinct from asking about "main".  "main" has a lot of
7550b57cec5SDimitry Andric     // special rules associated with it in the standard while these
7560b57cec5SDimitry Andric     // user-defined entry points are outside of the purview of the standard.
7570b57cec5SDimitry Andric     // For example, there can be only one definition for "main" in a standards
7580b57cec5SDimitry Andric     // compliant program; however nothing forbids the existence of wmain and
7590b57cec5SDimitry Andric     // WinMain in the same translation unit.
7600b57cec5SDimitry Andric     if (FD->isMSVCRTEntryPoint())
7610b57cec5SDimitry Andric       return false;
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric     // C++ functions and those whose names are not a simple identifier need
7640b57cec5SDimitry Andric     // mangling.
7650b57cec5SDimitry Andric     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
7660b57cec5SDimitry Andric       return true;
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric     // C functions are not mangled.
7690b57cec5SDimitry Andric     if (L == CLanguageLinkage)
7700b57cec5SDimitry Andric       return false;
7710b57cec5SDimitry Andric   }
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric   // Otherwise, no mangling is done outside C++ mode.
7740b57cec5SDimitry Andric   if (!getASTContext().getLangOpts().CPlusPlus)
7750b57cec5SDimitry Andric     return false;
7760b57cec5SDimitry Andric 
77704eeddc0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D)) {
77804eeddc0SDimitry Andric     // Decompositions are mangled.
77904eeddc0SDimitry Andric     if (isa<DecompositionDecl>(VD))
78004eeddc0SDimitry Andric       return true;
78104eeddc0SDimitry Andric 
7820b57cec5SDimitry Andric     // C variables are not mangled.
7830b57cec5SDimitry Andric     if (VD->isExternC())
7840b57cec5SDimitry Andric       return false;
7850b57cec5SDimitry Andric 
78681ad6265SDimitry Andric     // Variables at global scope are not mangled unless they have internal
78781ad6265SDimitry Andric     // linkage or are specializations or are attached to a named module.
7880b57cec5SDimitry Andric     const DeclContext *DC = getEffectiveDeclContext(D);
7890b57cec5SDimitry Andric     // Check for extern variable declared locally.
7900b57cec5SDimitry Andric     if (DC->isFunctionOrMethod() && D->hasLinkage())
79104eeddc0SDimitry Andric       while (!DC->isFileContext())
7920b57cec5SDimitry Andric         DC = getEffectiveParentContext(DC);
7935f757f3fSDimitry Andric     if (DC->isTranslationUnit() && D->getFormalLinkage() != Linkage::Internal &&
7940b57cec5SDimitry Andric         !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
79581ad6265SDimitry Andric         !isa<VarTemplateSpecializationDecl>(VD) &&
79681ad6265SDimitry Andric         !VD->getOwningModuleForLinkage())
7970b57cec5SDimitry Andric       return false;
7980b57cec5SDimitry Andric   }
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   return true;
8010b57cec5SDimitry Andric }
8020b57cec5SDimitry Andric 
writeAbiTags(const NamedDecl * ND,const AbiTagList * AdditionalAbiTags)8030b57cec5SDimitry Andric void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
8040b57cec5SDimitry Andric                                   const AbiTagList *AdditionalAbiTags) {
8050b57cec5SDimitry Andric   assert(AbiTags && "require AbiTagState");
8060b57cec5SDimitry Andric   AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
8070b57cec5SDimitry Andric }
8080b57cec5SDimitry Andric 
mangleSourceNameWithAbiTags(const NamedDecl * ND,const AbiTagList * AdditionalAbiTags)8090b57cec5SDimitry Andric void CXXNameMangler::mangleSourceNameWithAbiTags(
8100b57cec5SDimitry Andric     const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
8110b57cec5SDimitry Andric   mangleSourceName(ND->getIdentifier());
8120b57cec5SDimitry Andric   writeAbiTags(ND, AdditionalAbiTags);
8130b57cec5SDimitry Andric }
8140b57cec5SDimitry Andric 
mangle(GlobalDecl GD)8155ffd83dbSDimitry Andric void CXXNameMangler::mangle(GlobalDecl GD) {
8160b57cec5SDimitry Andric   // <mangled-name> ::= _Z <encoding>
8170b57cec5SDimitry Andric   //            ::= <data name>
8180b57cec5SDimitry Andric   //            ::= <special-name>
8190b57cec5SDimitry Andric   Out << "_Z";
8205ffd83dbSDimitry Andric   if (isa<FunctionDecl>(GD.getDecl()))
8215ffd83dbSDimitry Andric     mangleFunctionEncoding(GD);
822e8d8bef9SDimitry Andric   else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
823e8d8bef9SDimitry Andric                BindingDecl>(GD.getDecl()))
824e8d8bef9SDimitry Andric     mangleName(GD);
8255ffd83dbSDimitry Andric   else if (const IndirectFieldDecl *IFD =
8265ffd83dbSDimitry Andric                dyn_cast<IndirectFieldDecl>(GD.getDecl()))
8270b57cec5SDimitry Andric     mangleName(IFD->getAnonField());
8280b57cec5SDimitry Andric   else
8295ffd83dbSDimitry Andric     llvm_unreachable("unexpected kind of global decl");
8300b57cec5SDimitry Andric }
8310b57cec5SDimitry Andric 
mangleFunctionEncoding(GlobalDecl GD)8325ffd83dbSDimitry Andric void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
8335ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
8340b57cec5SDimitry Andric   // <encoding> ::= <function name> <bare-function-type>
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   // Don't mangle in the type if this isn't a decl we should typically mangle.
8370b57cec5SDimitry Andric   if (!Context.shouldMangleDeclName(FD)) {
8385ffd83dbSDimitry Andric     mangleName(GD);
8390b57cec5SDimitry Andric     return;
8400b57cec5SDimitry Andric   }
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric   AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
8430b57cec5SDimitry Andric   if (ReturnTypeAbiTags.empty()) {
8445f757f3fSDimitry Andric     // There are no tags for return type, the simplest case. Enter the function
8455f757f3fSDimitry Andric     // parameter scope before mangling the name, because a template using
8465f757f3fSDimitry Andric     // constrained `auto` can have references to its parameters within its
8475f757f3fSDimitry Andric     // template argument list:
8485f757f3fSDimitry Andric     //
8495f757f3fSDimitry Andric     //   template<typename T> void f(T x, C<decltype(x)> auto)
8505f757f3fSDimitry Andric     // ... is mangled as ...
8515f757f3fSDimitry Andric     //   template<typename T, C<decltype(param 1)> U> void f(T, U)
8525f757f3fSDimitry Andric     FunctionTypeDepthState Saved = FunctionTypeDepth.push();
8535ffd83dbSDimitry Andric     mangleName(GD);
8545f757f3fSDimitry Andric     FunctionTypeDepth.pop(Saved);
8550b57cec5SDimitry Andric     mangleFunctionEncodingBareType(FD);
8560b57cec5SDimitry Andric     return;
8570b57cec5SDimitry Andric   }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   // Mangle function name and encoding to temporary buffer.
8600b57cec5SDimitry Andric   // We have to output name and encoding to the same mangler to get the same
8610b57cec5SDimitry Andric   // substitution as it will be in final mangling.
8620b57cec5SDimitry Andric   SmallString<256> FunctionEncodingBuf;
8630b57cec5SDimitry Andric   llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
8640b57cec5SDimitry Andric   CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
8650b57cec5SDimitry Andric   // Output name of the function.
8660b57cec5SDimitry Andric   FunctionEncodingMangler.disableDerivedAbiTags();
8675f757f3fSDimitry Andric 
8685f757f3fSDimitry Andric   FunctionTypeDepthState Saved = FunctionTypeDepth.push();
8690b57cec5SDimitry Andric   FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
8705f757f3fSDimitry Andric   FunctionTypeDepth.pop(Saved);
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric   // Remember length of the function name in the buffer.
8730b57cec5SDimitry Andric   size_t EncodingPositionStart = FunctionEncodingStream.str().size();
8740b57cec5SDimitry Andric   FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   // Get tags from return type that are not present in function name or
8770b57cec5SDimitry Andric   // encoding.
8780b57cec5SDimitry Andric   const AbiTagList &UsedAbiTags =
8790b57cec5SDimitry Andric       FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
8800b57cec5SDimitry Andric   AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
8810b57cec5SDimitry Andric   AdditionalAbiTags.erase(
8820b57cec5SDimitry Andric       std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
8830b57cec5SDimitry Andric                           UsedAbiTags.begin(), UsedAbiTags.end(),
8840b57cec5SDimitry Andric                           AdditionalAbiTags.begin()),
8850b57cec5SDimitry Andric       AdditionalAbiTags.end());
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric   // Output name with implicit tags and function encoding from temporary buffer.
8885f757f3fSDimitry Andric   Saved = FunctionTypeDepth.push();
8890b57cec5SDimitry Andric   mangleNameWithAbiTags(FD, &AdditionalAbiTags);
8905f757f3fSDimitry Andric   FunctionTypeDepth.pop(Saved);
8910b57cec5SDimitry Andric   Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric   // Function encoding could create new substitutions so we have to add
8940b57cec5SDimitry Andric   // temp mangled substitutions to main mangler.
8950b57cec5SDimitry Andric   extendSubstitutions(&FunctionEncodingMangler);
8960b57cec5SDimitry Andric }
8970b57cec5SDimitry Andric 
mangleFunctionEncodingBareType(const FunctionDecl * FD)8980b57cec5SDimitry Andric void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
8990b57cec5SDimitry Andric   if (FD->hasAttr<EnableIfAttr>()) {
9000b57cec5SDimitry Andric     FunctionTypeDepthState Saved = FunctionTypeDepth.push();
9010b57cec5SDimitry Andric     Out << "Ua9enable_ifI";
9020b57cec5SDimitry Andric     for (AttrVec::const_iterator I = FD->getAttrs().begin(),
9030b57cec5SDimitry Andric                                  E = FD->getAttrs().end();
9040b57cec5SDimitry Andric          I != E; ++I) {
9050b57cec5SDimitry Andric       EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
9060b57cec5SDimitry Andric       if (!EIA)
9070b57cec5SDimitry Andric         continue;
9085f757f3fSDimitry Andric       if (isCompatibleWith(LangOptions::ClangABI::Ver11)) {
909d409305fSDimitry Andric         // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
910d409305fSDimitry Andric         // even though <template-arg> should not include an X/E around
911d409305fSDimitry Andric         // <expr-primary>.
9120b57cec5SDimitry Andric         Out << 'X';
9130b57cec5SDimitry Andric         mangleExpression(EIA->getCond());
9140b57cec5SDimitry Andric         Out << 'E';
9155f757f3fSDimitry Andric       } else {
9165f757f3fSDimitry Andric         mangleTemplateArgExpr(EIA->getCond());
9170b57cec5SDimitry Andric       }
918d409305fSDimitry Andric     }
9190b57cec5SDimitry Andric     Out << 'E';
9200b57cec5SDimitry Andric     FunctionTypeDepth.pop(Saved);
9210b57cec5SDimitry Andric   }
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   // When mangling an inheriting constructor, the bare function type used is
9240b57cec5SDimitry Andric   // that of the inherited constructor.
9250b57cec5SDimitry Andric   if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
9260b57cec5SDimitry Andric     if (auto Inherited = CD->getInheritedConstructor())
9270b57cec5SDimitry Andric       FD = Inherited.getConstructor();
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   // Whether the mangling of a function type includes the return type depends on
9300b57cec5SDimitry Andric   // the context and the nature of the function. The rules for deciding whether
9310b57cec5SDimitry Andric   // the return type is included are:
9320b57cec5SDimitry Andric   //
9330b57cec5SDimitry Andric   //   1. Template functions (names or types) have return types encoded, with
9340b57cec5SDimitry Andric   //   the exceptions listed below.
9350b57cec5SDimitry Andric   //   2. Function types not appearing as part of a function name mangling,
9360b57cec5SDimitry Andric   //   e.g. parameters, pointer types, etc., have return type encoded, with the
9370b57cec5SDimitry Andric   //   exceptions listed below.
9380b57cec5SDimitry Andric   //   3. Non-template function names do not have return types encoded.
9390b57cec5SDimitry Andric   //
9400b57cec5SDimitry Andric   // The exceptions mentioned in (1) and (2) above, for which the return type is
9410b57cec5SDimitry Andric   // never included, are
9420b57cec5SDimitry Andric   //   1. Constructors.
9430b57cec5SDimitry Andric   //   2. Destructors.
9440b57cec5SDimitry Andric   //   3. Conversion operator functions, e.g. operator int.
9450b57cec5SDimitry Andric   bool MangleReturnType = false;
9460b57cec5SDimitry Andric   if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
9470b57cec5SDimitry Andric     if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
9480b57cec5SDimitry Andric           isa<CXXConversionDecl>(FD)))
9490b57cec5SDimitry Andric       MangleReturnType = true;
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric     // Mangle the type of the primary template.
9520b57cec5SDimitry Andric     FD = PrimaryTemplate->getTemplatedDecl();
9530b57cec5SDimitry Andric   }
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric   mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
9560b57cec5SDimitry Andric                          MangleReturnType, FD);
9570b57cec5SDimitry Andric }
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric /// Return whether a given namespace is the 'std' namespace.
isStd(const NamespaceDecl * NS)9602a66634dSDimitry Andric bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
9612a66634dSDimitry Andric   if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
9620b57cec5SDimitry Andric     return false;
9630b57cec5SDimitry Andric 
9640fca6ea1SDimitry Andric   const IdentifierInfo *II = NS->getFirstDecl()->getIdentifier();
9650b57cec5SDimitry Andric   return II && II->isStr("std");
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric // isStdNamespace - Return whether a given decl context is a toplevel 'std'
9690b57cec5SDimitry Andric // namespace.
isStdNamespace(const DeclContext * DC)9702a66634dSDimitry Andric bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
9710b57cec5SDimitry Andric   if (!DC->isNamespace())
9720b57cec5SDimitry Andric     return false;
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric   return isStd(cast<NamespaceDecl>(DC));
9750b57cec5SDimitry Andric }
9760b57cec5SDimitry Andric 
9775ffd83dbSDimitry Andric static const GlobalDecl
isTemplate(GlobalDecl GD,const TemplateArgumentList * & TemplateArgs)9785ffd83dbSDimitry Andric isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
9795ffd83dbSDimitry Andric   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
9800b57cec5SDimitry Andric   // Check if we have a function template.
9810b57cec5SDimitry Andric   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
9820b57cec5SDimitry Andric     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
9830b57cec5SDimitry Andric       TemplateArgs = FD->getTemplateSpecializationArgs();
9845ffd83dbSDimitry Andric       return GD.getWithDecl(TD);
9850b57cec5SDimitry Andric     }
9860b57cec5SDimitry Andric   }
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric   // Check if we have a class template.
9890b57cec5SDimitry Andric   if (const ClassTemplateSpecializationDecl *Spec =
9900b57cec5SDimitry Andric         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
9910b57cec5SDimitry Andric     TemplateArgs = &Spec->getTemplateArgs();
9925ffd83dbSDimitry Andric     return GD.getWithDecl(Spec->getSpecializedTemplate());
9930b57cec5SDimitry Andric   }
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric   // Check if we have a variable template.
9960b57cec5SDimitry Andric   if (const VarTemplateSpecializationDecl *Spec =
9970b57cec5SDimitry Andric           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
9980b57cec5SDimitry Andric     TemplateArgs = &Spec->getTemplateArgs();
9995ffd83dbSDimitry Andric     return GD.getWithDecl(Spec->getSpecializedTemplate());
10000b57cec5SDimitry Andric   }
10010b57cec5SDimitry Andric 
10025ffd83dbSDimitry Andric   return GlobalDecl();
10030b57cec5SDimitry Andric }
10040b57cec5SDimitry Andric 
asTemplateName(GlobalDecl GD)1005e8d8bef9SDimitry Andric static TemplateName asTemplateName(GlobalDecl GD) {
1006e8d8bef9SDimitry Andric   const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
1007e8d8bef9SDimitry Andric   return TemplateName(const_cast<TemplateDecl*>(TD));
1008e8d8bef9SDimitry Andric }
1009e8d8bef9SDimitry Andric 
mangleName(GlobalDecl GD)10105ffd83dbSDimitry Andric void CXXNameMangler::mangleName(GlobalDecl GD) {
10115ffd83dbSDimitry Andric   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
10120b57cec5SDimitry Andric   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
10130b57cec5SDimitry Andric     // Variables should have implicit tags from its type.
10140b57cec5SDimitry Andric     AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
10150b57cec5SDimitry Andric     if (VariableTypeAbiTags.empty()) {
10160b57cec5SDimitry Andric       // Simple case no variable type tags.
10170b57cec5SDimitry Andric       mangleNameWithAbiTags(VD, nullptr);
10180b57cec5SDimitry Andric       return;
10190b57cec5SDimitry Andric     }
10200b57cec5SDimitry Andric 
10210b57cec5SDimitry Andric     // Mangle variable name to null stream to collect tags.
10220b57cec5SDimitry Andric     llvm::raw_null_ostream NullOutStream;
10230b57cec5SDimitry Andric     CXXNameMangler VariableNameMangler(*this, NullOutStream);
10240b57cec5SDimitry Andric     VariableNameMangler.disableDerivedAbiTags();
10250b57cec5SDimitry Andric     VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
10260b57cec5SDimitry Andric 
10270b57cec5SDimitry Andric     // Get tags from variable type that are not present in its name.
10280b57cec5SDimitry Andric     const AbiTagList &UsedAbiTags =
10290b57cec5SDimitry Andric         VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
10300b57cec5SDimitry Andric     AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
10310b57cec5SDimitry Andric     AdditionalAbiTags.erase(
10320b57cec5SDimitry Andric         std::set_difference(VariableTypeAbiTags.begin(),
10330b57cec5SDimitry Andric                             VariableTypeAbiTags.end(), UsedAbiTags.begin(),
10340b57cec5SDimitry Andric                             UsedAbiTags.end(), AdditionalAbiTags.begin()),
10350b57cec5SDimitry Andric         AdditionalAbiTags.end());
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric     // Output name with implicit tags.
10380b57cec5SDimitry Andric     mangleNameWithAbiTags(VD, &AdditionalAbiTags);
10390b57cec5SDimitry Andric   } else {
10405ffd83dbSDimitry Andric     mangleNameWithAbiTags(GD, nullptr);
10410b57cec5SDimitry Andric   }
10420b57cec5SDimitry Andric }
10430b57cec5SDimitry Andric 
GetLocalClassDecl(const Decl * D)10442a66634dSDimitry Andric const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
10452a66634dSDimitry Andric   const DeclContext *DC = Context.getEffectiveDeclContext(D);
10462a66634dSDimitry Andric   while (!DC->isNamespace() && !DC->isTranslationUnit()) {
10472a66634dSDimitry Andric     if (isLocalContainerContext(DC))
10482a66634dSDimitry Andric       return dyn_cast<RecordDecl>(D);
10492a66634dSDimitry Andric     D = cast<Decl>(DC);
10502a66634dSDimitry Andric     DC = Context.getEffectiveDeclContext(D);
10512a66634dSDimitry Andric   }
10522a66634dSDimitry Andric   return nullptr;
10532a66634dSDimitry Andric }
10542a66634dSDimitry Andric 
mangleNameWithAbiTags(GlobalDecl GD,const AbiTagList * AdditionalAbiTags)10555ffd83dbSDimitry Andric void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
10560b57cec5SDimitry Andric                                            const AbiTagList *AdditionalAbiTags) {
10575ffd83dbSDimitry Andric   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
10580b57cec5SDimitry Andric   //  <name> ::= [<module-name>] <nested-name>
10590b57cec5SDimitry Andric   //         ::= [<module-name>] <unscoped-name>
10600b57cec5SDimitry Andric   //         ::= [<module-name>] <unscoped-template-name> <template-args>
10610b57cec5SDimitry Andric   //         ::= <local-name>
10620b57cec5SDimitry Andric   //
10632a66634dSDimitry Andric   const DeclContext *DC = Context.getEffectiveDeclContext(ND);
10640fca6ea1SDimitry Andric   bool IsLambda = isLambda(ND);
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric   // If this is an extern variable declared locally, the relevant DeclContext
10670b57cec5SDimitry Andric   // is that of the containing namespace, or the translation unit.
10680b57cec5SDimitry Andric   // FIXME: This is a hack; extern variables declared locally should have
10690b57cec5SDimitry Andric   // a proper semantic declaration context!
10700fca6ea1SDimitry Andric   if (isLocalContainerContext(DC) && ND->hasLinkage() && !IsLambda)
10710b57cec5SDimitry Andric     while (!DC->isNamespace() && !DC->isTranslationUnit())
10722a66634dSDimitry Andric       DC = Context.getEffectiveParentContext(DC);
10730fca6ea1SDimitry Andric   else if (GetLocalClassDecl(ND) &&
10740fca6ea1SDimitry Andric            (!IsLambda || isCompatibleWith(LangOptions::ClangABI::Ver18))) {
10755ffd83dbSDimitry Andric     mangleLocalName(GD, AdditionalAbiTags);
10760b57cec5SDimitry Andric     return;
10770b57cec5SDimitry Andric   }
10780b57cec5SDimitry Andric 
10792a66634dSDimitry Andric   assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");
10800b57cec5SDimitry Andric 
1081fe6060f1SDimitry Andric   // Closures can require a nested-name mangling even if they're semantically
1082fe6060f1SDimitry Andric   // in the global namespace.
1083fe6060f1SDimitry Andric   if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
1084fe6060f1SDimitry Andric     mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
1085fe6060f1SDimitry Andric     return;
1086fe6060f1SDimitry Andric   }
1087fe6060f1SDimitry Andric 
10880fca6ea1SDimitry Andric   if (isLocalContainerContext(DC)) {
10890fca6ea1SDimitry Andric     mangleLocalName(GD, AdditionalAbiTags);
10900fca6ea1SDimitry Andric     return;
10910fca6ea1SDimitry Andric   }
10920fca6ea1SDimitry Andric 
10930b57cec5SDimitry Andric   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
10940b57cec5SDimitry Andric     // Check if we have a template.
10950b57cec5SDimitry Andric     const TemplateArgumentList *TemplateArgs = nullptr;
10965ffd83dbSDimitry Andric     if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
109781ad6265SDimitry Andric       mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
1098e8d8bef9SDimitry Andric       mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
10990b57cec5SDimitry Andric       return;
11000b57cec5SDimitry Andric     }
11010b57cec5SDimitry Andric 
110281ad6265SDimitry Andric     mangleUnscopedName(GD, DC, AdditionalAbiTags);
11030b57cec5SDimitry Andric     return;
11040b57cec5SDimitry Andric   }
11050b57cec5SDimitry Andric 
11065ffd83dbSDimitry Andric   mangleNestedName(GD, DC, AdditionalAbiTags);
11070b57cec5SDimitry Andric }
11080b57cec5SDimitry Andric 
mangleModuleName(const NamedDecl * ND)110981ad6265SDimitry Andric void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
111081ad6265SDimitry Andric   if (ND->isExternallyVisible())
111181ad6265SDimitry Andric     if (Module *M = ND->getOwningModuleForLinkage())
111281ad6265SDimitry Andric       mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
11130b57cec5SDimitry Andric }
11140b57cec5SDimitry Andric 
111581ad6265SDimitry Andric // <module-name> ::= <module-subname>
111681ad6265SDimitry Andric //		 ::= <module-name> <module-subname>
111781ad6265SDimitry Andric //	 	 ::= <substitution>
111881ad6265SDimitry Andric // <module-subname> ::= W <source-name>
111981ad6265SDimitry Andric //		    ::= W P <source-name>
mangleModuleNamePrefix(StringRef Name,bool IsPartition)112081ad6265SDimitry Andric void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
112181ad6265SDimitry Andric   //  <substitution> ::= S <seq-id> _
11220b57cec5SDimitry Andric   auto It = ModuleSubstitutions.find(Name);
11230b57cec5SDimitry Andric   if (It != ModuleSubstitutions.end()) {
112481ad6265SDimitry Andric     Out << 'S';
112581ad6265SDimitry Andric     mangleSeqID(It->second);
11260b57cec5SDimitry Andric     return;
11270b57cec5SDimitry Andric   }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   // FIXME: Preserve hierarchy in module names rather than flattening
11300b57cec5SDimitry Andric   // them to strings; use Module*s as substitution keys.
11310b57cec5SDimitry Andric   auto Parts = Name.rsplit('.');
11320b57cec5SDimitry Andric   if (Parts.second.empty())
11330b57cec5SDimitry Andric     Parts.second = Parts.first;
113481ad6265SDimitry Andric   else {
113581ad6265SDimitry Andric     mangleModuleNamePrefix(Parts.first, IsPartition);
113681ad6265SDimitry Andric     IsPartition = false;
113781ad6265SDimitry Andric   }
11380b57cec5SDimitry Andric 
113981ad6265SDimitry Andric   Out << 'W';
114081ad6265SDimitry Andric   if (IsPartition)
114181ad6265SDimitry Andric     Out << 'P';
11420b57cec5SDimitry Andric   Out << Parts.second.size() << Parts.second;
114381ad6265SDimitry Andric   ModuleSubstitutions.insert({Name, SeqID++});
11440b57cec5SDimitry Andric }
11450b57cec5SDimitry Andric 
mangleTemplateName(const TemplateDecl * TD,ArrayRef<TemplateArgument> Args)11460b57cec5SDimitry Andric void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
1147bdd1243dSDimitry Andric                                         ArrayRef<TemplateArgument> Args) {
11482a66634dSDimitry Andric   const DeclContext *DC = Context.getEffectiveDeclContext(TD);
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
115181ad6265SDimitry Andric     mangleUnscopedTemplateName(TD, DC, nullptr);
1152bdd1243dSDimitry Andric     mangleTemplateArgs(asTemplateName(TD), Args);
11530b57cec5SDimitry Andric   } else {
1154bdd1243dSDimitry Andric     mangleNestedName(TD, Args);
11550b57cec5SDimitry Andric   }
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric 
mangleUnscopedName(GlobalDecl GD,const DeclContext * DC,const AbiTagList * AdditionalAbiTags)115881ad6265SDimitry Andric void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
11590b57cec5SDimitry Andric                                         const AbiTagList *AdditionalAbiTags) {
11600b57cec5SDimitry Andric   //  <unscoped-name> ::= <unqualified-name>
11610b57cec5SDimitry Andric   //                  ::= St <unqualified-name>   # ::std::
11620b57cec5SDimitry Andric 
116381ad6265SDimitry Andric   assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");
116481ad6265SDimitry Andric   if (isStdNamespace(DC))
11650b57cec5SDimitry Andric     Out << "St";
11660b57cec5SDimitry Andric 
116781ad6265SDimitry Andric   mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
11680b57cec5SDimitry Andric }
11690b57cec5SDimitry Andric 
mangleUnscopedTemplateName(GlobalDecl GD,const DeclContext * DC,const AbiTagList * AdditionalAbiTags)11700b57cec5SDimitry Andric void CXXNameMangler::mangleUnscopedTemplateName(
117181ad6265SDimitry Andric     GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
11725ffd83dbSDimitry Andric   const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
11730b57cec5SDimitry Andric   //     <unscoped-template-name> ::= <unscoped-name>
11740b57cec5SDimitry Andric   //                              ::= <substitution>
11750b57cec5SDimitry Andric   if (mangleSubstitution(ND))
11760b57cec5SDimitry Andric     return;
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric   // <template-template-param> ::= <template-param>
11790b57cec5SDimitry Andric   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
11800b57cec5SDimitry Andric     assert(!AdditionalAbiTags &&
11810b57cec5SDimitry Andric            "template template param cannot have abi tags");
1182a7dea167SDimitry Andric     mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1183a7dea167SDimitry Andric   } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
118481ad6265SDimitry Andric     mangleUnscopedName(GD, DC, AdditionalAbiTags);
11850b57cec5SDimitry Andric   } else {
118681ad6265SDimitry Andric     mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
118781ad6265SDimitry Andric                        AdditionalAbiTags);
11880b57cec5SDimitry Andric   }
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric   addSubstitution(ND);
11910b57cec5SDimitry Andric }
11920b57cec5SDimitry Andric 
mangleFloat(const llvm::APFloat & f)11930b57cec5SDimitry Andric void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
11940b57cec5SDimitry Andric   // ABI:
11950b57cec5SDimitry Andric   //   Floating-point literals are encoded using a fixed-length
11960b57cec5SDimitry Andric   //   lowercase hexadecimal string corresponding to the internal
11970b57cec5SDimitry Andric   //   representation (IEEE on Itanium), high-order bytes first,
11980b57cec5SDimitry Andric   //   without leading zeroes. For example: "Lf bf800000 E" is -1.0f
11990b57cec5SDimitry Andric   //   on Itanium.
12000b57cec5SDimitry Andric   // The 'without leading zeroes' thing seems to be an editorial
12010b57cec5SDimitry Andric   // mistake; see the discussion on cxx-abi-dev beginning on
12020b57cec5SDimitry Andric   // 2012-01-16.
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric   // Our requirements here are just barely weird enough to justify
12050b57cec5SDimitry Andric   // using a custom algorithm instead of post-processing APInt::toString().
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   llvm::APInt valueBits = f.bitcastToAPInt();
12080b57cec5SDimitry Andric   unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
12090b57cec5SDimitry Andric   assert(numCharacters != 0);
12100b57cec5SDimitry Andric 
12110b57cec5SDimitry Andric   // Allocate a buffer of the right number of characters.
12120b57cec5SDimitry Andric   SmallVector<char, 20> buffer(numCharacters);
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric   // Fill the buffer left-to-right.
12150b57cec5SDimitry Andric   for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
12160b57cec5SDimitry Andric     // The bit-index of the next hex digit.
12170b57cec5SDimitry Andric     unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric     // Project out 4 bits starting at 'digitIndex'.
12200b57cec5SDimitry Andric     uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
12210b57cec5SDimitry Andric     hexDigit >>= (digitBitIndex % 64);
12220b57cec5SDimitry Andric     hexDigit &= 0xF;
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric     // Map that over to a lowercase hex digit.
12250b57cec5SDimitry Andric     static const char charForHex[16] = {
12260b57cec5SDimitry Andric       '0', '1', '2', '3', '4', '5', '6', '7',
12270b57cec5SDimitry Andric       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
12280b57cec5SDimitry Andric     };
12290b57cec5SDimitry Andric     buffer[stringIndex] = charForHex[hexDigit];
12300b57cec5SDimitry Andric   }
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric   Out.write(buffer.data(), numCharacters);
12330b57cec5SDimitry Andric }
12340b57cec5SDimitry Andric 
mangleFloatLiteral(QualType T,const llvm::APFloat & V)1235e8d8bef9SDimitry Andric void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1236e8d8bef9SDimitry Andric   Out << 'L';
1237e8d8bef9SDimitry Andric   mangleType(T);
1238e8d8bef9SDimitry Andric   mangleFloat(V);
1239e8d8bef9SDimitry Andric   Out << 'E';
1240e8d8bef9SDimitry Andric }
1241e8d8bef9SDimitry Andric 
mangleFixedPointLiteral()1242e8d8bef9SDimitry Andric void CXXNameMangler::mangleFixedPointLiteral() {
1243e8d8bef9SDimitry Andric   DiagnosticsEngine &Diags = Context.getDiags();
1244e8d8bef9SDimitry Andric   unsigned DiagID = Diags.getCustomDiagID(
1245e8d8bef9SDimitry Andric       DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1246e8d8bef9SDimitry Andric   Diags.Report(DiagID);
1247e8d8bef9SDimitry Andric }
1248e8d8bef9SDimitry Andric 
mangleNullPointer(QualType T)1249e8d8bef9SDimitry Andric void CXXNameMangler::mangleNullPointer(QualType T) {
1250e8d8bef9SDimitry Andric   //  <expr-primary> ::= L <type> 0 E
1251e8d8bef9SDimitry Andric   Out << 'L';
1252e8d8bef9SDimitry Andric   mangleType(T);
1253e8d8bef9SDimitry Andric   Out << "0E";
1254e8d8bef9SDimitry Andric }
1255e8d8bef9SDimitry Andric 
mangleNumber(const llvm::APSInt & Value)12560b57cec5SDimitry Andric void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
12570b57cec5SDimitry Andric   if (Value.isSigned() && Value.isNegative()) {
12580b57cec5SDimitry Andric     Out << 'n';
12590b57cec5SDimitry Andric     Value.abs().print(Out, /*signed*/ false);
12600b57cec5SDimitry Andric   } else {
12610b57cec5SDimitry Andric     Value.print(Out, /*signed*/ false);
12620b57cec5SDimitry Andric   }
12630b57cec5SDimitry Andric }
12640b57cec5SDimitry Andric 
mangleNumber(int64_t Number)12650b57cec5SDimitry Andric void CXXNameMangler::mangleNumber(int64_t Number) {
12660b57cec5SDimitry Andric   //  <number> ::= [n] <non-negative decimal integer>
12670b57cec5SDimitry Andric   if (Number < 0) {
12680b57cec5SDimitry Andric     Out << 'n';
12690b57cec5SDimitry Andric     Number = -Number;
12700b57cec5SDimitry Andric   }
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric   Out << Number;
12730b57cec5SDimitry Andric }
12740b57cec5SDimitry Andric 
mangleCallOffset(int64_t NonVirtual,int64_t Virtual)12750b57cec5SDimitry Andric void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
12760b57cec5SDimitry Andric   //  <call-offset>  ::= h <nv-offset> _
12770b57cec5SDimitry Andric   //                 ::= v <v-offset> _
12780b57cec5SDimitry Andric   //  <nv-offset>    ::= <offset number>        # non-virtual base override
12790b57cec5SDimitry Andric   //  <v-offset>     ::= <offset number> _ <virtual offset number>
12800b57cec5SDimitry Andric   //                      # virtual base override, with vcall offset
12810b57cec5SDimitry Andric   if (!Virtual) {
12820b57cec5SDimitry Andric     Out << 'h';
12830b57cec5SDimitry Andric     mangleNumber(NonVirtual);
12840b57cec5SDimitry Andric     Out << '_';
12850b57cec5SDimitry Andric     return;
12860b57cec5SDimitry Andric   }
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric   Out << 'v';
12890b57cec5SDimitry Andric   mangleNumber(NonVirtual);
12900b57cec5SDimitry Andric   Out << '_';
12910b57cec5SDimitry Andric   mangleNumber(Virtual);
12920b57cec5SDimitry Andric   Out << '_';
12930b57cec5SDimitry Andric }
12940b57cec5SDimitry Andric 
manglePrefix(QualType type)12950b57cec5SDimitry Andric void CXXNameMangler::manglePrefix(QualType type) {
12960b57cec5SDimitry Andric   if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
12970b57cec5SDimitry Andric     if (!mangleSubstitution(QualType(TST, 0))) {
12980b57cec5SDimitry Andric       mangleTemplatePrefix(TST->getTemplateName());
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric       // FIXME: GCC does not appear to mangle the template arguments when
13010b57cec5SDimitry Andric       // the template in question is a dependent template name. Should we
13020b57cec5SDimitry Andric       // emulate that badness?
1303bdd1243dSDimitry Andric       mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());
13040b57cec5SDimitry Andric       addSubstitution(QualType(TST, 0));
13050b57cec5SDimitry Andric     }
13060b57cec5SDimitry Andric   } else if (const auto *DTST =
13070b57cec5SDimitry Andric                  type->getAs<DependentTemplateSpecializationType>()) {
13080b57cec5SDimitry Andric     if (!mangleSubstitution(QualType(DTST, 0))) {
13090b57cec5SDimitry Andric       TemplateName Template = getASTContext().getDependentTemplateName(
13100b57cec5SDimitry Andric           DTST->getQualifier(), DTST->getIdentifier());
13110b57cec5SDimitry Andric       mangleTemplatePrefix(Template);
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric       // FIXME: GCC does not appear to mangle the template arguments when
13140b57cec5SDimitry Andric       // the template in question is a dependent template name. Should we
13150b57cec5SDimitry Andric       // emulate that badness?
1316bdd1243dSDimitry Andric       mangleTemplateArgs(Template, DTST->template_arguments());
13170b57cec5SDimitry Andric       addSubstitution(QualType(DTST, 0));
13180b57cec5SDimitry Andric     }
13190b57cec5SDimitry Andric   } else {
13200b57cec5SDimitry Andric     // We use the QualType mangle type variant here because it handles
13210b57cec5SDimitry Andric     // substitutions.
13220b57cec5SDimitry Andric     mangleType(type);
13230b57cec5SDimitry Andric   }
13240b57cec5SDimitry Andric }
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
13270b57cec5SDimitry Andric ///
13280b57cec5SDimitry Andric /// \param recursive - true if this is being called recursively,
13290b57cec5SDimitry Andric ///   i.e. if there is more prefix "to the right".
mangleUnresolvedPrefix(NestedNameSpecifier * qualifier,bool recursive)13300b57cec5SDimitry Andric void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
13310b57cec5SDimitry Andric                                             bool recursive) {
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   // x, ::x
13340b57cec5SDimitry Andric   // <unresolved-name> ::= [gs] <base-unresolved-name>
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric   // T::x / decltype(p)::x
13370b57cec5SDimitry Andric   // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric   // T::N::x /decltype(p)::N::x
13400b57cec5SDimitry Andric   // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
13410b57cec5SDimitry Andric   //                       <base-unresolved-name>
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric   // A::x, N::y, A<T>::z; "gs" means leading "::"
13440b57cec5SDimitry Andric   // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
13450b57cec5SDimitry Andric   //                       <base-unresolved-name>
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric   switch (qualifier->getKind()) {
13480b57cec5SDimitry Andric   case NestedNameSpecifier::Global:
13490b57cec5SDimitry Andric     Out << "gs";
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric     // We want an 'sr' unless this is the entire NNS.
13520b57cec5SDimitry Andric     if (recursive)
13530b57cec5SDimitry Andric       Out << "sr";
13540b57cec5SDimitry Andric 
13550b57cec5SDimitry Andric     // We never want an 'E' here.
13560b57cec5SDimitry Andric     return;
13570b57cec5SDimitry Andric 
13580b57cec5SDimitry Andric   case NestedNameSpecifier::Super:
13590b57cec5SDimitry Andric     llvm_unreachable("Can't mangle __super specifier");
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric   case NestedNameSpecifier::Namespace:
13620b57cec5SDimitry Andric     if (qualifier->getPrefix())
13630b57cec5SDimitry Andric       mangleUnresolvedPrefix(qualifier->getPrefix(),
13640b57cec5SDimitry Andric                              /*recursive*/ true);
13650b57cec5SDimitry Andric     else
13660b57cec5SDimitry Andric       Out << "sr";
13670b57cec5SDimitry Andric     mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
13680b57cec5SDimitry Andric     break;
13690b57cec5SDimitry Andric   case NestedNameSpecifier::NamespaceAlias:
13700b57cec5SDimitry Andric     if (qualifier->getPrefix())
13710b57cec5SDimitry Andric       mangleUnresolvedPrefix(qualifier->getPrefix(),
13720b57cec5SDimitry Andric                              /*recursive*/ true);
13730b57cec5SDimitry Andric     else
13740b57cec5SDimitry Andric       Out << "sr";
13750b57cec5SDimitry Andric     mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
13760b57cec5SDimitry Andric     break;
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric   case NestedNameSpecifier::TypeSpec:
13790b57cec5SDimitry Andric   case NestedNameSpecifier::TypeSpecWithTemplate: {
13800b57cec5SDimitry Andric     const Type *type = qualifier->getAsType();
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric     // We only want to use an unresolved-type encoding if this is one of:
13830b57cec5SDimitry Andric     //   - a decltype
13840b57cec5SDimitry Andric     //   - a template type parameter
13850b57cec5SDimitry Andric     //   - a template template parameter with arguments
13860b57cec5SDimitry Andric     // In all of these cases, we should have no prefix.
13870b57cec5SDimitry Andric     if (qualifier->getPrefix()) {
13880b57cec5SDimitry Andric       mangleUnresolvedPrefix(qualifier->getPrefix(),
13890b57cec5SDimitry Andric                              /*recursive*/ true);
13900b57cec5SDimitry Andric     } else {
13910b57cec5SDimitry Andric       // Otherwise, all the cases want this.
13920b57cec5SDimitry Andric       Out << "sr";
13930b57cec5SDimitry Andric     }
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric     if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
13960b57cec5SDimitry Andric       return;
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric     break;
13990b57cec5SDimitry Andric   }
14000b57cec5SDimitry Andric 
14010b57cec5SDimitry Andric   case NestedNameSpecifier::Identifier:
14020b57cec5SDimitry Andric     // Member expressions can have these without prefixes.
14030b57cec5SDimitry Andric     if (qualifier->getPrefix())
14040b57cec5SDimitry Andric       mangleUnresolvedPrefix(qualifier->getPrefix(),
14050b57cec5SDimitry Andric                              /*recursive*/ true);
14060b57cec5SDimitry Andric     else
14070b57cec5SDimitry Andric       Out << "sr";
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric     mangleSourceName(qualifier->getAsIdentifier());
14100b57cec5SDimitry Andric     // An Identifier has no type information, so we can't emit abi tags for it.
14110b57cec5SDimitry Andric     break;
14120b57cec5SDimitry Andric   }
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric   // If this was the innermost part of the NNS, and we fell out to
14150b57cec5SDimitry Andric   // here, append an 'E'.
14160b57cec5SDimitry Andric   if (!recursive)
14170b57cec5SDimitry Andric     Out << 'E';
14180b57cec5SDimitry Andric }
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric /// Mangle an unresolved-name, which is generally used for names which
14210b57cec5SDimitry Andric /// weren't resolved to specific entities.
mangleUnresolvedName(NestedNameSpecifier * qualifier,DeclarationName name,const TemplateArgumentLoc * TemplateArgs,unsigned NumTemplateArgs,unsigned knownArity)14220b57cec5SDimitry Andric void CXXNameMangler::mangleUnresolvedName(
14230b57cec5SDimitry Andric     NestedNameSpecifier *qualifier, DeclarationName name,
14240b57cec5SDimitry Andric     const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
14250b57cec5SDimitry Andric     unsigned knownArity) {
14260b57cec5SDimitry Andric   if (qualifier) mangleUnresolvedPrefix(qualifier);
14270b57cec5SDimitry Andric   switch (name.getNameKind()) {
14280b57cec5SDimitry Andric     // <base-unresolved-name> ::= <simple-id>
14290b57cec5SDimitry Andric     case DeclarationName::Identifier:
14300b57cec5SDimitry Andric       mangleSourceName(name.getAsIdentifierInfo());
14310b57cec5SDimitry Andric       break;
14320b57cec5SDimitry Andric     // <base-unresolved-name> ::= dn <destructor-name>
14330b57cec5SDimitry Andric     case DeclarationName::CXXDestructorName:
14340b57cec5SDimitry Andric       Out << "dn";
14350b57cec5SDimitry Andric       mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
14360b57cec5SDimitry Andric       break;
14370b57cec5SDimitry Andric     // <base-unresolved-name> ::= on <operator-name>
14380b57cec5SDimitry Andric     case DeclarationName::CXXConversionFunctionName:
14390b57cec5SDimitry Andric     case DeclarationName::CXXLiteralOperatorName:
14400b57cec5SDimitry Andric     case DeclarationName::CXXOperatorName:
14410b57cec5SDimitry Andric       Out << "on";
14420b57cec5SDimitry Andric       mangleOperatorName(name, knownArity);
14430b57cec5SDimitry Andric       break;
14440b57cec5SDimitry Andric     case DeclarationName::CXXConstructorName:
14450b57cec5SDimitry Andric       llvm_unreachable("Can't mangle a constructor name!");
14460b57cec5SDimitry Andric     case DeclarationName::CXXUsingDirective:
14470b57cec5SDimitry Andric       llvm_unreachable("Can't mangle a using directive name!");
14480b57cec5SDimitry Andric     case DeclarationName::CXXDeductionGuideName:
14490b57cec5SDimitry Andric       llvm_unreachable("Can't mangle a deduction guide name!");
14500b57cec5SDimitry Andric     case DeclarationName::ObjCMultiArgSelector:
14510b57cec5SDimitry Andric     case DeclarationName::ObjCOneArgSelector:
14520b57cec5SDimitry Andric     case DeclarationName::ObjCZeroArgSelector:
14530b57cec5SDimitry Andric       llvm_unreachable("Can't mangle Objective-C selector names here!");
14540b57cec5SDimitry Andric   }
14550b57cec5SDimitry Andric 
14560b57cec5SDimitry Andric   // The <simple-id> and on <operator-name> productions end in an optional
14570b57cec5SDimitry Andric   // <template-args>.
14580b57cec5SDimitry Andric   if (TemplateArgs)
1459e8d8bef9SDimitry Andric     mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
14600b57cec5SDimitry Andric }
14610b57cec5SDimitry Andric 
mangleUnqualifiedName(GlobalDecl GD,DeclarationName Name,const DeclContext * DC,unsigned KnownArity,const AbiTagList * AdditionalAbiTags)146281ad6265SDimitry Andric void CXXNameMangler::mangleUnqualifiedName(
146381ad6265SDimitry Andric     GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
146481ad6265SDimitry Andric     unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
14655ffd83dbSDimitry Andric   const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
14665f757f3fSDimitry Andric   //  <unqualified-name> ::= [<module-name>] [F] <operator-name>
14670b57cec5SDimitry Andric   //                     ::= <ctor-dtor-name>
14685f757f3fSDimitry Andric   //                     ::= [<module-name>] [F] <source-name>
146981ad6265SDimitry Andric   //                     ::= [<module-name>] DC <source-name>* E
147081ad6265SDimitry Andric 
147181ad6265SDimitry Andric   if (ND && DC && DC->isFileContext())
147281ad6265SDimitry Andric     mangleModuleName(ND);
147381ad6265SDimitry Andric 
14745f757f3fSDimitry Andric   // A member-like constrained friend is mangled with a leading 'F'.
14755f757f3fSDimitry Andric   // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
14765f757f3fSDimitry Andric   auto *FD = dyn_cast<FunctionDecl>(ND);
14775f757f3fSDimitry Andric   auto *FTD = dyn_cast<FunctionTemplateDecl>(ND);
14785f757f3fSDimitry Andric   if ((FD && FD->isMemberLikeConstrainedFriend()) ||
14795f757f3fSDimitry Andric       (FTD && FTD->getTemplatedDecl()->isMemberLikeConstrainedFriend())) {
14805f757f3fSDimitry Andric     if (!isCompatibleWith(LangOptions::ClangABI::Ver17))
14815f757f3fSDimitry Andric       Out << 'F';
14825f757f3fSDimitry Andric   }
14835f757f3fSDimitry Andric 
148481ad6265SDimitry Andric   unsigned Arity = KnownArity;
14850b57cec5SDimitry Andric   switch (Name.getNameKind()) {
14860b57cec5SDimitry Andric   case DeclarationName::Identifier: {
14870b57cec5SDimitry Andric     const IdentifierInfo *II = Name.getAsIdentifierInfo();
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric     // We mangle decomposition declarations as the names of their bindings.
14900b57cec5SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
14910b57cec5SDimitry Andric       // FIXME: Non-standard mangling for decomposition declarations:
14920b57cec5SDimitry Andric       //
14930b57cec5SDimitry Andric       //  <unqualified-name> ::= DC <source-name>* E
14940b57cec5SDimitry Andric       //
14950b57cec5SDimitry Andric       // Proposed on cxx-abi-dev on 2016-08-12
14960b57cec5SDimitry Andric       Out << "DC";
14970b57cec5SDimitry Andric       for (auto *BD : DD->bindings())
14980b57cec5SDimitry Andric         mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
14990b57cec5SDimitry Andric       Out << 'E';
15000b57cec5SDimitry Andric       writeAbiTags(ND, AdditionalAbiTags);
15010b57cec5SDimitry Andric       break;
15020b57cec5SDimitry Andric     }
15030b57cec5SDimitry Andric 
15045ffd83dbSDimitry Andric     if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
15055ffd83dbSDimitry Andric       // We follow MSVC in mangling GUID declarations as if they were variables
15065ffd83dbSDimitry Andric       // with a particular reserved name. Continue the pretense here.
15075ffd83dbSDimitry Andric       SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
15085ffd83dbSDimitry Andric       llvm::raw_svector_ostream GUIDOS(GUID);
15095ffd83dbSDimitry Andric       Context.mangleMSGuidDecl(GD, GUIDOS);
15105ffd83dbSDimitry Andric       Out << GUID.size() << GUID;
15115ffd83dbSDimitry Andric       break;
15125ffd83dbSDimitry Andric     }
15135ffd83dbSDimitry Andric 
1514e8d8bef9SDimitry Andric     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1515e8d8bef9SDimitry Andric       // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1516e8d8bef9SDimitry Andric       Out << "TA";
1517e8d8bef9SDimitry Andric       mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1518e8d8bef9SDimitry Andric                                TPO->getValue(), /*TopLevel=*/true);
1519e8d8bef9SDimitry Andric       break;
1520e8d8bef9SDimitry Andric     }
1521e8d8bef9SDimitry Andric 
15220b57cec5SDimitry Andric     if (II) {
15230b57cec5SDimitry Andric       // Match GCC's naming convention for internal linkage symbols, for
15240b57cec5SDimitry Andric       // symbols that are not actually visible outside of this TU. GCC
15250b57cec5SDimitry Andric       // distinguishes between internal and external linkage symbols in
15260b57cec5SDimitry Andric       // its mangling, to support cases like this that were valid C++ prior
15270b57cec5SDimitry Andric       // to DR426:
15280b57cec5SDimitry Andric       //
15290b57cec5SDimitry Andric       //   void test() { extern void foo(); }
15300b57cec5SDimitry Andric       //   static void foo();
15310b57cec5SDimitry Andric       //
15320b57cec5SDimitry Andric       // Don't bother with the L marker for names in anonymous namespaces; the
15330b57cec5SDimitry Andric       // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
15340b57cec5SDimitry Andric       // matches GCC anyway, because GCC does not treat anonymous namespaces as
15350b57cec5SDimitry Andric       // implying internal linkage.
15362a66634dSDimitry Andric       if (Context.isInternalLinkageDecl(ND))
15370b57cec5SDimitry Andric         Out << 'L';
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric       bool IsRegCall = FD &&
15400b57cec5SDimitry Andric                        FD->getType()->castAs<FunctionType>()->getCallConv() ==
15410b57cec5SDimitry Andric                            clang::CC_X86RegCall;
15425ffd83dbSDimitry Andric       bool IsDeviceStub =
15435ffd83dbSDimitry Andric           FD && FD->hasAttr<CUDAGlobalAttr>() &&
15445ffd83dbSDimitry Andric           GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
15455ffd83dbSDimitry Andric       if (IsDeviceStub)
15465ffd83dbSDimitry Andric         mangleDeviceStubName(II);
15475ffd83dbSDimitry Andric       else if (IsRegCall)
15480b57cec5SDimitry Andric         mangleRegCallName(II);
15490b57cec5SDimitry Andric       else
15500b57cec5SDimitry Andric         mangleSourceName(II);
15510b57cec5SDimitry Andric 
15520b57cec5SDimitry Andric       writeAbiTags(ND, AdditionalAbiTags);
15530b57cec5SDimitry Andric       break;
15540b57cec5SDimitry Andric     }
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric     // Otherwise, an anonymous entity.  We must have a declaration.
15570b57cec5SDimitry Andric     assert(ND && "mangling empty name without declaration");
15580b57cec5SDimitry Andric 
15590b57cec5SDimitry Andric     if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
15600b57cec5SDimitry Andric       if (NS->isAnonymousNamespace()) {
15610b57cec5SDimitry Andric         // This is how gcc mangles these names.
15620b57cec5SDimitry Andric         Out << "12_GLOBAL__N_1";
15630b57cec5SDimitry Andric         break;
15640b57cec5SDimitry Andric       }
15650b57cec5SDimitry Andric     }
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric     if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
15680b57cec5SDimitry Andric       // We must have an anonymous union or struct declaration.
1569a7dea167SDimitry Andric       const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric       // Itanium C++ ABI 5.1.2:
15720b57cec5SDimitry Andric       //
15730b57cec5SDimitry Andric       //   For the purposes of mangling, the name of an anonymous union is
15740b57cec5SDimitry Andric       //   considered to be the name of the first named data member found by a
15750b57cec5SDimitry Andric       //   pre-order, depth-first, declaration-order walk of the data members of
15760b57cec5SDimitry Andric       //   the anonymous union. If there is no such data member (i.e., if all of
15770b57cec5SDimitry Andric       //   the data members in the union are unnamed), then there is no way for
15780b57cec5SDimitry Andric       //   a program to refer to the anonymous union, and there is therefore no
15790b57cec5SDimitry Andric       //   need to mangle its name.
15800b57cec5SDimitry Andric       assert(RD->isAnonymousStructOrUnion()
15810b57cec5SDimitry Andric              && "Expected anonymous struct or union!");
15820b57cec5SDimitry Andric       const FieldDecl *FD = RD->findFirstNamedDataMember();
15830b57cec5SDimitry Andric 
15840b57cec5SDimitry Andric       // It's actually possible for various reasons for us to get here
15850b57cec5SDimitry Andric       // with an empty anonymous struct / union.  Fortunately, it
15860b57cec5SDimitry Andric       // doesn't really matter what name we generate.
15870b57cec5SDimitry Andric       if (!FD) break;
15880b57cec5SDimitry Andric       assert(FD->getIdentifier() && "Data member name isn't an identifier!");
15890b57cec5SDimitry Andric 
15900b57cec5SDimitry Andric       mangleSourceName(FD->getIdentifier());
15910b57cec5SDimitry Andric       // Not emitting abi tags: internal name anyway.
15920b57cec5SDimitry Andric       break;
15930b57cec5SDimitry Andric     }
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric     // Class extensions have no name as a category, and it's possible
15960b57cec5SDimitry Andric     // for them to be the semantic parent of certain declarations
15970b57cec5SDimitry Andric     // (primarily, tag decls defined within declarations).  Such
15980b57cec5SDimitry Andric     // declarations will always have internal linkage, so the name
15990b57cec5SDimitry Andric     // doesn't really matter, but we shouldn't crash on them.  For
16000b57cec5SDimitry Andric     // safety, just handle all ObjC containers here.
16010b57cec5SDimitry Andric     if (isa<ObjCContainerDecl>(ND))
16020b57cec5SDimitry Andric       break;
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric     // We must have an anonymous struct.
16050b57cec5SDimitry Andric     const TagDecl *TD = cast<TagDecl>(ND);
16060b57cec5SDimitry Andric     if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
16070b57cec5SDimitry Andric       assert(TD->getDeclContext() == D->getDeclContext() &&
16080b57cec5SDimitry Andric              "Typedef should not be in another decl context!");
16090b57cec5SDimitry Andric       assert(D->getDeclName().getAsIdentifierInfo() &&
16100b57cec5SDimitry Andric              "Typedef was not named!");
16110b57cec5SDimitry Andric       mangleSourceName(D->getDeclName().getAsIdentifierInfo());
16120b57cec5SDimitry Andric       assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
16130b57cec5SDimitry Andric       // Explicit abi tags are still possible; take from underlying type, not
16140b57cec5SDimitry Andric       // from typedef.
16150b57cec5SDimitry Andric       writeAbiTags(TD, nullptr);
16160b57cec5SDimitry Andric       break;
16170b57cec5SDimitry Andric     }
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric     // <unnamed-type-name> ::= <closure-type-name>
16200b57cec5SDimitry Andric     //
16210b57cec5SDimitry Andric     // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
16220b57cec5SDimitry Andric     // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
16230b57cec5SDimitry Andric     //     # Parameter types or 'v' for 'void'.
16240b57cec5SDimitry Andric     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1625bdd1243dSDimitry Andric       std::optional<unsigned> DeviceNumber =
1626349cc55cSDimitry Andric           Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
1627349cc55cSDimitry Andric 
1628349cc55cSDimitry Andric       // If we have a device-number via the discriminator, use that to mangle
1629349cc55cSDimitry Andric       // the lambda, otherwise use the typical lambda-mangling-number. In either
1630349cc55cSDimitry Andric       // case, a '0' should be mangled as a normal unnamed class instead of as a
1631349cc55cSDimitry Andric       // lambda.
1632349cc55cSDimitry Andric       if (Record->isLambda() &&
1633349cc55cSDimitry Andric           ((DeviceNumber && *DeviceNumber > 0) ||
1634349cc55cSDimitry Andric            (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
16350b57cec5SDimitry Andric         assert(!AdditionalAbiTags &&
16360b57cec5SDimitry Andric                "Lambda type cannot have additional abi tags");
16370b57cec5SDimitry Andric         mangleLambda(Record);
16380b57cec5SDimitry Andric         break;
16390b57cec5SDimitry Andric       }
16400b57cec5SDimitry Andric     }
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric     if (TD->isExternallyVisible()) {
164381ad6265SDimitry Andric       unsigned UnnamedMangle =
164481ad6265SDimitry Andric           getASTContext().getManglingNumber(TD, Context.isAux());
16450b57cec5SDimitry Andric       Out << "Ut";
16460b57cec5SDimitry Andric       if (UnnamedMangle > 1)
16470b57cec5SDimitry Andric         Out << UnnamedMangle - 2;
16480b57cec5SDimitry Andric       Out << '_';
16490b57cec5SDimitry Andric       writeAbiTags(TD, AdditionalAbiTags);
16500b57cec5SDimitry Andric       break;
16510b57cec5SDimitry Andric     }
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric     // Get a unique id for the anonymous struct. If it is not a real output
16540b57cec5SDimitry Andric     // ID doesn't matter so use fake one.
1655bdd1243dSDimitry Andric     unsigned AnonStructId =
1656bdd1243dSDimitry Andric         NullOut ? 0
1657bdd1243dSDimitry Andric                 : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));
16580b57cec5SDimitry Andric 
16590b57cec5SDimitry Andric     // Mangle it as a source name in the form
16600b57cec5SDimitry Andric     // [n] $_<id>
16610b57cec5SDimitry Andric     // where n is the length of the string.
16620b57cec5SDimitry Andric     SmallString<8> Str;
16630b57cec5SDimitry Andric     Str += "$_";
16640b57cec5SDimitry Andric     Str += llvm::utostr(AnonStructId);
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric     Out << Str.size();
16670b57cec5SDimitry Andric     Out << Str;
16680b57cec5SDimitry Andric     break;
16690b57cec5SDimitry Andric   }
16700b57cec5SDimitry Andric 
16710b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
16720b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
16730b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
16740b57cec5SDimitry Andric     llvm_unreachable("Can't mangle Objective-C selector names here!");
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName: {
16770b57cec5SDimitry Andric     const CXXRecordDecl *InheritedFrom = nullptr;
1678e8d8bef9SDimitry Andric     TemplateName InheritedTemplateName;
16790b57cec5SDimitry Andric     const TemplateArgumentList *InheritedTemplateArgs = nullptr;
16800b57cec5SDimitry Andric     if (auto Inherited =
16810b57cec5SDimitry Andric             cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
16820b57cec5SDimitry Andric       InheritedFrom = Inherited.getConstructor()->getParent();
1683e8d8bef9SDimitry Andric       InheritedTemplateName =
1684e8d8bef9SDimitry Andric           TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
16850b57cec5SDimitry Andric       InheritedTemplateArgs =
16860b57cec5SDimitry Andric           Inherited.getConstructor()->getTemplateSpecializationArgs();
16870b57cec5SDimitry Andric     }
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric     if (ND == Structor)
16900b57cec5SDimitry Andric       // If the named decl is the C++ constructor we're mangling, use the type
16910b57cec5SDimitry Andric       // we were given.
16920b57cec5SDimitry Andric       mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
16930b57cec5SDimitry Andric     else
16940b57cec5SDimitry Andric       // Otherwise, use the complete constructor name. This is relevant if a
16950b57cec5SDimitry Andric       // class with a constructor is declared within a constructor.
16960b57cec5SDimitry Andric       mangleCXXCtorType(Ctor_Complete, InheritedFrom);
16970b57cec5SDimitry Andric 
16980b57cec5SDimitry Andric     // FIXME: The template arguments are part of the enclosing prefix or
16990b57cec5SDimitry Andric     // nested-name, but it's more convenient to mangle them here.
17000b57cec5SDimitry Andric     if (InheritedTemplateArgs)
1701e8d8bef9SDimitry Andric       mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric     writeAbiTags(ND, AdditionalAbiTags);
17040b57cec5SDimitry Andric     break;
17050b57cec5SDimitry Andric   }
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
17080b57cec5SDimitry Andric     if (ND == Structor)
17090b57cec5SDimitry Andric       // If the named decl is the C++ destructor we're mangling, use the type we
17100b57cec5SDimitry Andric       // were given.
17110b57cec5SDimitry Andric       mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
17120b57cec5SDimitry Andric     else
17130b57cec5SDimitry Andric       // Otherwise, use the complete destructor name. This is relevant if a
17140b57cec5SDimitry Andric       // class with a destructor is declared within a destructor.
17150b57cec5SDimitry Andric       mangleCXXDtorType(Dtor_Complete);
17165f757f3fSDimitry Andric     assert(ND);
17170b57cec5SDimitry Andric     writeAbiTags(ND, AdditionalAbiTags);
17180b57cec5SDimitry Andric     break;
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
17210b57cec5SDimitry Andric     if (ND && Arity == UnknownArity) {
17220b57cec5SDimitry Andric       Arity = cast<FunctionDecl>(ND)->getNumParams();
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric       // If we have a member function, we need to include the 'this' pointer.
17250b57cec5SDimitry Andric       if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
17265f757f3fSDimitry Andric         if (MD->isImplicitObjectMemberFunction())
17270b57cec5SDimitry Andric           Arity++;
17280b57cec5SDimitry Andric     }
1729bdd1243dSDimitry Andric     [[fallthrough]];
17300b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
17310b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
17320b57cec5SDimitry Andric     mangleOperatorName(Name, Arity);
17330b57cec5SDimitry Andric     writeAbiTags(ND, AdditionalAbiTags);
17340b57cec5SDimitry Andric     break;
17350b57cec5SDimitry Andric 
17360b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
17370b57cec5SDimitry Andric     llvm_unreachable("Can't mangle a deduction guide name!");
17380b57cec5SDimitry Andric 
17390b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
17400b57cec5SDimitry Andric     llvm_unreachable("Can't mangle a using directive name!");
17410b57cec5SDimitry Andric   }
17420b57cec5SDimitry Andric }
17430b57cec5SDimitry Andric 
mangleRegCallName(const IdentifierInfo * II)17440b57cec5SDimitry Andric void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
17450b57cec5SDimitry Andric   // <source-name> ::= <positive length number> __regcall3__ <identifier>
17460b57cec5SDimitry Andric   // <number> ::= [n] <non-negative decimal integer>
17470b57cec5SDimitry Andric   // <identifier> ::= <unqualified source code identifier>
17485f757f3fSDimitry Andric   if (getASTContext().getLangOpts().RegCall4)
17495f757f3fSDimitry Andric     Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"
17505f757f3fSDimitry Andric         << II->getName();
17515f757f3fSDimitry Andric   else
17520b57cec5SDimitry Andric     Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
17530b57cec5SDimitry Andric         << II->getName();
17540b57cec5SDimitry Andric }
17550b57cec5SDimitry Andric 
mangleDeviceStubName(const IdentifierInfo * II)17565ffd83dbSDimitry Andric void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
17575ffd83dbSDimitry Andric   // <source-name> ::= <positive length number> __device_stub__ <identifier>
17585ffd83dbSDimitry Andric   // <number> ::= [n] <non-negative decimal integer>
17595ffd83dbSDimitry Andric   // <identifier> ::= <unqualified source code identifier>
17605ffd83dbSDimitry Andric   Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
17615ffd83dbSDimitry Andric       << II->getName();
17625ffd83dbSDimitry Andric }
17635ffd83dbSDimitry Andric 
mangleSourceName(const IdentifierInfo * II)17640b57cec5SDimitry Andric void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
17650b57cec5SDimitry Andric   // <source-name> ::= <positive length number> <identifier>
17660b57cec5SDimitry Andric   // <number> ::= [n] <non-negative decimal integer>
17670b57cec5SDimitry Andric   // <identifier> ::= <unqualified source code identifier>
17680b57cec5SDimitry Andric   Out << II->getLength() << II->getName();
17690b57cec5SDimitry Andric }
17700b57cec5SDimitry Andric 
mangleNestedName(GlobalDecl GD,const DeclContext * DC,const AbiTagList * AdditionalAbiTags,bool NoFunction)17715ffd83dbSDimitry Andric void CXXNameMangler::mangleNestedName(GlobalDecl GD,
17720b57cec5SDimitry Andric                                       const DeclContext *DC,
17730b57cec5SDimitry Andric                                       const AbiTagList *AdditionalAbiTags,
17740b57cec5SDimitry Andric                                       bool NoFunction) {
17755ffd83dbSDimitry Andric   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
17760b57cec5SDimitry Andric   // <nested-name>
17770b57cec5SDimitry Andric   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
17780b57cec5SDimitry Andric   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
17790b57cec5SDimitry Andric   //       <template-args> E
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric   Out << 'N';
17820b57cec5SDimitry Andric   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
17830b57cec5SDimitry Andric     Qualifiers MethodQuals = Method->getMethodQualifiers();
17840b57cec5SDimitry Andric     // We do not consider restrict a distinguishing attribute for overloading
17850b57cec5SDimitry Andric     // purposes so we must not mangle it.
17865f757f3fSDimitry Andric     if (Method->isExplicitObjectMemberFunction())
17875f757f3fSDimitry Andric       Out << 'H';
17880b57cec5SDimitry Andric     MethodQuals.removeRestrict();
17890b57cec5SDimitry Andric     mangleQualifiers(MethodQuals);
17900b57cec5SDimitry Andric     mangleRefQualifier(Method->getRefQualifier());
17910b57cec5SDimitry Andric   }
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric   // Check if we have a template.
17940b57cec5SDimitry Andric   const TemplateArgumentList *TemplateArgs = nullptr;
17955ffd83dbSDimitry Andric   if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
17960b57cec5SDimitry Andric     mangleTemplatePrefix(TD, NoFunction);
1797e8d8bef9SDimitry Andric     mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1798fe6060f1SDimitry Andric   } else {
17990b57cec5SDimitry Andric     manglePrefix(DC, NoFunction);
180081ad6265SDimitry Andric     mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
18010b57cec5SDimitry Andric   }
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric   Out << 'E';
18040b57cec5SDimitry Andric }
mangleNestedName(const TemplateDecl * TD,ArrayRef<TemplateArgument> Args)18050b57cec5SDimitry Andric void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1806bdd1243dSDimitry Andric                                       ArrayRef<TemplateArgument> Args) {
18070b57cec5SDimitry Andric   // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   Out << 'N';
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric   mangleTemplatePrefix(TD);
1812bdd1243dSDimitry Andric   mangleTemplateArgs(asTemplateName(TD), Args);
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   Out << 'E';
18150b57cec5SDimitry Andric }
18160b57cec5SDimitry Andric 
mangleNestedNameWithClosurePrefix(GlobalDecl GD,const NamedDecl * PrefixND,const AbiTagList * AdditionalAbiTags)1817fe6060f1SDimitry Andric void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1818fe6060f1SDimitry Andric     GlobalDecl GD, const NamedDecl *PrefixND,
1819fe6060f1SDimitry Andric     const AbiTagList *AdditionalAbiTags) {
1820fe6060f1SDimitry Andric   // A <closure-prefix> represents a variable or field, not a regular
1821fe6060f1SDimitry Andric   // DeclContext, so needs special handling. In this case we're mangling a
1822fe6060f1SDimitry Andric   // limited form of <nested-name>:
1823fe6060f1SDimitry Andric   //
1824fe6060f1SDimitry Andric   // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1825fe6060f1SDimitry Andric 
1826fe6060f1SDimitry Andric   Out << 'N';
1827fe6060f1SDimitry Andric 
1828fe6060f1SDimitry Andric   mangleClosurePrefix(PrefixND);
182981ad6265SDimitry Andric   mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1830fe6060f1SDimitry Andric 
1831fe6060f1SDimitry Andric   Out << 'E';
1832fe6060f1SDimitry Andric }
1833fe6060f1SDimitry Andric 
getParentOfLocalEntity(const DeclContext * DC)18345ffd83dbSDimitry Andric static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
18355ffd83dbSDimitry Andric   GlobalDecl GD;
18365ffd83dbSDimitry Andric   // The Itanium spec says:
18375ffd83dbSDimitry Andric   // For entities in constructors and destructors, the mangling of the
18385ffd83dbSDimitry Andric   // complete object constructor or destructor is used as the base function
18395ffd83dbSDimitry Andric   // name, i.e. the C1 or D1 version.
18405ffd83dbSDimitry Andric   if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
18415ffd83dbSDimitry Andric     GD = GlobalDecl(CD, Ctor_Complete);
18425ffd83dbSDimitry Andric   else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
18435ffd83dbSDimitry Andric     GD = GlobalDecl(DD, Dtor_Complete);
18445ffd83dbSDimitry Andric   else
18455ffd83dbSDimitry Andric     GD = GlobalDecl(cast<FunctionDecl>(DC));
18465ffd83dbSDimitry Andric   return GD;
18475ffd83dbSDimitry Andric }
18485ffd83dbSDimitry Andric 
mangleLocalName(GlobalDecl GD,const AbiTagList * AdditionalAbiTags)18495ffd83dbSDimitry Andric void CXXNameMangler::mangleLocalName(GlobalDecl GD,
18500b57cec5SDimitry Andric                                      const AbiTagList *AdditionalAbiTags) {
18515ffd83dbSDimitry Andric   const Decl *D = GD.getDecl();
18520b57cec5SDimitry Andric   // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
18530b57cec5SDimitry Andric   //              := Z <function encoding> E s [<discriminator>]
18540b57cec5SDimitry Andric   // <local-name> := Z <function encoding> E d [ <parameter number> ]
18550b57cec5SDimitry Andric   //                 _ <entity name>
18560b57cec5SDimitry Andric   // <discriminator> := _ <non-negative number>
18570b57cec5SDimitry Andric   assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
18580b57cec5SDimitry Andric   const RecordDecl *RD = GetLocalClassDecl(D);
18592a66634dSDimitry Andric   const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric   Out << 'Z';
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric   {
18640b57cec5SDimitry Andric     AbiTagState LocalAbiTags(AbiTags);
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
18670b57cec5SDimitry Andric       mangleObjCMethodName(MD);
18680b57cec5SDimitry Andric     else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
18690b57cec5SDimitry Andric       mangleBlockForPrefix(BD);
18700b57cec5SDimitry Andric     else
18715ffd83dbSDimitry Andric       mangleFunctionEncoding(getParentOfLocalEntity(DC));
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric     // Implicit ABI tags (from namespace) are not available in the following
18740b57cec5SDimitry Andric     // entity; reset to actually emitted tags, which are available.
18750b57cec5SDimitry Andric     LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
18760b57cec5SDimitry Andric   }
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric   Out << 'E';
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric   // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
18810b57cec5SDimitry Andric   // be a bug that is fixed in trunk.
18820b57cec5SDimitry Andric 
18830b57cec5SDimitry Andric   if (RD) {
18840b57cec5SDimitry Andric     // The parameter number is omitted for the last parameter, 0 for the
18850b57cec5SDimitry Andric     // second-to-last parameter, 1 for the third-to-last parameter, etc. The
18860b57cec5SDimitry Andric     // <entity name> will of course contain a <closure-type-name>: Its
18870b57cec5SDimitry Andric     // numbering will be local to the particular argument in which it appears
18880b57cec5SDimitry Andric     // -- other default arguments do not affect its encoding.
18890b57cec5SDimitry Andric     const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
18900b57cec5SDimitry Andric     if (CXXRD && CXXRD->isLambda()) {
18910b57cec5SDimitry Andric       if (const ParmVarDecl *Parm
18920b57cec5SDimitry Andric               = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
18930b57cec5SDimitry Andric         if (const FunctionDecl *Func
18940b57cec5SDimitry Andric               = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
18950b57cec5SDimitry Andric           Out << 'd';
18960b57cec5SDimitry Andric           unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
18970b57cec5SDimitry Andric           if (Num > 1)
18980b57cec5SDimitry Andric             mangleNumber(Num - 2);
18990b57cec5SDimitry Andric           Out << '_';
19000b57cec5SDimitry Andric         }
19010b57cec5SDimitry Andric       }
19020b57cec5SDimitry Andric     }
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric     // Mangle the name relative to the closest enclosing function.
19050b57cec5SDimitry Andric     // equality ok because RD derived from ND above
19060b57cec5SDimitry Andric     if (D == RD)  {
190781ad6265SDimitry Andric       mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
19080b57cec5SDimitry Andric     } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1909fe6060f1SDimitry Andric       if (const NamedDecl *PrefixND = getClosurePrefix(BD))
1910fe6060f1SDimitry Andric         mangleClosurePrefix(PrefixND, true /*NoFunction*/);
1911fe6060f1SDimitry Andric       else
19122a66634dSDimitry Andric         manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
19130b57cec5SDimitry Andric       assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
19140b57cec5SDimitry Andric       mangleUnqualifiedBlock(BD);
19150b57cec5SDimitry Andric     } else {
19160b57cec5SDimitry Andric       const NamedDecl *ND = cast<NamedDecl>(D);
19172a66634dSDimitry Andric       mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
19182a66634dSDimitry Andric                        AdditionalAbiTags, true /*NoFunction*/);
19190b57cec5SDimitry Andric     }
19200b57cec5SDimitry Andric   } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
19210b57cec5SDimitry Andric     // Mangle a block in a default parameter; see above explanation for
19220b57cec5SDimitry Andric     // lambdas.
19230b57cec5SDimitry Andric     if (const ParmVarDecl *Parm
19240b57cec5SDimitry Andric             = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
19250b57cec5SDimitry Andric       if (const FunctionDecl *Func
19260b57cec5SDimitry Andric             = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
19270b57cec5SDimitry Andric         Out << 'd';
19280b57cec5SDimitry Andric         unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
19290b57cec5SDimitry Andric         if (Num > 1)
19300b57cec5SDimitry Andric           mangleNumber(Num - 2);
19310b57cec5SDimitry Andric         Out << '_';
19320b57cec5SDimitry Andric       }
19330b57cec5SDimitry Andric     }
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric     assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
19360b57cec5SDimitry Andric     mangleUnqualifiedBlock(BD);
19370b57cec5SDimitry Andric   } else {
193881ad6265SDimitry Andric     mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
19390b57cec5SDimitry Andric   }
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric   if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
19420b57cec5SDimitry Andric     unsigned disc;
19430b57cec5SDimitry Andric     if (Context.getNextDiscriminator(ND, disc)) {
19440b57cec5SDimitry Andric       if (disc < 10)
19450b57cec5SDimitry Andric         Out << '_' << disc;
19460b57cec5SDimitry Andric       else
19470b57cec5SDimitry Andric         Out << "__" << disc << '_';
19480b57cec5SDimitry Andric     }
19490b57cec5SDimitry Andric   }
19500b57cec5SDimitry Andric }
19510b57cec5SDimitry Andric 
mangleBlockForPrefix(const BlockDecl * Block)19520b57cec5SDimitry Andric void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
19530b57cec5SDimitry Andric   if (GetLocalClassDecl(Block)) {
19540b57cec5SDimitry Andric     mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
19550b57cec5SDimitry Andric     return;
19560b57cec5SDimitry Andric   }
19572a66634dSDimitry Andric   const DeclContext *DC = Context.getEffectiveDeclContext(Block);
19580b57cec5SDimitry Andric   if (isLocalContainerContext(DC)) {
19590b57cec5SDimitry Andric     mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
19600b57cec5SDimitry Andric     return;
19610b57cec5SDimitry Andric   }
1962fe6060f1SDimitry Andric   if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1963fe6060f1SDimitry Andric     mangleClosurePrefix(PrefixND);
1964fe6060f1SDimitry Andric   else
1965fe6060f1SDimitry Andric     manglePrefix(DC);
19660b57cec5SDimitry Andric   mangleUnqualifiedBlock(Block);
19670b57cec5SDimitry Andric }
19680b57cec5SDimitry Andric 
mangleUnqualifiedBlock(const BlockDecl * Block)19690b57cec5SDimitry Andric void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1970fe6060f1SDimitry Andric   // When trying to be ABI-compatibility with clang 12 and before, mangle a
1971fe6060f1SDimitry Andric   // <data-member-prefix> now, with no substitutions and no <template-args>.
19720b57cec5SDimitry Andric   if (Decl *Context = Block->getBlockManglingContextDecl()) {
19735f757f3fSDimitry Andric     if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
1974fe6060f1SDimitry Andric         (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
19750b57cec5SDimitry Andric         Context->getDeclContext()->isRecord()) {
19760b57cec5SDimitry Andric       const auto *ND = cast<NamedDecl>(Context);
19770b57cec5SDimitry Andric       if (ND->getIdentifier()) {
19780b57cec5SDimitry Andric         mangleSourceNameWithAbiTags(ND);
19790b57cec5SDimitry Andric         Out << 'M';
19800b57cec5SDimitry Andric       }
19810b57cec5SDimitry Andric     }
19820b57cec5SDimitry Andric   }
19830b57cec5SDimitry Andric 
19840b57cec5SDimitry Andric   // If we have a block mangling number, use it.
19850b57cec5SDimitry Andric   unsigned Number = Block->getBlockManglingNumber();
19860b57cec5SDimitry Andric   // Otherwise, just make up a number. It doesn't matter what it is because
19870b57cec5SDimitry Andric   // the symbol in question isn't externally visible.
19880b57cec5SDimitry Andric   if (!Number)
19890b57cec5SDimitry Andric     Number = Context.getBlockId(Block, false);
19900b57cec5SDimitry Andric   else {
19910b57cec5SDimitry Andric     // Stored mangling numbers are 1-based.
19920b57cec5SDimitry Andric     --Number;
19930b57cec5SDimitry Andric   }
19940b57cec5SDimitry Andric   Out << "Ub";
19950b57cec5SDimitry Andric   if (Number > 0)
19960b57cec5SDimitry Andric     Out << Number - 1;
19970b57cec5SDimitry Andric   Out << '_';
19980b57cec5SDimitry Andric }
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric // <template-param-decl>
20010b57cec5SDimitry Andric //   ::= Ty                                  # template type parameter
20025f757f3fSDimitry Andric //   ::= Tk <concept name> [<template-args>] # constrained type parameter
20030b57cec5SDimitry Andric //   ::= Tn <type>                           # template non-type parameter
20045f757f3fSDimitry Andric //   ::= Tt <template-param-decl>* E [Q <requires-clause expr>]
20055f757f3fSDimitry Andric //                                           # template template parameter
2006a7dea167SDimitry Andric //   ::= Tp <template-param-decl>            # template parameter pack
mangleTemplateParamDecl(const NamedDecl * Decl)20070b57cec5SDimitry Andric void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
20085f757f3fSDimitry Andric   // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
2009a7dea167SDimitry Andric   if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
2010a7dea167SDimitry Andric     if (Ty->isParameterPack())
2011a7dea167SDimitry Andric       Out << "Tp";
20125f757f3fSDimitry Andric     const TypeConstraint *Constraint = Ty->getTypeConstraint();
20135f757f3fSDimitry Andric     if (Constraint && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
20145f757f3fSDimitry Andric       // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
20155f757f3fSDimitry Andric       Out << "Tk";
20165f757f3fSDimitry Andric       mangleTypeConstraint(Constraint);
20175f757f3fSDimitry Andric     } else {
20180b57cec5SDimitry Andric       Out << "Ty";
20195f757f3fSDimitry Andric     }
20200b57cec5SDimitry Andric   } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
2021a7dea167SDimitry Andric     if (Tn->isExpandedParameterPack()) {
2022a7dea167SDimitry Andric       for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
20230b57cec5SDimitry Andric         Out << "Tn";
2024a7dea167SDimitry Andric         mangleType(Tn->getExpansionType(I));
2025a7dea167SDimitry Andric       }
2026a7dea167SDimitry Andric     } else {
2027a7dea167SDimitry Andric       QualType T = Tn->getType();
2028a7dea167SDimitry Andric       if (Tn->isParameterPack()) {
2029a7dea167SDimitry Andric         Out << "Tp";
2030a7dea167SDimitry Andric         if (auto *PackExpansion = T->getAs<PackExpansionType>())
2031a7dea167SDimitry Andric           T = PackExpansion->getPattern();
2032a7dea167SDimitry Andric       }
2033a7dea167SDimitry Andric       Out << "Tn";
2034a7dea167SDimitry Andric       mangleType(T);
2035a7dea167SDimitry Andric     }
20360b57cec5SDimitry Andric   } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
2037a7dea167SDimitry Andric     if (Tt->isExpandedParameterPack()) {
2038a7dea167SDimitry Andric       for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
20395f757f3fSDimitry Andric            ++I)
20405f757f3fSDimitry Andric         mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I));
2041a7dea167SDimitry Andric     } else {
2042a7dea167SDimitry Andric       if (Tt->isParameterPack())
2043a7dea167SDimitry Andric         Out << "Tp";
20445f757f3fSDimitry Andric       mangleTemplateParameterList(Tt->getTemplateParameters());
20455f757f3fSDimitry Andric     }
20465f757f3fSDimitry Andric   }
20475f757f3fSDimitry Andric }
20485f757f3fSDimitry Andric 
mangleTemplateParameterList(const TemplateParameterList * Params)20495f757f3fSDimitry Andric void CXXNameMangler::mangleTemplateParameterList(
20505f757f3fSDimitry Andric     const TemplateParameterList *Params) {
20510b57cec5SDimitry Andric   Out << "Tt";
20525f757f3fSDimitry Andric   for (auto *Param : *Params)
20530b57cec5SDimitry Andric     mangleTemplateParamDecl(Param);
20545f757f3fSDimitry Andric   mangleRequiresClause(Params->getRequiresClause());
20550b57cec5SDimitry Andric   Out << "E";
20560b57cec5SDimitry Andric }
20575f757f3fSDimitry Andric 
mangleTypeConstraint(const ConceptDecl * Concept,ArrayRef<TemplateArgument> Arguments)20585f757f3fSDimitry Andric void CXXNameMangler::mangleTypeConstraint(
20595f757f3fSDimitry Andric     const ConceptDecl *Concept, ArrayRef<TemplateArgument> Arguments) {
20605f757f3fSDimitry Andric   const DeclContext *DC = Context.getEffectiveDeclContext(Concept);
20615f757f3fSDimitry Andric   if (!Arguments.empty())
20625f757f3fSDimitry Andric     mangleTemplateName(Concept, Arguments);
20635f757f3fSDimitry Andric   else if (DC->isTranslationUnit() || isStdNamespace(DC))
20645f757f3fSDimitry Andric     mangleUnscopedName(Concept, DC, nullptr);
20655f757f3fSDimitry Andric   else
20665f757f3fSDimitry Andric     mangleNestedName(Concept, DC, nullptr);
20675f757f3fSDimitry Andric }
20685f757f3fSDimitry Andric 
mangleTypeConstraint(const TypeConstraint * Constraint)20695f757f3fSDimitry Andric void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) {
20705f757f3fSDimitry Andric   llvm::SmallVector<TemplateArgument, 8> Args;
20715f757f3fSDimitry Andric   if (Constraint->getTemplateArgsAsWritten()) {
20725f757f3fSDimitry Andric     for (const TemplateArgumentLoc &ArgLoc :
20735f757f3fSDimitry Andric          Constraint->getTemplateArgsAsWritten()->arguments())
20745f757f3fSDimitry Andric       Args.push_back(ArgLoc.getArgument());
20755f757f3fSDimitry Andric   }
20765f757f3fSDimitry Andric   return mangleTypeConstraint(Constraint->getNamedConcept(), Args);
20775f757f3fSDimitry Andric }
20785f757f3fSDimitry Andric 
mangleRequiresClause(const Expr * RequiresClause)20795f757f3fSDimitry Andric void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) {
20805f757f3fSDimitry Andric   // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
20815f757f3fSDimitry Andric   if (RequiresClause && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
20825f757f3fSDimitry Andric     Out << 'Q';
20835f757f3fSDimitry Andric     mangleExpression(RequiresClause);
20840b57cec5SDimitry Andric   }
2085a7dea167SDimitry Andric }
20860b57cec5SDimitry Andric 
mangleLambda(const CXXRecordDecl * Lambda)20870b57cec5SDimitry Andric void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
2088fe6060f1SDimitry Andric   // When trying to be ABI-compatibility with clang 12 and before, mangle a
2089fe6060f1SDimitry Andric   // <data-member-prefix> now, with no substitutions.
20900b57cec5SDimitry Andric   if (Decl *Context = Lambda->getLambdaContextDecl()) {
20915f757f3fSDimitry Andric     if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
2092fe6060f1SDimitry Andric         (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
20930b57cec5SDimitry Andric         !isa<ParmVarDecl>(Context)) {
20940b57cec5SDimitry Andric       if (const IdentifierInfo *Name
20950b57cec5SDimitry Andric             = cast<NamedDecl>(Context)->getIdentifier()) {
20960b57cec5SDimitry Andric         mangleSourceName(Name);
20970b57cec5SDimitry Andric         const TemplateArgumentList *TemplateArgs = nullptr;
2098e8d8bef9SDimitry Andric         if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
2099e8d8bef9SDimitry Andric           mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
21000b57cec5SDimitry Andric         Out << 'M';
21010b57cec5SDimitry Andric       }
21020b57cec5SDimitry Andric     }
21030b57cec5SDimitry Andric   }
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric   Out << "Ul";
2106a7dea167SDimitry Andric   mangleLambdaSig(Lambda);
21070b57cec5SDimitry Andric   Out << "E";
21080b57cec5SDimitry Andric 
21090b57cec5SDimitry Andric   // The number is omitted for the first closure type with a given
21100b57cec5SDimitry Andric   // <lambda-sig> in a given context; it is n-2 for the nth closure type
21110b57cec5SDimitry Andric   // (in lexical order) with that same <lambda-sig> and context.
21120b57cec5SDimitry Andric   //
21130b57cec5SDimitry Andric   // The AST keeps track of the number for us.
2114d409305fSDimitry Andric   //
2115d409305fSDimitry Andric   // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2116d409305fSDimitry Andric   // and host-side compilations, an extra device mangle context may be created
2117d409305fSDimitry Andric   // if the host-side CXX ABI has different numbering for lambda. In such case,
2118d409305fSDimitry Andric   // if the mangle context is that device-side one, use the device-side lambda
2119d409305fSDimitry Andric   // mangling number for this lambda.
2120bdd1243dSDimitry Andric   std::optional<unsigned> DeviceNumber =
2121fe6060f1SDimitry Andric       Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
2122349cc55cSDimitry Andric   unsigned Number =
2123349cc55cSDimitry Andric       DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2124fe6060f1SDimitry Andric 
21250b57cec5SDimitry Andric   assert(Number > 0 && "Lambda should be mangled as an unnamed class");
21260b57cec5SDimitry Andric   if (Number > 1)
21270b57cec5SDimitry Andric     mangleNumber(Number - 2);
21280b57cec5SDimitry Andric   Out << '_';
21290b57cec5SDimitry Andric }
21300b57cec5SDimitry Andric 
mangleLambdaSig(const CXXRecordDecl * Lambda)2131a7dea167SDimitry Andric void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
21325f757f3fSDimitry Andric   // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.
2133a7dea167SDimitry Andric   for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2134a7dea167SDimitry Andric     mangleTemplateParamDecl(D);
21355f757f3fSDimitry Andric 
21365f757f3fSDimitry Andric   // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
21375f757f3fSDimitry Andric   if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList())
21385f757f3fSDimitry Andric     mangleRequiresClause(TPL->getRequiresClause());
21395f757f3fSDimitry Andric 
21405ffd83dbSDimitry Andric   auto *Proto =
21415ffd83dbSDimitry Andric       Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();
2142a7dea167SDimitry Andric   mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
2143a7dea167SDimitry Andric                          Lambda->getLambdaStaticInvoker());
2144a7dea167SDimitry Andric }
2145a7dea167SDimitry Andric 
manglePrefix(NestedNameSpecifier * qualifier)21460b57cec5SDimitry Andric void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
21470b57cec5SDimitry Andric   switch (qualifier->getKind()) {
21480b57cec5SDimitry Andric   case NestedNameSpecifier::Global:
21490b57cec5SDimitry Andric     // nothing
21500b57cec5SDimitry Andric     return;
21510b57cec5SDimitry Andric 
21520b57cec5SDimitry Andric   case NestedNameSpecifier::Super:
21530b57cec5SDimitry Andric     llvm_unreachable("Can't mangle __super specifier");
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric   case NestedNameSpecifier::Namespace:
21560b57cec5SDimitry Andric     mangleName(qualifier->getAsNamespace());
21570b57cec5SDimitry Andric     return;
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric   case NestedNameSpecifier::NamespaceAlias:
21600b57cec5SDimitry Andric     mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
21610b57cec5SDimitry Andric     return;
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric   case NestedNameSpecifier::TypeSpec:
21640b57cec5SDimitry Andric   case NestedNameSpecifier::TypeSpecWithTemplate:
21650b57cec5SDimitry Andric     manglePrefix(QualType(qualifier->getAsType(), 0));
21660b57cec5SDimitry Andric     return;
21670b57cec5SDimitry Andric 
21680b57cec5SDimitry Andric   case NestedNameSpecifier::Identifier:
216981ad6265SDimitry Andric     // Clang 14 and before did not consider this substitutable.
21705f757f3fSDimitry Andric     bool Clang14Compat = isCompatibleWith(LangOptions::ClangABI::Ver14);
217181ad6265SDimitry Andric     if (!Clang14Compat && mangleSubstitution(qualifier))
217281ad6265SDimitry Andric       return;
217381ad6265SDimitry Andric 
21740b57cec5SDimitry Andric     // Member expressions can have these without prefixes, but that
21750b57cec5SDimitry Andric     // should end up in mangleUnresolvedPrefix instead.
21760b57cec5SDimitry Andric     assert(qualifier->getPrefix());
21770b57cec5SDimitry Andric     manglePrefix(qualifier->getPrefix());
21780b57cec5SDimitry Andric 
21790b57cec5SDimitry Andric     mangleSourceName(qualifier->getAsIdentifier());
218081ad6265SDimitry Andric 
218181ad6265SDimitry Andric     if (!Clang14Compat)
218281ad6265SDimitry Andric       addSubstitution(qualifier);
21830b57cec5SDimitry Andric     return;
21840b57cec5SDimitry Andric   }
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric   llvm_unreachable("unexpected nested name specifier");
21870b57cec5SDimitry Andric }
21880b57cec5SDimitry Andric 
manglePrefix(const DeclContext * DC,bool NoFunction)21890b57cec5SDimitry Andric void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
21900b57cec5SDimitry Andric   //  <prefix> ::= <prefix> <unqualified-name>
21910b57cec5SDimitry Andric   //           ::= <template-prefix> <template-args>
2192fe6060f1SDimitry Andric   //           ::= <closure-prefix>
21930b57cec5SDimitry Andric   //           ::= <template-param>
21940b57cec5SDimitry Andric   //           ::= # empty
21950b57cec5SDimitry Andric   //           ::= <substitution>
21960b57cec5SDimitry Andric 
21972a66634dSDimitry Andric   assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric   if (DC->isTranslationUnit())
22000b57cec5SDimitry Andric     return;
22010b57cec5SDimitry Andric 
22020b57cec5SDimitry Andric   if (NoFunction && isLocalContainerContext(DC))
22030b57cec5SDimitry Andric     return;
22040b57cec5SDimitry Andric 
22050b57cec5SDimitry Andric   const NamedDecl *ND = cast<NamedDecl>(DC);
22060b57cec5SDimitry Andric   if (mangleSubstitution(ND))
22070b57cec5SDimitry Andric     return;
22080b57cec5SDimitry Andric 
2209fe6060f1SDimitry Andric   // Check if we have a template-prefix or a closure-prefix.
22100b57cec5SDimitry Andric   const TemplateArgumentList *TemplateArgs = nullptr;
22115ffd83dbSDimitry Andric   if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
22120b57cec5SDimitry Andric     mangleTemplatePrefix(TD);
2213e8d8bef9SDimitry Andric     mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2214fe6060f1SDimitry Andric   } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2215fe6060f1SDimitry Andric     mangleClosurePrefix(PrefixND, NoFunction);
221681ad6265SDimitry Andric     mangleUnqualifiedName(ND, nullptr, nullptr);
22170b57cec5SDimitry Andric   } else {
221881ad6265SDimitry Andric     const DeclContext *DC = Context.getEffectiveDeclContext(ND);
221981ad6265SDimitry Andric     manglePrefix(DC, NoFunction);
222081ad6265SDimitry Andric     mangleUnqualifiedName(ND, DC, nullptr);
22210b57cec5SDimitry Andric   }
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric   addSubstitution(ND);
22240b57cec5SDimitry Andric }
22250b57cec5SDimitry Andric 
mangleTemplatePrefix(TemplateName Template)22260b57cec5SDimitry Andric void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
22270b57cec5SDimitry Andric   // <template-prefix> ::= <prefix> <template unqualified-name>
22280b57cec5SDimitry Andric   //                   ::= <template-param>
22290b57cec5SDimitry Andric   //                   ::= <substitution>
22300b57cec5SDimitry Andric   if (TemplateDecl *TD = Template.getAsTemplateDecl())
22310b57cec5SDimitry Andric     return mangleTemplatePrefix(TD);
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
2234e8d8bef9SDimitry Andric   assert(Dependent && "unexpected template name kind");
2235e8d8bef9SDimitry Andric 
2236e8d8bef9SDimitry Andric   // Clang 11 and before mangled the substitution for a dependent template name
2237e8d8bef9SDimitry Andric   // after already having emitted (a substitution for) the prefix.
22385f757f3fSDimitry Andric   bool Clang11Compat = isCompatibleWith(LangOptions::ClangABI::Ver11);
2239e8d8bef9SDimitry Andric   if (!Clang11Compat && mangleSubstitution(Template))
2240e8d8bef9SDimitry Andric     return;
2241e8d8bef9SDimitry Andric 
22420b57cec5SDimitry Andric   if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
22430b57cec5SDimitry Andric     manglePrefix(Qualifier);
2244e8d8bef9SDimitry Andric 
2245e8d8bef9SDimitry Andric   if (Clang11Compat && mangleSubstitution(Template))
2246e8d8bef9SDimitry Andric     return;
2247e8d8bef9SDimitry Andric 
2248e8d8bef9SDimitry Andric   if (const IdentifierInfo *Id = Dependent->getIdentifier())
2249e8d8bef9SDimitry Andric     mangleSourceName(Id);
2250e8d8bef9SDimitry Andric   else
2251e8d8bef9SDimitry Andric     mangleOperatorName(Dependent->getOperator(), UnknownArity);
2252e8d8bef9SDimitry Andric 
2253e8d8bef9SDimitry Andric   addSubstitution(Template);
22540b57cec5SDimitry Andric }
22550b57cec5SDimitry Andric 
mangleTemplatePrefix(GlobalDecl GD,bool NoFunction)22565ffd83dbSDimitry Andric void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
22570b57cec5SDimitry Andric                                           bool NoFunction) {
22585ffd83dbSDimitry Andric   const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
22590b57cec5SDimitry Andric   // <template-prefix> ::= <prefix> <template unqualified-name>
22600b57cec5SDimitry Andric   //                   ::= <template-param>
22610b57cec5SDimitry Andric   //                   ::= <substitution>
22620b57cec5SDimitry Andric   // <template-template-param> ::= <template-param>
22630b57cec5SDimitry Andric   //                               <substitution>
22640b57cec5SDimitry Andric 
22650b57cec5SDimitry Andric   if (mangleSubstitution(ND))
22660b57cec5SDimitry Andric     return;
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric   // <template-template-param> ::= <template-param>
22690b57cec5SDimitry Andric   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2270a7dea167SDimitry Andric     mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
22710b57cec5SDimitry Andric   } else {
227281ad6265SDimitry Andric     const DeclContext *DC = Context.getEffectiveDeclContext(ND);
227381ad6265SDimitry Andric     manglePrefix(DC, NoFunction);
2274a7dea167SDimitry Andric     if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
227581ad6265SDimitry Andric       mangleUnqualifiedName(GD, DC, nullptr);
22760b57cec5SDimitry Andric     else
227781ad6265SDimitry Andric       mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
227881ad6265SDimitry Andric                             nullptr);
22790b57cec5SDimitry Andric   }
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric   addSubstitution(ND);
22820b57cec5SDimitry Andric }
22830b57cec5SDimitry Andric 
getClosurePrefix(const Decl * ND)2284fe6060f1SDimitry Andric const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
22855f757f3fSDimitry Andric   if (isCompatibleWith(LangOptions::ClangABI::Ver12))
2286fe6060f1SDimitry Andric     return nullptr;
2287fe6060f1SDimitry Andric 
2288fe6060f1SDimitry Andric   const NamedDecl *Context = nullptr;
2289fe6060f1SDimitry Andric   if (auto *Block = dyn_cast<BlockDecl>(ND)) {
2290fe6060f1SDimitry Andric     Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
2291fe6060f1SDimitry Andric   } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
2292fe6060f1SDimitry Andric     if (RD->isLambda())
2293fe6060f1SDimitry Andric       Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2294fe6060f1SDimitry Andric   }
2295fe6060f1SDimitry Andric   if (!Context)
2296fe6060f1SDimitry Andric     return nullptr;
2297fe6060f1SDimitry Andric 
2298fe6060f1SDimitry Andric   // Only lambdas within the initializer of a non-local variable or non-static
2299fe6060f1SDimitry Andric   // data member get a <closure-prefix>.
2300fe6060f1SDimitry Andric   if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
2301fe6060f1SDimitry Andric       isa<FieldDecl>(Context))
2302fe6060f1SDimitry Andric     return Context;
2303fe6060f1SDimitry Andric 
2304fe6060f1SDimitry Andric   return nullptr;
2305fe6060f1SDimitry Andric }
2306fe6060f1SDimitry Andric 
mangleClosurePrefix(const NamedDecl * ND,bool NoFunction)2307fe6060f1SDimitry Andric void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2308fe6060f1SDimitry Andric   //  <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2309fe6060f1SDimitry Andric   //                   ::= <template-prefix> <template-args> M
2310fe6060f1SDimitry Andric   if (mangleSubstitution(ND))
2311fe6060f1SDimitry Andric     return;
2312fe6060f1SDimitry Andric 
2313fe6060f1SDimitry Andric   const TemplateArgumentList *TemplateArgs = nullptr;
2314fe6060f1SDimitry Andric   if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2315fe6060f1SDimitry Andric     mangleTemplatePrefix(TD, NoFunction);
2316fe6060f1SDimitry Andric     mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2317fe6060f1SDimitry Andric   } else {
231881ad6265SDimitry Andric     const auto *DC = Context.getEffectiveDeclContext(ND);
231981ad6265SDimitry Andric     manglePrefix(DC, NoFunction);
232081ad6265SDimitry Andric     mangleUnqualifiedName(ND, DC, nullptr);
2321fe6060f1SDimitry Andric   }
2322fe6060f1SDimitry Andric 
2323fe6060f1SDimitry Andric   Out << 'M';
2324fe6060f1SDimitry Andric 
2325fe6060f1SDimitry Andric   addSubstitution(ND);
2326fe6060f1SDimitry Andric }
2327fe6060f1SDimitry Andric 
23280b57cec5SDimitry Andric /// Mangles a template name under the production <type>.  Required for
23290b57cec5SDimitry Andric /// template template arguments.
23300b57cec5SDimitry Andric ///   <type> ::= <class-enum-type>
23310b57cec5SDimitry Andric ///          ::= <template-param>
23320b57cec5SDimitry Andric ///          ::= <substitution>
mangleType(TemplateName TN)23330b57cec5SDimitry Andric void CXXNameMangler::mangleType(TemplateName TN) {
23340b57cec5SDimitry Andric   if (mangleSubstitution(TN))
23350b57cec5SDimitry Andric     return;
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric   TemplateDecl *TD = nullptr;
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   switch (TN.getKind()) {
23400b57cec5SDimitry Andric   case TemplateName::QualifiedTemplate:
234181ad6265SDimitry Andric   case TemplateName::UsingTemplate:
23420b57cec5SDimitry Andric   case TemplateName::Template:
23430b57cec5SDimitry Andric     TD = TN.getAsTemplateDecl();
23440b57cec5SDimitry Andric     goto HaveDecl;
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric   HaveDecl:
2347a7dea167SDimitry Andric     if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2348a7dea167SDimitry Andric       mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
23490b57cec5SDimitry Andric     else
23500b57cec5SDimitry Andric       mangleName(TD);
23510b57cec5SDimitry Andric     break;
23520b57cec5SDimitry Andric 
23530b57cec5SDimitry Andric   case TemplateName::OverloadedTemplate:
23540b57cec5SDimitry Andric   case TemplateName::AssumedTemplate:
23550b57cec5SDimitry Andric     llvm_unreachable("can't mangle an overloaded template name as a <type>");
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric   case TemplateName::DependentTemplate: {
23580b57cec5SDimitry Andric     const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
23590b57cec5SDimitry Andric     assert(Dependent->isIdentifier());
23600b57cec5SDimitry Andric 
23610b57cec5SDimitry Andric     // <class-enum-type> ::= <name>
23620b57cec5SDimitry Andric     // <name> ::= <nested-name>
23630b57cec5SDimitry Andric     mangleUnresolvedPrefix(Dependent->getQualifier());
23640b57cec5SDimitry Andric     mangleSourceName(Dependent->getIdentifier());
23650b57cec5SDimitry Andric     break;
23660b57cec5SDimitry Andric   }
23670b57cec5SDimitry Andric 
23680b57cec5SDimitry Andric   case TemplateName::SubstTemplateTemplateParm: {
23690b57cec5SDimitry Andric     // Substituted template parameters are mangled as the substituted
23700b57cec5SDimitry Andric     // template.  This will check for the substitution twice, which is
23710b57cec5SDimitry Andric     // fine, but we have to return early so that we don't try to *add*
23720b57cec5SDimitry Andric     // the substitution twice.
23730b57cec5SDimitry Andric     SubstTemplateTemplateParmStorage *subst
23740b57cec5SDimitry Andric       = TN.getAsSubstTemplateTemplateParm();
23750b57cec5SDimitry Andric     mangleType(subst->getReplacement());
23760b57cec5SDimitry Andric     return;
23770b57cec5SDimitry Andric   }
23780b57cec5SDimitry Andric 
23790b57cec5SDimitry Andric   case TemplateName::SubstTemplateTemplateParmPack: {
23800b57cec5SDimitry Andric     // FIXME: not clear how to mangle this!
23810b57cec5SDimitry Andric     // template <template <class> class T...> class A {
23820b57cec5SDimitry Andric     //   template <template <class> class U...> void foo(B<T,U> x...);
23830b57cec5SDimitry Andric     // };
23840b57cec5SDimitry Andric     Out << "_SUBSTPACK_";
23850b57cec5SDimitry Andric     break;
23860b57cec5SDimitry Andric   }
23870b57cec5SDimitry Andric   }
23880b57cec5SDimitry Andric 
23890b57cec5SDimitry Andric   addSubstitution(TN);
23900b57cec5SDimitry Andric }
23910b57cec5SDimitry Andric 
mangleUnresolvedTypeOrSimpleId(QualType Ty,StringRef Prefix)23920b57cec5SDimitry Andric bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
23930b57cec5SDimitry Andric                                                     StringRef Prefix) {
23940b57cec5SDimitry Andric   // Only certain other types are valid as prefixes;  enumerate them.
23950b57cec5SDimitry Andric   switch (Ty->getTypeClass()) {
23960b57cec5SDimitry Andric   case Type::Builtin:
23970b57cec5SDimitry Andric   case Type::Complex:
23980b57cec5SDimitry Andric   case Type::Adjusted:
23990b57cec5SDimitry Andric   case Type::Decayed:
24000fca6ea1SDimitry Andric   case Type::ArrayParameter:
24010b57cec5SDimitry Andric   case Type::Pointer:
24020b57cec5SDimitry Andric   case Type::BlockPointer:
24030b57cec5SDimitry Andric   case Type::LValueReference:
24040b57cec5SDimitry Andric   case Type::RValueReference:
24050b57cec5SDimitry Andric   case Type::MemberPointer:
24060b57cec5SDimitry Andric   case Type::ConstantArray:
24070b57cec5SDimitry Andric   case Type::IncompleteArray:
24080b57cec5SDimitry Andric   case Type::VariableArray:
24090b57cec5SDimitry Andric   case Type::DependentSizedArray:
24100b57cec5SDimitry Andric   case Type::DependentAddressSpace:
24110b57cec5SDimitry Andric   case Type::DependentVector:
24120b57cec5SDimitry Andric   case Type::DependentSizedExtVector:
24130b57cec5SDimitry Andric   case Type::Vector:
24140b57cec5SDimitry Andric   case Type::ExtVector:
24155ffd83dbSDimitry Andric   case Type::ConstantMatrix:
24165ffd83dbSDimitry Andric   case Type::DependentSizedMatrix:
24170b57cec5SDimitry Andric   case Type::FunctionProto:
24180b57cec5SDimitry Andric   case Type::FunctionNoProto:
24190b57cec5SDimitry Andric   case Type::Paren:
24200b57cec5SDimitry Andric   case Type::Attributed:
242181ad6265SDimitry Andric   case Type::BTFTagAttributed:
24220b57cec5SDimitry Andric   case Type::Auto:
24230b57cec5SDimitry Andric   case Type::DeducedTemplateSpecialization:
24240b57cec5SDimitry Andric   case Type::PackExpansion:
24250b57cec5SDimitry Andric   case Type::ObjCObject:
24260b57cec5SDimitry Andric   case Type::ObjCInterface:
24270b57cec5SDimitry Andric   case Type::ObjCObjectPointer:
24280b57cec5SDimitry Andric   case Type::ObjCTypeParam:
24290b57cec5SDimitry Andric   case Type::Atomic:
24300b57cec5SDimitry Andric   case Type::Pipe:
24310b57cec5SDimitry Andric   case Type::MacroQualified:
24320eae32dcSDimitry Andric   case Type::BitInt:
24330eae32dcSDimitry Andric   case Type::DependentBitInt:
24340fca6ea1SDimitry Andric   case Type::CountAttributed:
24350b57cec5SDimitry Andric     llvm_unreachable("type is illegal as a nested name specifier");
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric   case Type::SubstTemplateTypeParmPack:
24380b57cec5SDimitry Andric     // FIXME: not clear how to mangle this!
24390b57cec5SDimitry Andric     // template <class T...> class A {
24400b57cec5SDimitry Andric     //   template <class U...> void foo(decltype(T::foo(U())) x...);
24410b57cec5SDimitry Andric     // };
24420b57cec5SDimitry Andric     Out << "_SUBSTPACK_";
24430b57cec5SDimitry Andric     break;
24440b57cec5SDimitry Andric 
24450b57cec5SDimitry Andric   // <unresolved-type> ::= <template-param>
24460b57cec5SDimitry Andric   //                   ::= <decltype>
24470b57cec5SDimitry Andric   //                   ::= <template-template-param> <template-args>
24480b57cec5SDimitry Andric   // (this last is not official yet)
24490b57cec5SDimitry Andric   case Type::TypeOfExpr:
24500b57cec5SDimitry Andric   case Type::TypeOf:
24510b57cec5SDimitry Andric   case Type::Decltype:
24520fca6ea1SDimitry Andric   case Type::PackIndexing:
24530b57cec5SDimitry Andric   case Type::TemplateTypeParm:
24540b57cec5SDimitry Andric   case Type::UnaryTransform:
24550b57cec5SDimitry Andric   case Type::SubstTemplateTypeParm:
24560b57cec5SDimitry Andric   unresolvedType:
24570b57cec5SDimitry Andric     // Some callers want a prefix before the mangled type.
24580b57cec5SDimitry Andric     Out << Prefix;
24590b57cec5SDimitry Andric 
24600b57cec5SDimitry Andric     // This seems to do everything we want.  It's not really
24610b57cec5SDimitry Andric     // sanctioned for a substituted template parameter, though.
24620b57cec5SDimitry Andric     mangleType(Ty);
24630b57cec5SDimitry Andric 
24640b57cec5SDimitry Andric     // We never want to print 'E' directly after an unresolved-type,
24650b57cec5SDimitry Andric     // so we return directly.
24660b57cec5SDimitry Andric     return true;
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric   case Type::Typedef:
24690b57cec5SDimitry Andric     mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
24700b57cec5SDimitry Andric     break;
24710b57cec5SDimitry Andric 
24720b57cec5SDimitry Andric   case Type::UnresolvedUsing:
24730b57cec5SDimitry Andric     mangleSourceNameWithAbiTags(
24740b57cec5SDimitry Andric         cast<UnresolvedUsingType>(Ty)->getDecl());
24750b57cec5SDimitry Andric     break;
24760b57cec5SDimitry Andric 
24770b57cec5SDimitry Andric   case Type::Enum:
24780b57cec5SDimitry Andric   case Type::Record:
24790b57cec5SDimitry Andric     mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
24800b57cec5SDimitry Andric     break;
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric   case Type::TemplateSpecialization: {
24830b57cec5SDimitry Andric     const TemplateSpecializationType *TST =
24840b57cec5SDimitry Andric         cast<TemplateSpecializationType>(Ty);
24850b57cec5SDimitry Andric     TemplateName TN = TST->getTemplateName();
24860b57cec5SDimitry Andric     switch (TN.getKind()) {
24870b57cec5SDimitry Andric     case TemplateName::Template:
24880b57cec5SDimitry Andric     case TemplateName::QualifiedTemplate: {
24890b57cec5SDimitry Andric       TemplateDecl *TD = TN.getAsTemplateDecl();
24900b57cec5SDimitry Andric 
24910b57cec5SDimitry Andric       // If the base is a template template parameter, this is an
24920b57cec5SDimitry Andric       // unresolved type.
24930b57cec5SDimitry Andric       assert(TD && "no template for template specialization type");
24940b57cec5SDimitry Andric       if (isa<TemplateTemplateParmDecl>(TD))
24950b57cec5SDimitry Andric         goto unresolvedType;
24960b57cec5SDimitry Andric 
24970b57cec5SDimitry Andric       mangleSourceNameWithAbiTags(TD);
24980b57cec5SDimitry Andric       break;
24990b57cec5SDimitry Andric     }
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric     case TemplateName::OverloadedTemplate:
25020b57cec5SDimitry Andric     case TemplateName::AssumedTemplate:
25030b57cec5SDimitry Andric     case TemplateName::DependentTemplate:
25040b57cec5SDimitry Andric       llvm_unreachable("invalid base for a template specialization type");
25050b57cec5SDimitry Andric 
25060b57cec5SDimitry Andric     case TemplateName::SubstTemplateTemplateParm: {
25070b57cec5SDimitry Andric       SubstTemplateTemplateParmStorage *subst =
25080b57cec5SDimitry Andric           TN.getAsSubstTemplateTemplateParm();
25090b57cec5SDimitry Andric       mangleExistingSubstitution(subst->getReplacement());
25100b57cec5SDimitry Andric       break;
25110b57cec5SDimitry Andric     }
25120b57cec5SDimitry Andric 
25130b57cec5SDimitry Andric     case TemplateName::SubstTemplateTemplateParmPack: {
25140b57cec5SDimitry Andric       // FIXME: not clear how to mangle this!
25150b57cec5SDimitry Andric       // template <template <class U> class T...> class A {
25160b57cec5SDimitry Andric       //   template <class U...> void foo(decltype(T<U>::foo) x...);
25170b57cec5SDimitry Andric       // };
25180b57cec5SDimitry Andric       Out << "_SUBSTPACK_";
25190b57cec5SDimitry Andric       break;
25200b57cec5SDimitry Andric     }
252181ad6265SDimitry Andric     case TemplateName::UsingTemplate: {
252281ad6265SDimitry Andric       TemplateDecl *TD = TN.getAsTemplateDecl();
252381ad6265SDimitry Andric       assert(TD && !isa<TemplateTemplateParmDecl>(TD));
252481ad6265SDimitry Andric       mangleSourceNameWithAbiTags(TD);
252581ad6265SDimitry Andric       break;
252681ad6265SDimitry Andric     }
25270b57cec5SDimitry Andric     }
25280b57cec5SDimitry Andric 
2529e8d8bef9SDimitry Andric     // Note: we don't pass in the template name here. We are mangling the
2530e8d8bef9SDimitry Andric     // original source-level template arguments, so we shouldn't consider
2531e8d8bef9SDimitry Andric     // conversions to the corresponding template parameter.
2532e8d8bef9SDimitry Andric     // FIXME: Other compilers mangle partially-resolved template arguments in
2533e8d8bef9SDimitry Andric     // unresolved-qualifier-levels.
2534bdd1243dSDimitry Andric     mangleTemplateArgs(TemplateName(), TST->template_arguments());
25350b57cec5SDimitry Andric     break;
25360b57cec5SDimitry Andric   }
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric   case Type::InjectedClassName:
25390b57cec5SDimitry Andric     mangleSourceNameWithAbiTags(
25400b57cec5SDimitry Andric         cast<InjectedClassNameType>(Ty)->getDecl());
25410b57cec5SDimitry Andric     break;
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric   case Type::DependentName:
25440b57cec5SDimitry Andric     mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
25450b57cec5SDimitry Andric     break;
25460b57cec5SDimitry Andric 
25470b57cec5SDimitry Andric   case Type::DependentTemplateSpecialization: {
25480b57cec5SDimitry Andric     const DependentTemplateSpecializationType *DTST =
25490b57cec5SDimitry Andric         cast<DependentTemplateSpecializationType>(Ty);
2550e8d8bef9SDimitry Andric     TemplateName Template = getASTContext().getDependentTemplateName(
2551e8d8bef9SDimitry Andric         DTST->getQualifier(), DTST->getIdentifier());
25520b57cec5SDimitry Andric     mangleSourceName(DTST->getIdentifier());
2553bdd1243dSDimitry Andric     mangleTemplateArgs(Template, DTST->template_arguments());
25540b57cec5SDimitry Andric     break;
25550b57cec5SDimitry Andric   }
25560b57cec5SDimitry Andric 
25570eae32dcSDimitry Andric   case Type::Using:
25580eae32dcSDimitry Andric     return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
25590eae32dcSDimitry Andric                                           Prefix);
25600b57cec5SDimitry Andric   case Type::Elaborated:
25610b57cec5SDimitry Andric     return mangleUnresolvedTypeOrSimpleId(
25620b57cec5SDimitry Andric         cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
25630b57cec5SDimitry Andric   }
25640b57cec5SDimitry Andric 
25650b57cec5SDimitry Andric   return false;
25660b57cec5SDimitry Andric }
25670b57cec5SDimitry Andric 
mangleOperatorName(DeclarationName Name,unsigned Arity)25680b57cec5SDimitry Andric void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
25690b57cec5SDimitry Andric   switch (Name.getNameKind()) {
25700b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName:
25710b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
25720b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
25730b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
25740b57cec5SDimitry Andric   case DeclarationName::Identifier:
25750b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
25760b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
25770b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
25780b57cec5SDimitry Andric     llvm_unreachable("Not an operator name");
25790b57cec5SDimitry Andric 
25800b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
25810b57cec5SDimitry Andric     // <operator-name> ::= cv <type>    # (cast)
25820b57cec5SDimitry Andric     Out << "cv";
25830b57cec5SDimitry Andric     mangleType(Name.getCXXNameType());
25840b57cec5SDimitry Andric     break;
25850b57cec5SDimitry Andric 
25860b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
25870b57cec5SDimitry Andric     Out << "li";
25880b57cec5SDimitry Andric     mangleSourceName(Name.getCXXLiteralIdentifier());
25890b57cec5SDimitry Andric     return;
25900b57cec5SDimitry Andric 
25910b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
25920b57cec5SDimitry Andric     mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
25930b57cec5SDimitry Andric     break;
25940b57cec5SDimitry Andric   }
25950b57cec5SDimitry Andric }
25960b57cec5SDimitry Andric 
25970b57cec5SDimitry Andric void
mangleOperatorName(OverloadedOperatorKind OO,unsigned Arity)25980b57cec5SDimitry Andric CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
25990b57cec5SDimitry Andric   switch (OO) {
26000b57cec5SDimitry Andric   // <operator-name> ::= nw     # new
26010b57cec5SDimitry Andric   case OO_New: Out << "nw"; break;
26020b57cec5SDimitry Andric   //              ::= na        # new[]
26030b57cec5SDimitry Andric   case OO_Array_New: Out << "na"; break;
26040b57cec5SDimitry Andric   //              ::= dl        # delete
26050b57cec5SDimitry Andric   case OO_Delete: Out << "dl"; break;
26060b57cec5SDimitry Andric   //              ::= da        # delete[]
26070b57cec5SDimitry Andric   case OO_Array_Delete: Out << "da"; break;
26080b57cec5SDimitry Andric   //              ::= ps        # + (unary)
26090b57cec5SDimitry Andric   //              ::= pl        # + (binary or unknown)
26100b57cec5SDimitry Andric   case OO_Plus:
26110b57cec5SDimitry Andric     Out << (Arity == 1? "ps" : "pl"); break;
26120b57cec5SDimitry Andric   //              ::= ng        # - (unary)
26130b57cec5SDimitry Andric   //              ::= mi        # - (binary or unknown)
26140b57cec5SDimitry Andric   case OO_Minus:
26150b57cec5SDimitry Andric     Out << (Arity == 1? "ng" : "mi"); break;
26160b57cec5SDimitry Andric   //              ::= ad        # & (unary)
26170b57cec5SDimitry Andric   //              ::= an        # & (binary or unknown)
26180b57cec5SDimitry Andric   case OO_Amp:
26190b57cec5SDimitry Andric     Out << (Arity == 1? "ad" : "an"); break;
26200b57cec5SDimitry Andric   //              ::= de        # * (unary)
26210b57cec5SDimitry Andric   //              ::= ml        # * (binary or unknown)
26220b57cec5SDimitry Andric   case OO_Star:
26230b57cec5SDimitry Andric     // Use binary when unknown.
26240b57cec5SDimitry Andric     Out << (Arity == 1? "de" : "ml"); break;
26250b57cec5SDimitry Andric   //              ::= co        # ~
26260b57cec5SDimitry Andric   case OO_Tilde: Out << "co"; break;
26270b57cec5SDimitry Andric   //              ::= dv        # /
26280b57cec5SDimitry Andric   case OO_Slash: Out << "dv"; break;
26290b57cec5SDimitry Andric   //              ::= rm        # %
26300b57cec5SDimitry Andric   case OO_Percent: Out << "rm"; break;
26310b57cec5SDimitry Andric   //              ::= or        # |
26320b57cec5SDimitry Andric   case OO_Pipe: Out << "or"; break;
26330b57cec5SDimitry Andric   //              ::= eo        # ^
26340b57cec5SDimitry Andric   case OO_Caret: Out << "eo"; break;
26350b57cec5SDimitry Andric   //              ::= aS        # =
26360b57cec5SDimitry Andric   case OO_Equal: Out << "aS"; break;
26370b57cec5SDimitry Andric   //              ::= pL        # +=
26380b57cec5SDimitry Andric   case OO_PlusEqual: Out << "pL"; break;
26390b57cec5SDimitry Andric   //              ::= mI        # -=
26400b57cec5SDimitry Andric   case OO_MinusEqual: Out << "mI"; break;
26410b57cec5SDimitry Andric   //              ::= mL        # *=
26420b57cec5SDimitry Andric   case OO_StarEqual: Out << "mL"; break;
26430b57cec5SDimitry Andric   //              ::= dV        # /=
26440b57cec5SDimitry Andric   case OO_SlashEqual: Out << "dV"; break;
26450b57cec5SDimitry Andric   //              ::= rM        # %=
26460b57cec5SDimitry Andric   case OO_PercentEqual: Out << "rM"; break;
26470b57cec5SDimitry Andric   //              ::= aN        # &=
26480b57cec5SDimitry Andric   case OO_AmpEqual: Out << "aN"; break;
26490b57cec5SDimitry Andric   //              ::= oR        # |=
26500b57cec5SDimitry Andric   case OO_PipeEqual: Out << "oR"; break;
26510b57cec5SDimitry Andric   //              ::= eO        # ^=
26520b57cec5SDimitry Andric   case OO_CaretEqual: Out << "eO"; break;
26530b57cec5SDimitry Andric   //              ::= ls        # <<
26540b57cec5SDimitry Andric   case OO_LessLess: Out << "ls"; break;
26550b57cec5SDimitry Andric   //              ::= rs        # >>
26560b57cec5SDimitry Andric   case OO_GreaterGreater: Out << "rs"; break;
26570b57cec5SDimitry Andric   //              ::= lS        # <<=
26580b57cec5SDimitry Andric   case OO_LessLessEqual: Out << "lS"; break;
26590b57cec5SDimitry Andric   //              ::= rS        # >>=
26600b57cec5SDimitry Andric   case OO_GreaterGreaterEqual: Out << "rS"; break;
26610b57cec5SDimitry Andric   //              ::= eq        # ==
26620b57cec5SDimitry Andric   case OO_EqualEqual: Out << "eq"; break;
26630b57cec5SDimitry Andric   //              ::= ne        # !=
26640b57cec5SDimitry Andric   case OO_ExclaimEqual: Out << "ne"; break;
26650b57cec5SDimitry Andric   //              ::= lt        # <
26660b57cec5SDimitry Andric   case OO_Less: Out << "lt"; break;
26670b57cec5SDimitry Andric   //              ::= gt        # >
26680b57cec5SDimitry Andric   case OO_Greater: Out << "gt"; break;
26690b57cec5SDimitry Andric   //              ::= le        # <=
26700b57cec5SDimitry Andric   case OO_LessEqual: Out << "le"; break;
26710b57cec5SDimitry Andric   //              ::= ge        # >=
26720b57cec5SDimitry Andric   case OO_GreaterEqual: Out << "ge"; break;
26730b57cec5SDimitry Andric   //              ::= nt        # !
26740b57cec5SDimitry Andric   case OO_Exclaim: Out << "nt"; break;
26750b57cec5SDimitry Andric   //              ::= aa        # &&
26760b57cec5SDimitry Andric   case OO_AmpAmp: Out << "aa"; break;
26770b57cec5SDimitry Andric   //              ::= oo        # ||
26780b57cec5SDimitry Andric   case OO_PipePipe: Out << "oo"; break;
26790b57cec5SDimitry Andric   //              ::= pp        # ++
26800b57cec5SDimitry Andric   case OO_PlusPlus: Out << "pp"; break;
26810b57cec5SDimitry Andric   //              ::= mm        # --
26820b57cec5SDimitry Andric   case OO_MinusMinus: Out << "mm"; break;
26830b57cec5SDimitry Andric   //              ::= cm        # ,
26840b57cec5SDimitry Andric   case OO_Comma: Out << "cm"; break;
26850b57cec5SDimitry Andric   //              ::= pm        # ->*
26860b57cec5SDimitry Andric   case OO_ArrowStar: Out << "pm"; break;
26870b57cec5SDimitry Andric   //              ::= pt        # ->
26880b57cec5SDimitry Andric   case OO_Arrow: Out << "pt"; break;
26890b57cec5SDimitry Andric   //              ::= cl        # ()
26900b57cec5SDimitry Andric   case OO_Call: Out << "cl"; break;
26910b57cec5SDimitry Andric   //              ::= ix        # []
26920b57cec5SDimitry Andric   case OO_Subscript: Out << "ix"; break;
26930b57cec5SDimitry Andric 
26940b57cec5SDimitry Andric   //              ::= qu        # ?
26950b57cec5SDimitry Andric   // The conditional operator can't be overloaded, but we still handle it when
26960b57cec5SDimitry Andric   // mangling expressions.
26970b57cec5SDimitry Andric   case OO_Conditional: Out << "qu"; break;
26980b57cec5SDimitry Andric   // Proposal on cxx-abi-dev, 2015-10-21.
26990b57cec5SDimitry Andric   //              ::= aw        # co_await
27000b57cec5SDimitry Andric   case OO_Coawait: Out << "aw"; break;
27010b57cec5SDimitry Andric   // Proposed in cxx-abi github issue 43.
27020b57cec5SDimitry Andric   //              ::= ss        # <=>
27030b57cec5SDimitry Andric   case OO_Spaceship: Out << "ss"; break;
27040b57cec5SDimitry Andric 
27050b57cec5SDimitry Andric   case OO_None:
27060b57cec5SDimitry Andric   case NUM_OVERLOADED_OPERATORS:
27070b57cec5SDimitry Andric     llvm_unreachable("Not an overloaded operator");
27080b57cec5SDimitry Andric   }
27090b57cec5SDimitry Andric }
27100b57cec5SDimitry Andric 
mangleQualifiers(Qualifiers Quals,const DependentAddressSpaceType * DAST)27110b57cec5SDimitry Andric void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
27120b57cec5SDimitry Andric   // Vendor qualifiers come first and if they are order-insensitive they must
27130b57cec5SDimitry Andric   // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric   // <type> ::= U <addrspace-expr>
27160b57cec5SDimitry Andric   if (DAST) {
27170b57cec5SDimitry Andric     Out << "U2ASI";
27180b57cec5SDimitry Andric     mangleExpression(DAST->getAddrSpaceExpr());
27190b57cec5SDimitry Andric     Out << "E";
27200b57cec5SDimitry Andric   }
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric   // Address space qualifiers start with an ordinary letter.
27230b57cec5SDimitry Andric   if (Quals.hasAddressSpace()) {
27240b57cec5SDimitry Andric     // Address space extension:
27250b57cec5SDimitry Andric     //
27260b57cec5SDimitry Andric     //   <type> ::= U <target-addrspace>
27270b57cec5SDimitry Andric     //   <type> ::= U <OpenCL-addrspace>
27280b57cec5SDimitry Andric     //   <type> ::= U <CUDA-addrspace>
27290b57cec5SDimitry Andric 
27300b57cec5SDimitry Andric     SmallString<64> ASString;
27310b57cec5SDimitry Andric     LangAS AS = Quals.getAddressSpace();
27320b57cec5SDimitry Andric 
27330b57cec5SDimitry Andric     if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
27340b57cec5SDimitry Andric       //  <target-addrspace> ::= "AS" <address-space-number>
27350b57cec5SDimitry Andric       unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2736fe6060f1SDimitry Andric       if (TargetAS != 0 ||
2737fe6060f1SDimitry Andric           Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
27380b57cec5SDimitry Andric         ASString = "AS" + llvm::utostr(TargetAS);
27390b57cec5SDimitry Andric     } else {
27400b57cec5SDimitry Andric       switch (AS) {
27410b57cec5SDimitry Andric       default: llvm_unreachable("Not a language specific address space");
27420b57cec5SDimitry Andric       //  <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2743e8d8bef9SDimitry Andric       //                                "private"| "generic" | "device" |
2744e8d8bef9SDimitry Andric       //                                "host" ]
2745e8d8bef9SDimitry Andric       case LangAS::opencl_global:
2746e8d8bef9SDimitry Andric         ASString = "CLglobal";
2747e8d8bef9SDimitry Andric         break;
2748e8d8bef9SDimitry Andric       case LangAS::opencl_global_device:
2749e8d8bef9SDimitry Andric         ASString = "CLdevice";
2750e8d8bef9SDimitry Andric         break;
2751e8d8bef9SDimitry Andric       case LangAS::opencl_global_host:
2752e8d8bef9SDimitry Andric         ASString = "CLhost";
2753e8d8bef9SDimitry Andric         break;
2754e8d8bef9SDimitry Andric       case LangAS::opencl_local:
2755e8d8bef9SDimitry Andric         ASString = "CLlocal";
2756e8d8bef9SDimitry Andric         break;
2757e8d8bef9SDimitry Andric       case LangAS::opencl_constant:
2758e8d8bef9SDimitry Andric         ASString = "CLconstant";
2759e8d8bef9SDimitry Andric         break;
2760e8d8bef9SDimitry Andric       case LangAS::opencl_private:
2761e8d8bef9SDimitry Andric         ASString = "CLprivate";
2762e8d8bef9SDimitry Andric         break;
2763e8d8bef9SDimitry Andric       case LangAS::opencl_generic:
2764e8d8bef9SDimitry Andric         ASString = "CLgeneric";
2765e8d8bef9SDimitry Andric         break;
2766fe6060f1SDimitry Andric       //  <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2767fe6060f1SDimitry Andric       //                              "device" | "host" ]
2768fe6060f1SDimitry Andric       case LangAS::sycl_global:
2769fe6060f1SDimitry Andric         ASString = "SYglobal";
2770fe6060f1SDimitry Andric         break;
2771fe6060f1SDimitry Andric       case LangAS::sycl_global_device:
2772fe6060f1SDimitry Andric         ASString = "SYdevice";
2773fe6060f1SDimitry Andric         break;
2774fe6060f1SDimitry Andric       case LangAS::sycl_global_host:
2775fe6060f1SDimitry Andric         ASString = "SYhost";
2776fe6060f1SDimitry Andric         break;
2777fe6060f1SDimitry Andric       case LangAS::sycl_local:
2778fe6060f1SDimitry Andric         ASString = "SYlocal";
2779fe6060f1SDimitry Andric         break;
2780fe6060f1SDimitry Andric       case LangAS::sycl_private:
2781fe6060f1SDimitry Andric         ASString = "SYprivate";
2782fe6060f1SDimitry Andric         break;
27830b57cec5SDimitry Andric       //  <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2784e8d8bef9SDimitry Andric       case LangAS::cuda_device:
2785e8d8bef9SDimitry Andric         ASString = "CUdevice";
2786e8d8bef9SDimitry Andric         break;
2787e8d8bef9SDimitry Andric       case LangAS::cuda_constant:
2788e8d8bef9SDimitry Andric         ASString = "CUconstant";
2789e8d8bef9SDimitry Andric         break;
2790e8d8bef9SDimitry Andric       case LangAS::cuda_shared:
2791e8d8bef9SDimitry Andric         ASString = "CUshared";
2792e8d8bef9SDimitry Andric         break;
2793480093f4SDimitry Andric       //  <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2794480093f4SDimitry Andric       case LangAS::ptr32_sptr:
2795480093f4SDimitry Andric         ASString = "ptr32_sptr";
2796480093f4SDimitry Andric         break;
2797480093f4SDimitry Andric       case LangAS::ptr32_uptr:
2798480093f4SDimitry Andric         ASString = "ptr32_uptr";
2799480093f4SDimitry Andric         break;
2800480093f4SDimitry Andric       case LangAS::ptr64:
2801480093f4SDimitry Andric         ASString = "ptr64";
2802480093f4SDimitry Andric         break;
28030b57cec5SDimitry Andric       }
28040b57cec5SDimitry Andric     }
28050b57cec5SDimitry Andric     if (!ASString.empty())
28060b57cec5SDimitry Andric       mangleVendorQualifier(ASString);
28070b57cec5SDimitry Andric   }
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric   // The ARC ownership qualifiers start with underscores.
28100b57cec5SDimitry Andric   // Objective-C ARC Extension:
28110b57cec5SDimitry Andric   //
28120b57cec5SDimitry Andric   //   <type> ::= U "__strong"
28130b57cec5SDimitry Andric   //   <type> ::= U "__weak"
28140b57cec5SDimitry Andric   //   <type> ::= U "__autoreleasing"
28150b57cec5SDimitry Andric   //
28160b57cec5SDimitry Andric   // Note: we emit __weak first to preserve the order as
28170b57cec5SDimitry Andric   // required by the Itanium ABI.
28180b57cec5SDimitry Andric   if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
28190b57cec5SDimitry Andric     mangleVendorQualifier("__weak");
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric   // __unaligned (from -fms-extensions)
28220b57cec5SDimitry Andric   if (Quals.hasUnaligned())
28230b57cec5SDimitry Andric     mangleVendorQualifier("__unaligned");
28240b57cec5SDimitry Andric 
28250b57cec5SDimitry Andric   // Remaining ARC ownership qualifiers.
28260b57cec5SDimitry Andric   switch (Quals.getObjCLifetime()) {
28270b57cec5SDimitry Andric   case Qualifiers::OCL_None:
28280b57cec5SDimitry Andric     break;
28290b57cec5SDimitry Andric 
28300b57cec5SDimitry Andric   case Qualifiers::OCL_Weak:
28310b57cec5SDimitry Andric     // Do nothing as we already handled this case above.
28320b57cec5SDimitry Andric     break;
28330b57cec5SDimitry Andric 
28340b57cec5SDimitry Andric   case Qualifiers::OCL_Strong:
28350b57cec5SDimitry Andric     mangleVendorQualifier("__strong");
28360b57cec5SDimitry Andric     break;
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric   case Qualifiers::OCL_Autoreleasing:
28390b57cec5SDimitry Andric     mangleVendorQualifier("__autoreleasing");
28400b57cec5SDimitry Andric     break;
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric   case Qualifiers::OCL_ExplicitNone:
28430b57cec5SDimitry Andric     // The __unsafe_unretained qualifier is *not* mangled, so that
28440b57cec5SDimitry Andric     // __unsafe_unretained types in ARC produce the same manglings as the
28450b57cec5SDimitry Andric     // equivalent (but, naturally, unqualified) types in non-ARC, providing
28460b57cec5SDimitry Andric     // better ABI compatibility.
28470b57cec5SDimitry Andric     //
28480b57cec5SDimitry Andric     // It's safe to do this because unqualified 'id' won't show up
28490b57cec5SDimitry Andric     // in any type signatures that need to be mangled.
28500b57cec5SDimitry Andric     break;
28510b57cec5SDimitry Andric   }
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric   // <CV-qualifiers> ::= [r] [V] [K]    # restrict (C99), volatile, const
28540b57cec5SDimitry Andric   if (Quals.hasRestrict())
28550b57cec5SDimitry Andric     Out << 'r';
28560b57cec5SDimitry Andric   if (Quals.hasVolatile())
28570b57cec5SDimitry Andric     Out << 'V';
28580b57cec5SDimitry Andric   if (Quals.hasConst())
28590b57cec5SDimitry Andric     Out << 'K';
28600b57cec5SDimitry Andric }
28610b57cec5SDimitry Andric 
mangleVendorQualifier(StringRef name)28620b57cec5SDimitry Andric void CXXNameMangler::mangleVendorQualifier(StringRef name) {
28630b57cec5SDimitry Andric   Out << 'U' << name.size() << name;
28640b57cec5SDimitry Andric }
28650b57cec5SDimitry Andric 
mangleRefQualifier(RefQualifierKind RefQualifier)28660b57cec5SDimitry Andric void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
28670b57cec5SDimitry Andric   // <ref-qualifier> ::= R                # lvalue reference
28680b57cec5SDimitry Andric   //                 ::= O                # rvalue-reference
28690b57cec5SDimitry Andric   switch (RefQualifier) {
28700b57cec5SDimitry Andric   case RQ_None:
28710b57cec5SDimitry Andric     break;
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric   case RQ_LValue:
28740b57cec5SDimitry Andric     Out << 'R';
28750b57cec5SDimitry Andric     break;
28760b57cec5SDimitry Andric 
28770b57cec5SDimitry Andric   case RQ_RValue:
28780b57cec5SDimitry Andric     Out << 'O';
28790b57cec5SDimitry Andric     break;
28800b57cec5SDimitry Andric   }
28810b57cec5SDimitry Andric }
28820b57cec5SDimitry Andric 
mangleObjCMethodName(const ObjCMethodDecl * MD)28830b57cec5SDimitry Andric void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2884e8d8bef9SDimitry Andric   Context.mangleObjCMethodNameAsSourceName(MD, Out);
28850b57cec5SDimitry Andric }
28860b57cec5SDimitry Andric 
isTypeSubstitutable(Qualifiers Quals,const Type * Ty,ASTContext & Ctx)28870b57cec5SDimitry Andric static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
28880b57cec5SDimitry Andric                                 ASTContext &Ctx) {
28890b57cec5SDimitry Andric   if (Quals)
28900b57cec5SDimitry Andric     return true;
28910b57cec5SDimitry Andric   if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
28920b57cec5SDimitry Andric     return true;
28930b57cec5SDimitry Andric   if (Ty->isOpenCLSpecificType())
28940b57cec5SDimitry Andric     return true;
28955f757f3fSDimitry Andric   // From Clang 18.0 we correctly treat SVE types as substitution candidates.
28965f757f3fSDimitry Andric   if (Ty->isSVESizelessBuiltinType() &&
28975f757f3fSDimitry Andric       Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)
28985f757f3fSDimitry Andric     return true;
28990b57cec5SDimitry Andric   if (Ty->isBuiltinType())
29000b57cec5SDimitry Andric     return false;
29010b57cec5SDimitry Andric   // Through to Clang 6.0, we accidentally treated undeduced auto types as
29020b57cec5SDimitry Andric   // substitution candidates.
29030b57cec5SDimitry Andric   if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
29040b57cec5SDimitry Andric       isa<AutoType>(Ty))
29050b57cec5SDimitry Andric     return false;
2906e8d8bef9SDimitry Andric   // A placeholder type for class template deduction is substitutable with
2907e8d8bef9SDimitry Andric   // its corresponding template name; this is handled specially when mangling
2908e8d8bef9SDimitry Andric   // the type.
2909e8d8bef9SDimitry Andric   if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2910e8d8bef9SDimitry Andric     if (DeducedTST->getDeducedType().isNull())
2911e8d8bef9SDimitry Andric       return false;
29120b57cec5SDimitry Andric   return true;
29130b57cec5SDimitry Andric }
29140b57cec5SDimitry Andric 
mangleType(QualType T)29150b57cec5SDimitry Andric void CXXNameMangler::mangleType(QualType T) {
29160b57cec5SDimitry Andric   // If our type is instantiation-dependent but not dependent, we mangle
29170b57cec5SDimitry Andric   // it as it was written in the source, removing any top-level sugar.
29180b57cec5SDimitry Andric   // Otherwise, use the canonical type.
29190b57cec5SDimitry Andric   //
29200b57cec5SDimitry Andric   // FIXME: This is an approximation of the instantiation-dependent name
29210b57cec5SDimitry Andric   // mangling rules, since we should really be using the type as written and
29220b57cec5SDimitry Andric   // augmented via semantic analysis (i.e., with implicit conversions and
29230b57cec5SDimitry Andric   // default template arguments) for any instantiation-dependent type.
29240b57cec5SDimitry Andric   // Unfortunately, that requires several changes to our AST:
29250b57cec5SDimitry Andric   //   - Instantiation-dependent TemplateSpecializationTypes will need to be
29260b57cec5SDimitry Andric   //     uniqued, so that we can handle substitutions properly
29270b57cec5SDimitry Andric   //   - Default template arguments will need to be represented in the
29280b57cec5SDimitry Andric   //     TemplateSpecializationType, since they need to be mangled even though
29290b57cec5SDimitry Andric   //     they aren't written.
29300b57cec5SDimitry Andric   //   - Conversions on non-type template arguments need to be expressed, since
29310b57cec5SDimitry Andric   //     they can affect the mangling of sizeof/alignof.
29320b57cec5SDimitry Andric   //
29330b57cec5SDimitry Andric   // FIXME: This is wrong when mapping to the canonical type for a dependent
29340b57cec5SDimitry Andric   // type discards instantiation-dependent portions of the type, such as for:
29350b57cec5SDimitry Andric   //
29360b57cec5SDimitry Andric   //   template<typename T, int N> void f(T (&)[sizeof(N)]);
29370b57cec5SDimitry Andric   //   template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
29380b57cec5SDimitry Andric   //
29390b57cec5SDimitry Andric   // It's also wrong in the opposite direction when instantiation-dependent,
29400b57cec5SDimitry Andric   // canonically-equivalent types differ in some irrelevant portion of inner
29410b57cec5SDimitry Andric   // type sugar. In such cases, we fail to form correct substitutions, eg:
29420b57cec5SDimitry Andric   //
29430b57cec5SDimitry Andric   //   template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
29440b57cec5SDimitry Andric   //
29450b57cec5SDimitry Andric   // We should instead canonicalize the non-instantiation-dependent parts,
29460b57cec5SDimitry Andric   // regardless of whether the type as a whole is dependent or instantiation
29470b57cec5SDimitry Andric   // dependent.
29480b57cec5SDimitry Andric   if (!T->isInstantiationDependentType() || T->isDependentType())
29490b57cec5SDimitry Andric     T = T.getCanonicalType();
29500b57cec5SDimitry Andric   else {
29510b57cec5SDimitry Andric     // Desugar any types that are purely sugar.
29520b57cec5SDimitry Andric     do {
29530b57cec5SDimitry Andric       // Don't desugar through template specialization types that aren't
29540b57cec5SDimitry Andric       // type aliases. We need to mangle the template arguments as written.
29550b57cec5SDimitry Andric       if (const TemplateSpecializationType *TST
29560b57cec5SDimitry Andric                                       = dyn_cast<TemplateSpecializationType>(T))
29570b57cec5SDimitry Andric         if (!TST->isTypeAlias())
29580b57cec5SDimitry Andric           break;
29590b57cec5SDimitry Andric 
2960e8d8bef9SDimitry Andric       // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2961e8d8bef9SDimitry Andric       // instantation-dependent qualifiers. See
2962e8d8bef9SDimitry Andric       // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2963e8d8bef9SDimitry Andric 
29640b57cec5SDimitry Andric       QualType Desugared
29650b57cec5SDimitry Andric         = T.getSingleStepDesugaredType(Context.getASTContext());
29660b57cec5SDimitry Andric       if (Desugared == T)
29670b57cec5SDimitry Andric         break;
29680b57cec5SDimitry Andric 
29690b57cec5SDimitry Andric       T = Desugared;
29700b57cec5SDimitry Andric     } while (true);
29710b57cec5SDimitry Andric   }
29720b57cec5SDimitry Andric   SplitQualType split = T.split();
29730b57cec5SDimitry Andric   Qualifiers quals = split.Quals;
29740b57cec5SDimitry Andric   const Type *ty = split.Ty;
29750b57cec5SDimitry Andric 
29760b57cec5SDimitry Andric   bool isSubstitutable =
29770b57cec5SDimitry Andric     isTypeSubstitutable(quals, ty, Context.getASTContext());
29780b57cec5SDimitry Andric   if (isSubstitutable && mangleSubstitution(T))
29790b57cec5SDimitry Andric     return;
29800b57cec5SDimitry Andric 
29810b57cec5SDimitry Andric   // If we're mangling a qualified array type, push the qualifiers to
29820b57cec5SDimitry Andric   // the element type.
29830b57cec5SDimitry Andric   if (quals && isa<ArrayType>(T)) {
29840b57cec5SDimitry Andric     ty = Context.getASTContext().getAsArrayType(T);
29850b57cec5SDimitry Andric     quals = Qualifiers();
29860b57cec5SDimitry Andric 
29870b57cec5SDimitry Andric     // Note that we don't update T: we want to add the
29880b57cec5SDimitry Andric     // substitution at the original type.
29890b57cec5SDimitry Andric   }
29900b57cec5SDimitry Andric 
29910b57cec5SDimitry Andric   if (quals || ty->isDependentAddressSpaceType()) {
29920b57cec5SDimitry Andric     if (const DependentAddressSpaceType *DAST =
29930b57cec5SDimitry Andric         dyn_cast<DependentAddressSpaceType>(ty)) {
29940b57cec5SDimitry Andric       SplitQualType splitDAST = DAST->getPointeeType().split();
29950b57cec5SDimitry Andric       mangleQualifiers(splitDAST.Quals, DAST);
29960b57cec5SDimitry Andric       mangleType(QualType(splitDAST.Ty, 0));
29970b57cec5SDimitry Andric     } else {
29980b57cec5SDimitry Andric       mangleQualifiers(quals);
29990b57cec5SDimitry Andric 
30000b57cec5SDimitry Andric       // Recurse:  even if the qualified type isn't yet substitutable,
30010b57cec5SDimitry Andric       // the unqualified type might be.
30020b57cec5SDimitry Andric       mangleType(QualType(ty, 0));
30030b57cec5SDimitry Andric     }
30040b57cec5SDimitry Andric   } else {
30050b57cec5SDimitry Andric     switch (ty->getTypeClass()) {
30060b57cec5SDimitry Andric #define ABSTRACT_TYPE(CLASS, PARENT)
30070b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(CLASS, PARENT) \
30080b57cec5SDimitry Andric     case Type::CLASS: \
30090b57cec5SDimitry Andric       llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
30100b57cec5SDimitry Andric       return;
30110b57cec5SDimitry Andric #define TYPE(CLASS, PARENT) \
30120b57cec5SDimitry Andric     case Type::CLASS: \
30130b57cec5SDimitry Andric       mangleType(static_cast<const CLASS##Type*>(ty)); \
30140b57cec5SDimitry Andric       break;
3015a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
30160b57cec5SDimitry Andric     }
30170b57cec5SDimitry Andric   }
30180b57cec5SDimitry Andric 
30190b57cec5SDimitry Andric   // Add the substitution.
30200b57cec5SDimitry Andric   if (isSubstitutable)
30210b57cec5SDimitry Andric     addSubstitution(T);
30220b57cec5SDimitry Andric }
30230b57cec5SDimitry Andric 
mangleNameOrStandardSubstitution(const NamedDecl * ND)30240b57cec5SDimitry Andric void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
30250b57cec5SDimitry Andric   if (!mangleStandardSubstitution(ND))
30260b57cec5SDimitry Andric     mangleName(ND);
30270b57cec5SDimitry Andric }
30280b57cec5SDimitry Andric 
mangleType(const BuiltinType * T)30290b57cec5SDimitry Andric void CXXNameMangler::mangleType(const BuiltinType *T) {
30300b57cec5SDimitry Andric   //  <type>         ::= <builtin-type>
30310b57cec5SDimitry Andric   //  <builtin-type> ::= v  # void
30320b57cec5SDimitry Andric   //                 ::= w  # wchar_t
30330b57cec5SDimitry Andric   //                 ::= b  # bool
30340b57cec5SDimitry Andric   //                 ::= c  # char
30350b57cec5SDimitry Andric   //                 ::= a  # signed char
30360b57cec5SDimitry Andric   //                 ::= h  # unsigned char
30370b57cec5SDimitry Andric   //                 ::= s  # short
30380b57cec5SDimitry Andric   //                 ::= t  # unsigned short
30390b57cec5SDimitry Andric   //                 ::= i  # int
30400b57cec5SDimitry Andric   //                 ::= j  # unsigned int
30410b57cec5SDimitry Andric   //                 ::= l  # long
30420b57cec5SDimitry Andric   //                 ::= m  # unsigned long
30430b57cec5SDimitry Andric   //                 ::= x  # long long, __int64
30440b57cec5SDimitry Andric   //                 ::= y  # unsigned long long, __int64
30450b57cec5SDimitry Andric   //                 ::= n  # __int128
30460b57cec5SDimitry Andric   //                 ::= o  # unsigned __int128
30470b57cec5SDimitry Andric   //                 ::= f  # float
30480b57cec5SDimitry Andric   //                 ::= d  # double
30490b57cec5SDimitry Andric   //                 ::= e  # long double, __float80
30500b57cec5SDimitry Andric   //                 ::= g  # __float128
3051349cc55cSDimitry Andric   //                 ::= g  # __ibm128
30520b57cec5SDimitry Andric   // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)
30530b57cec5SDimitry Andric   // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)
30540b57cec5SDimitry Andric   // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)
30550b57cec5SDimitry Andric   //                 ::= Dh # IEEE 754r half-precision floating point (16 bits)
30560b57cec5SDimitry Andric   //                 ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
30570b57cec5SDimitry Andric   //                 ::= Di # char32_t
30580b57cec5SDimitry Andric   //                 ::= Ds # char16_t
30590b57cec5SDimitry Andric   //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
30605f757f3fSDimitry Andric   //                 ::= [DS] DA  # N1169 fixed-point [_Sat] T _Accum
30615f757f3fSDimitry Andric   //                 ::= [DS] DR  # N1169 fixed-point [_Sat] T _Fract
30620b57cec5SDimitry Andric   //                 ::= u <source-name>    # vendor extended type
30635f757f3fSDimitry Andric   //
30645f757f3fSDimitry Andric   //  <fixed-point-size>
30655f757f3fSDimitry Andric   //                 ::= s # short
30665f757f3fSDimitry Andric   //                 ::= t # unsigned short
30675f757f3fSDimitry Andric   //                 ::= i # plain
30685f757f3fSDimitry Andric   //                 ::= j # unsigned
30695f757f3fSDimitry Andric   //                 ::= l # long
30705f757f3fSDimitry Andric   //                 ::= m # unsigned long
30710b57cec5SDimitry Andric   std::string type_name;
307206c3fb27SDimitry Andric   // Normalize integer types as vendor extended types:
307306c3fb27SDimitry Andric   // u<length>i<type size>
307406c3fb27SDimitry Andric   // u<length>u<type size>
307506c3fb27SDimitry Andric   if (NormalizeIntegers && T->isInteger()) {
307606c3fb27SDimitry Andric     if (T->isSignedInteger()) {
307706c3fb27SDimitry Andric       switch (getASTContext().getTypeSize(T)) {
307806c3fb27SDimitry Andric       case 8:
307906c3fb27SDimitry Andric         // Pick a representative for each integer size in the substitution
308006c3fb27SDimitry Andric         // dictionary. (Its actual defined size is not relevant.)
308106c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::SChar))
308206c3fb27SDimitry Andric           break;
308306c3fb27SDimitry Andric         Out << "u2i8";
308406c3fb27SDimitry Andric         addSubstitution(BuiltinType::SChar);
308506c3fb27SDimitry Andric         break;
308606c3fb27SDimitry Andric       case 16:
308706c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::Short))
308806c3fb27SDimitry Andric           break;
308906c3fb27SDimitry Andric         Out << "u3i16";
309006c3fb27SDimitry Andric         addSubstitution(BuiltinType::Short);
309106c3fb27SDimitry Andric         break;
309206c3fb27SDimitry Andric       case 32:
309306c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::Int))
309406c3fb27SDimitry Andric           break;
309506c3fb27SDimitry Andric         Out << "u3i32";
309606c3fb27SDimitry Andric         addSubstitution(BuiltinType::Int);
309706c3fb27SDimitry Andric         break;
309806c3fb27SDimitry Andric       case 64:
309906c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::Long))
310006c3fb27SDimitry Andric           break;
310106c3fb27SDimitry Andric         Out << "u3i64";
310206c3fb27SDimitry Andric         addSubstitution(BuiltinType::Long);
310306c3fb27SDimitry Andric         break;
310406c3fb27SDimitry Andric       case 128:
310506c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::Int128))
310606c3fb27SDimitry Andric           break;
310706c3fb27SDimitry Andric         Out << "u4i128";
310806c3fb27SDimitry Andric         addSubstitution(BuiltinType::Int128);
310906c3fb27SDimitry Andric         break;
311006c3fb27SDimitry Andric       default:
311106c3fb27SDimitry Andric         llvm_unreachable("Unknown integer size for normalization");
311206c3fb27SDimitry Andric       }
311306c3fb27SDimitry Andric     } else {
311406c3fb27SDimitry Andric       switch (getASTContext().getTypeSize(T)) {
311506c3fb27SDimitry Andric       case 8:
311606c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::UChar))
311706c3fb27SDimitry Andric           break;
311806c3fb27SDimitry Andric         Out << "u2u8";
311906c3fb27SDimitry Andric         addSubstitution(BuiltinType::UChar);
312006c3fb27SDimitry Andric         break;
312106c3fb27SDimitry Andric       case 16:
312206c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::UShort))
312306c3fb27SDimitry Andric           break;
312406c3fb27SDimitry Andric         Out << "u3u16";
312506c3fb27SDimitry Andric         addSubstitution(BuiltinType::UShort);
312606c3fb27SDimitry Andric         break;
312706c3fb27SDimitry Andric       case 32:
312806c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::UInt))
312906c3fb27SDimitry Andric           break;
313006c3fb27SDimitry Andric         Out << "u3u32";
313106c3fb27SDimitry Andric         addSubstitution(BuiltinType::UInt);
313206c3fb27SDimitry Andric         break;
313306c3fb27SDimitry Andric       case 64:
313406c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::ULong))
313506c3fb27SDimitry Andric           break;
313606c3fb27SDimitry Andric         Out << "u3u64";
313706c3fb27SDimitry Andric         addSubstitution(BuiltinType::ULong);
313806c3fb27SDimitry Andric         break;
313906c3fb27SDimitry Andric       case 128:
314006c3fb27SDimitry Andric         if (mangleSubstitution(BuiltinType::UInt128))
314106c3fb27SDimitry Andric           break;
314206c3fb27SDimitry Andric         Out << "u4u128";
314306c3fb27SDimitry Andric         addSubstitution(BuiltinType::UInt128);
314406c3fb27SDimitry Andric         break;
314506c3fb27SDimitry Andric       default:
314606c3fb27SDimitry Andric         llvm_unreachable("Unknown integer size for normalization");
314706c3fb27SDimitry Andric       }
314806c3fb27SDimitry Andric     }
314906c3fb27SDimitry Andric     return;
315006c3fb27SDimitry Andric   }
31510b57cec5SDimitry Andric   switch (T->getKind()) {
31520b57cec5SDimitry Andric   case BuiltinType::Void:
31530b57cec5SDimitry Andric     Out << 'v';
31540b57cec5SDimitry Andric     break;
31550b57cec5SDimitry Andric   case BuiltinType::Bool:
31560b57cec5SDimitry Andric     Out << 'b';
31570b57cec5SDimitry Andric     break;
31580b57cec5SDimitry Andric   case BuiltinType::Char_U:
31590b57cec5SDimitry Andric   case BuiltinType::Char_S:
31600b57cec5SDimitry Andric     Out << 'c';
31610b57cec5SDimitry Andric     break;
31620b57cec5SDimitry Andric   case BuiltinType::UChar:
31630b57cec5SDimitry Andric     Out << 'h';
31640b57cec5SDimitry Andric     break;
31650b57cec5SDimitry Andric   case BuiltinType::UShort:
31660b57cec5SDimitry Andric     Out << 't';
31670b57cec5SDimitry Andric     break;
31680b57cec5SDimitry Andric   case BuiltinType::UInt:
31690b57cec5SDimitry Andric     Out << 'j';
31700b57cec5SDimitry Andric     break;
31710b57cec5SDimitry Andric   case BuiltinType::ULong:
31720b57cec5SDimitry Andric     Out << 'm';
31730b57cec5SDimitry Andric     break;
31740b57cec5SDimitry Andric   case BuiltinType::ULongLong:
31750b57cec5SDimitry Andric     Out << 'y';
31760b57cec5SDimitry Andric     break;
31770b57cec5SDimitry Andric   case BuiltinType::UInt128:
31780b57cec5SDimitry Andric     Out << 'o';
31790b57cec5SDimitry Andric     break;
31800b57cec5SDimitry Andric   case BuiltinType::SChar:
31810b57cec5SDimitry Andric     Out << 'a';
31820b57cec5SDimitry Andric     break;
31830b57cec5SDimitry Andric   case BuiltinType::WChar_S:
31840b57cec5SDimitry Andric   case BuiltinType::WChar_U:
31850b57cec5SDimitry Andric     Out << 'w';
31860b57cec5SDimitry Andric     break;
31870b57cec5SDimitry Andric   case BuiltinType::Char8:
31880b57cec5SDimitry Andric     Out << "Du";
31890b57cec5SDimitry Andric     break;
31900b57cec5SDimitry Andric   case BuiltinType::Char16:
31910b57cec5SDimitry Andric     Out << "Ds";
31920b57cec5SDimitry Andric     break;
31930b57cec5SDimitry Andric   case BuiltinType::Char32:
31940b57cec5SDimitry Andric     Out << "Di";
31950b57cec5SDimitry Andric     break;
31960b57cec5SDimitry Andric   case BuiltinType::Short:
31970b57cec5SDimitry Andric     Out << 's';
31980b57cec5SDimitry Andric     break;
31990b57cec5SDimitry Andric   case BuiltinType::Int:
32000b57cec5SDimitry Andric     Out << 'i';
32010b57cec5SDimitry Andric     break;
32020b57cec5SDimitry Andric   case BuiltinType::Long:
32030b57cec5SDimitry Andric     Out << 'l';
32040b57cec5SDimitry Andric     break;
32050b57cec5SDimitry Andric   case BuiltinType::LongLong:
32060b57cec5SDimitry Andric     Out << 'x';
32070b57cec5SDimitry Andric     break;
32080b57cec5SDimitry Andric   case BuiltinType::Int128:
32090b57cec5SDimitry Andric     Out << 'n';
32100b57cec5SDimitry Andric     break;
32110b57cec5SDimitry Andric   case BuiltinType::Float16:
32120b57cec5SDimitry Andric     Out << "DF16_";
32130b57cec5SDimitry Andric     break;
32140b57cec5SDimitry Andric   case BuiltinType::ShortAccum:
32155f757f3fSDimitry Andric     Out << "DAs";
32165f757f3fSDimitry Andric     break;
32170b57cec5SDimitry Andric   case BuiltinType::Accum:
32185f757f3fSDimitry Andric     Out << "DAi";
32195f757f3fSDimitry Andric     break;
32200b57cec5SDimitry Andric   case BuiltinType::LongAccum:
32215f757f3fSDimitry Andric     Out << "DAl";
32225f757f3fSDimitry Andric     break;
32230b57cec5SDimitry Andric   case BuiltinType::UShortAccum:
32245f757f3fSDimitry Andric     Out << "DAt";
32255f757f3fSDimitry Andric     break;
32260b57cec5SDimitry Andric   case BuiltinType::UAccum:
32275f757f3fSDimitry Andric     Out << "DAj";
32285f757f3fSDimitry Andric     break;
32290b57cec5SDimitry Andric   case BuiltinType::ULongAccum:
32305f757f3fSDimitry Andric     Out << "DAm";
32315f757f3fSDimitry Andric     break;
32320b57cec5SDimitry Andric   case BuiltinType::ShortFract:
32335f757f3fSDimitry Andric     Out << "DRs";
32345f757f3fSDimitry Andric     break;
32350b57cec5SDimitry Andric   case BuiltinType::Fract:
32365f757f3fSDimitry Andric     Out << "DRi";
32375f757f3fSDimitry Andric     break;
32380b57cec5SDimitry Andric   case BuiltinType::LongFract:
32395f757f3fSDimitry Andric     Out << "DRl";
32405f757f3fSDimitry Andric     break;
32410b57cec5SDimitry Andric   case BuiltinType::UShortFract:
32425f757f3fSDimitry Andric     Out << "DRt";
32435f757f3fSDimitry Andric     break;
32440b57cec5SDimitry Andric   case BuiltinType::UFract:
32455f757f3fSDimitry Andric     Out << "DRj";
32465f757f3fSDimitry Andric     break;
32470b57cec5SDimitry Andric   case BuiltinType::ULongFract:
32485f757f3fSDimitry Andric     Out << "DRm";
32495f757f3fSDimitry Andric     break;
32500b57cec5SDimitry Andric   case BuiltinType::SatShortAccum:
32515f757f3fSDimitry Andric     Out << "DSDAs";
32525f757f3fSDimitry Andric     break;
32530b57cec5SDimitry Andric   case BuiltinType::SatAccum:
32545f757f3fSDimitry Andric     Out << "DSDAi";
32555f757f3fSDimitry Andric     break;
32560b57cec5SDimitry Andric   case BuiltinType::SatLongAccum:
32575f757f3fSDimitry Andric     Out << "DSDAl";
32585f757f3fSDimitry Andric     break;
32590b57cec5SDimitry Andric   case BuiltinType::SatUShortAccum:
32605f757f3fSDimitry Andric     Out << "DSDAt";
32615f757f3fSDimitry Andric     break;
32620b57cec5SDimitry Andric   case BuiltinType::SatUAccum:
32635f757f3fSDimitry Andric     Out << "DSDAj";
32645f757f3fSDimitry Andric     break;
32650b57cec5SDimitry Andric   case BuiltinType::SatULongAccum:
32665f757f3fSDimitry Andric     Out << "DSDAm";
32675f757f3fSDimitry Andric     break;
32680b57cec5SDimitry Andric   case BuiltinType::SatShortFract:
32695f757f3fSDimitry Andric     Out << "DSDRs";
32705f757f3fSDimitry Andric     break;
32710b57cec5SDimitry Andric   case BuiltinType::SatFract:
32725f757f3fSDimitry Andric     Out << "DSDRi";
32735f757f3fSDimitry Andric     break;
32740b57cec5SDimitry Andric   case BuiltinType::SatLongFract:
32755f757f3fSDimitry Andric     Out << "DSDRl";
32765f757f3fSDimitry Andric     break;
32770b57cec5SDimitry Andric   case BuiltinType::SatUShortFract:
32785f757f3fSDimitry Andric     Out << "DSDRt";
32795f757f3fSDimitry Andric     break;
32800b57cec5SDimitry Andric   case BuiltinType::SatUFract:
32815f757f3fSDimitry Andric     Out << "DSDRj";
32825f757f3fSDimitry Andric     break;
32830b57cec5SDimitry Andric   case BuiltinType::SatULongFract:
32845f757f3fSDimitry Andric     Out << "DSDRm";
32855f757f3fSDimitry Andric     break;
32860b57cec5SDimitry Andric   case BuiltinType::Half:
32870b57cec5SDimitry Andric     Out << "Dh";
32880b57cec5SDimitry Andric     break;
32890b57cec5SDimitry Andric   case BuiltinType::Float:
32900b57cec5SDimitry Andric     Out << 'f';
32910b57cec5SDimitry Andric     break;
32920b57cec5SDimitry Andric   case BuiltinType::Double:
32930b57cec5SDimitry Andric     Out << 'd';
32940b57cec5SDimitry Andric     break;
32950b57cec5SDimitry Andric   case BuiltinType::LongDouble: {
329606c3fb27SDimitry Andric     const TargetInfo *TI =
329706c3fb27SDimitry Andric         getASTContext().getLangOpts().OpenMP &&
329806c3fb27SDimitry Andric                 getASTContext().getLangOpts().OpenMPIsTargetDevice
32990b57cec5SDimitry Andric             ? getASTContext().getAuxTargetInfo()
33000b57cec5SDimitry Andric             : &getASTContext().getTargetInfo();
33010b57cec5SDimitry Andric     Out << TI->getLongDoubleMangling();
33020b57cec5SDimitry Andric     break;
33030b57cec5SDimitry Andric   }
33040b57cec5SDimitry Andric   case BuiltinType::Float128: {
330506c3fb27SDimitry Andric     const TargetInfo *TI =
330606c3fb27SDimitry Andric         getASTContext().getLangOpts().OpenMP &&
330706c3fb27SDimitry Andric                 getASTContext().getLangOpts().OpenMPIsTargetDevice
33080b57cec5SDimitry Andric             ? getASTContext().getAuxTargetInfo()
33090b57cec5SDimitry Andric             : &getASTContext().getTargetInfo();
33100b57cec5SDimitry Andric     Out << TI->getFloat128Mangling();
33110b57cec5SDimitry Andric     break;
33120b57cec5SDimitry Andric   }
33135ffd83dbSDimitry Andric   case BuiltinType::BFloat16: {
331406c3fb27SDimitry Andric     const TargetInfo *TI =
331506c3fb27SDimitry Andric         ((getASTContext().getLangOpts().OpenMP &&
331606c3fb27SDimitry Andric           getASTContext().getLangOpts().OpenMPIsTargetDevice) ||
331706c3fb27SDimitry Andric          getASTContext().getLangOpts().SYCLIsDevice)
331806c3fb27SDimitry Andric             ? getASTContext().getAuxTargetInfo()
331906c3fb27SDimitry Andric             : &getASTContext().getTargetInfo();
33205ffd83dbSDimitry Andric     Out << TI->getBFloat16Mangling();
33215ffd83dbSDimitry Andric     break;
33225ffd83dbSDimitry Andric   }
3323349cc55cSDimitry Andric   case BuiltinType::Ibm128: {
3324349cc55cSDimitry Andric     const TargetInfo *TI = &getASTContext().getTargetInfo();
3325349cc55cSDimitry Andric     Out << TI->getIbm128Mangling();
3326349cc55cSDimitry Andric     break;
3327349cc55cSDimitry Andric   }
33280b57cec5SDimitry Andric   case BuiltinType::NullPtr:
33290b57cec5SDimitry Andric     Out << "Dn";
33300b57cec5SDimitry Andric     break;
33310b57cec5SDimitry Andric 
33320b57cec5SDimitry Andric #define BUILTIN_TYPE(Id, SingletonId)
33330b57cec5SDimitry Andric #define PLACEHOLDER_TYPE(Id, SingletonId) \
33340b57cec5SDimitry Andric   case BuiltinType::Id:
33350b57cec5SDimitry Andric #include "clang/AST/BuiltinTypes.def"
33360b57cec5SDimitry Andric   case BuiltinType::Dependent:
33370b57cec5SDimitry Andric     if (!NullOut)
33380b57cec5SDimitry Andric       llvm_unreachable("mangling a placeholder type");
33390b57cec5SDimitry Andric     break;
33400b57cec5SDimitry Andric   case BuiltinType::ObjCId:
33410b57cec5SDimitry Andric     Out << "11objc_object";
33420b57cec5SDimitry Andric     break;
33430b57cec5SDimitry Andric   case BuiltinType::ObjCClass:
33440b57cec5SDimitry Andric     Out << "10objc_class";
33450b57cec5SDimitry Andric     break;
33460b57cec5SDimitry Andric   case BuiltinType::ObjCSel:
33470b57cec5SDimitry Andric     Out << "13objc_selector";
33480b57cec5SDimitry Andric     break;
33490b57cec5SDimitry Andric #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
33500b57cec5SDimitry Andric   case BuiltinType::Id: \
33510b57cec5SDimitry Andric     type_name = "ocl_" #ImgType "_" #Suffix; \
33520b57cec5SDimitry Andric     Out << type_name.size() << type_name; \
33530b57cec5SDimitry Andric     break;
33540b57cec5SDimitry Andric #include "clang/Basic/OpenCLImageTypes.def"
33550b57cec5SDimitry Andric   case BuiltinType::OCLSampler:
33560b57cec5SDimitry Andric     Out << "11ocl_sampler";
33570b57cec5SDimitry Andric     break;
33580b57cec5SDimitry Andric   case BuiltinType::OCLEvent:
33590b57cec5SDimitry Andric     Out << "9ocl_event";
33600b57cec5SDimitry Andric     break;
33610b57cec5SDimitry Andric   case BuiltinType::OCLClkEvent:
33620b57cec5SDimitry Andric     Out << "12ocl_clkevent";
33630b57cec5SDimitry Andric     break;
33640b57cec5SDimitry Andric   case BuiltinType::OCLQueue:
33650b57cec5SDimitry Andric     Out << "9ocl_queue";
33660b57cec5SDimitry Andric     break;
33670b57cec5SDimitry Andric   case BuiltinType::OCLReserveID:
33680b57cec5SDimitry Andric     Out << "13ocl_reserveid";
33690b57cec5SDimitry Andric     break;
33700b57cec5SDimitry Andric #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
33710b57cec5SDimitry Andric   case BuiltinType::Id: \
33720b57cec5SDimitry Andric     type_name = "ocl_" #ExtType; \
33730b57cec5SDimitry Andric     Out << type_name.size() << type_name; \
33740b57cec5SDimitry Andric     break;
33750b57cec5SDimitry Andric #include "clang/Basic/OpenCLExtensionTypes.def"
3376a7dea167SDimitry Andric   // The SVE types are effectively target-specific.  The mangling scheme
3377a7dea167SDimitry Andric   // is defined in the appendices to the Procedure Call Standard for the
3378a7dea167SDimitry Andric   // Arm Architecture.
33795ffd83dbSDimitry Andric #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls,    \
33805ffd83dbSDimitry Andric                         ElBits, IsSigned, IsFP, IsBF)                          \
3381a7dea167SDimitry Andric   case BuiltinType::Id:                                                        \
33825f757f3fSDimitry Andric     if (T->getKind() == BuiltinType::SveBFloat16 &&                            \
33835f757f3fSDimitry Andric         isCompatibleWith(LangOptions::ClangABI::Ver17)) {                      \
33845f757f3fSDimitry Andric       /* Prior to Clang 18.0 we used this incorrect mangled name */            \
33855f757f3fSDimitry Andric       type_name = "__SVBFloat16_t";                                            \
33865f757f3fSDimitry Andric       Out << "u" << type_name.size() << type_name;                             \
33875f757f3fSDimitry Andric     } else {                                                                   \
33885ffd83dbSDimitry Andric       type_name = MangledName;                                                 \
33895ffd83dbSDimitry Andric       Out << (type_name == InternalName ? "u" : "") << type_name.size()        \
33905ffd83dbSDimitry Andric           << type_name;                                                        \
33915f757f3fSDimitry Andric     }                                                                          \
33925ffd83dbSDimitry Andric     break;
33935ffd83dbSDimitry Andric #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
33945ffd83dbSDimitry Andric   case BuiltinType::Id:                                                        \
33955ffd83dbSDimitry Andric     type_name = MangledName;                                                   \
33965ffd83dbSDimitry Andric     Out << (type_name == InternalName ? "u" : "") << type_name.size()          \
33975ffd83dbSDimitry Andric         << type_name;                                                          \
3398a7dea167SDimitry Andric     break;
339906c3fb27SDimitry Andric #define SVE_OPAQUE_TYPE(InternalName, MangledName, Id, SingletonId)            \
340006c3fb27SDimitry Andric   case BuiltinType::Id:                                                        \
340106c3fb27SDimitry Andric     type_name = MangledName;                                                   \
340206c3fb27SDimitry Andric     Out << (type_name == InternalName ? "u" : "") << type_name.size()          \
340306c3fb27SDimitry Andric         << type_name;                                                          \
340406c3fb27SDimitry Andric     break;
3405a7dea167SDimitry Andric #include "clang/Basic/AArch64SVEACLETypes.def"
3406e8d8bef9SDimitry Andric #define PPC_VECTOR_TYPE(Name, Id, Size) \
3407e8d8bef9SDimitry Andric   case BuiltinType::Id: \
3408e8d8bef9SDimitry Andric     type_name = #Name; \
3409e8d8bef9SDimitry Andric     Out << 'u' << type_name.size() << type_name; \
3410e8d8bef9SDimitry Andric     break;
3411e8d8bef9SDimitry Andric #include "clang/Basic/PPCTypes.def"
3412fe6060f1SDimitry Andric     // TODO: Check the mangling scheme for RISC-V V.
3413fe6060f1SDimitry Andric #define RVV_TYPE(Name, Id, SingletonId)                                        \
3414fe6060f1SDimitry Andric   case BuiltinType::Id:                                                        \
3415fe6060f1SDimitry Andric     type_name = Name;                                                          \
3416fe6060f1SDimitry Andric     Out << 'u' << type_name.size() << type_name;                               \
3417fe6060f1SDimitry Andric     break;
3418fe6060f1SDimitry Andric #include "clang/Basic/RISCVVTypes.def"
341906c3fb27SDimitry Andric #define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS)          \
342006c3fb27SDimitry Andric   case BuiltinType::Id:                                                        \
342106c3fb27SDimitry Andric     type_name = MangledName;                                                   \
342206c3fb27SDimitry Andric     Out << 'u' << type_name.size() << type_name;                               \
342306c3fb27SDimitry Andric     break;
342406c3fb27SDimitry Andric #include "clang/Basic/WebAssemblyReferenceTypes.def"
34250fca6ea1SDimitry Andric #define AMDGPU_TYPE(Name, Id, SingletonId)                                     \
34260fca6ea1SDimitry Andric   case BuiltinType::Id:                                                        \
34270fca6ea1SDimitry Andric     type_name = Name;                                                          \
34280fca6ea1SDimitry Andric     Out << 'u' << type_name.size() << type_name;                               \
34290fca6ea1SDimitry Andric     break;
34300fca6ea1SDimitry Andric #include "clang/Basic/AMDGPUTypes.def"
34310b57cec5SDimitry Andric   }
34320b57cec5SDimitry Andric }
34330b57cec5SDimitry Andric 
getCallingConvQualifierName(CallingConv CC)34340b57cec5SDimitry Andric StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
34350b57cec5SDimitry Andric   switch (CC) {
34360b57cec5SDimitry Andric   case CC_C:
34370b57cec5SDimitry Andric     return "";
34380b57cec5SDimitry Andric 
34390b57cec5SDimitry Andric   case CC_X86VectorCall:
34400b57cec5SDimitry Andric   case CC_X86Pascal:
34410b57cec5SDimitry Andric   case CC_X86RegCall:
34420b57cec5SDimitry Andric   case CC_AAPCS:
34430b57cec5SDimitry Andric   case CC_AAPCS_VFP:
34440b57cec5SDimitry Andric   case CC_AArch64VectorCall:
344581ad6265SDimitry Andric   case CC_AArch64SVEPCS:
344681ad6265SDimitry Andric   case CC_AMDGPUKernelCall:
34470b57cec5SDimitry Andric   case CC_IntelOclBicc:
34480b57cec5SDimitry Andric   case CC_SpirFunction:
34490b57cec5SDimitry Andric   case CC_OpenCLKernel:
34500b57cec5SDimitry Andric   case CC_PreserveMost:
34510b57cec5SDimitry Andric   case CC_PreserveAll:
34525f757f3fSDimitry Andric   case CC_M68kRTD:
34530fca6ea1SDimitry Andric   case CC_PreserveNone:
34540fca6ea1SDimitry Andric   case CC_RISCVVectorCall:
34550b57cec5SDimitry Andric     // FIXME: we should be mangling all of the above.
34560b57cec5SDimitry Andric     return "";
34570b57cec5SDimitry Andric 
34580b57cec5SDimitry Andric   case CC_X86ThisCall:
34590b57cec5SDimitry Andric     // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
34600b57cec5SDimitry Andric     // used explicitly. At this point, we don't have that much information in
34610b57cec5SDimitry Andric     // the AST, since clang tends to bake the convention into the canonical
34620b57cec5SDimitry Andric     // function type. thiscall only rarely used explicitly, so don't mangle it
34630b57cec5SDimitry Andric     // for now.
34640b57cec5SDimitry Andric     return "";
34650b57cec5SDimitry Andric 
34660b57cec5SDimitry Andric   case CC_X86StdCall:
34670b57cec5SDimitry Andric     return "stdcall";
34680b57cec5SDimitry Andric   case CC_X86FastCall:
34690b57cec5SDimitry Andric     return "fastcall";
34700b57cec5SDimitry Andric   case CC_X86_64SysV:
34710b57cec5SDimitry Andric     return "sysv_abi";
34720b57cec5SDimitry Andric   case CC_Win64:
34730b57cec5SDimitry Andric     return "ms_abi";
34740b57cec5SDimitry Andric   case CC_Swift:
34750b57cec5SDimitry Andric     return "swiftcall";
3476fe6060f1SDimitry Andric   case CC_SwiftAsync:
3477fe6060f1SDimitry Andric     return "swiftasynccall";
34780b57cec5SDimitry Andric   }
34790b57cec5SDimitry Andric   llvm_unreachable("bad calling convention");
34800b57cec5SDimitry Andric }
34810b57cec5SDimitry Andric 
mangleExtFunctionInfo(const FunctionType * T)34820b57cec5SDimitry Andric void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
34830b57cec5SDimitry Andric   // Fast path.
34840b57cec5SDimitry Andric   if (T->getExtInfo() == FunctionType::ExtInfo())
34850b57cec5SDimitry Andric     return;
34860b57cec5SDimitry Andric 
34870b57cec5SDimitry Andric   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
34880b57cec5SDimitry Andric   // This will get more complicated in the future if we mangle other
34890b57cec5SDimitry Andric   // things here; but for now, since we mangle ns_returns_retained as
34900b57cec5SDimitry Andric   // a qualifier on the result type, we can get away with this:
34910b57cec5SDimitry Andric   StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
34920b57cec5SDimitry Andric   if (!CCQualifier.empty())
34930b57cec5SDimitry Andric     mangleVendorQualifier(CCQualifier);
34940b57cec5SDimitry Andric 
34950b57cec5SDimitry Andric   // FIXME: regparm
34960b57cec5SDimitry Andric   // FIXME: noreturn
34970b57cec5SDimitry Andric }
34980b57cec5SDimitry Andric 
34990b57cec5SDimitry Andric void
mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI)35000b57cec5SDimitry Andric CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
35010b57cec5SDimitry Andric   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
35020b57cec5SDimitry Andric 
35030b57cec5SDimitry Andric   // Note that these are *not* substitution candidates.  Demanglers might
35040b57cec5SDimitry Andric   // have trouble with this if the parameter type is fully substituted.
35050b57cec5SDimitry Andric 
35060b57cec5SDimitry Andric   switch (PI.getABI()) {
35070b57cec5SDimitry Andric   case ParameterABI::Ordinary:
35080b57cec5SDimitry Andric     break;
35090b57cec5SDimitry Andric 
35100b57cec5SDimitry Andric   // All of these start with "swift", so they come before "ns_consumed".
35110b57cec5SDimitry Andric   case ParameterABI::SwiftContext:
3512fe6060f1SDimitry Andric   case ParameterABI::SwiftAsyncContext:
35130b57cec5SDimitry Andric   case ParameterABI::SwiftErrorResult:
35140b57cec5SDimitry Andric   case ParameterABI::SwiftIndirectResult:
35150b57cec5SDimitry Andric     mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
35160b57cec5SDimitry Andric     break;
35170b57cec5SDimitry Andric   }
35180b57cec5SDimitry Andric 
35190b57cec5SDimitry Andric   if (PI.isConsumed())
35200b57cec5SDimitry Andric     mangleVendorQualifier("ns_consumed");
35210b57cec5SDimitry Andric 
35220b57cec5SDimitry Andric   if (PI.isNoEscape())
35230b57cec5SDimitry Andric     mangleVendorQualifier("noescape");
35240b57cec5SDimitry Andric }
35250b57cec5SDimitry Andric 
35260b57cec5SDimitry Andric // <type>          ::= <function-type>
35270b57cec5SDimitry Andric // <function-type> ::= [<CV-qualifiers>] F [Y]
35280b57cec5SDimitry Andric //                      <bare-function-type> [<ref-qualifier>] E
mangleType(const FunctionProtoType * T)35290b57cec5SDimitry Andric void CXXNameMangler::mangleType(const FunctionProtoType *T) {
35300b57cec5SDimitry Andric   mangleExtFunctionInfo(T);
35310b57cec5SDimitry Andric 
35320b57cec5SDimitry Andric   // Mangle CV-qualifiers, if present.  These are 'this' qualifiers,
35330b57cec5SDimitry Andric   // e.g. "const" in "int (A::*)() const".
35340b57cec5SDimitry Andric   mangleQualifiers(T->getMethodQuals());
35350b57cec5SDimitry Andric 
35360b57cec5SDimitry Andric   // Mangle instantiation-dependent exception-specification, if present,
35370b57cec5SDimitry Andric   // per cxx-abi-dev proposal on 2016-10-11.
35380b57cec5SDimitry Andric   if (T->hasInstantiationDependentExceptionSpec()) {
35390b57cec5SDimitry Andric     if (isComputedNoexcept(T->getExceptionSpecType())) {
35400b57cec5SDimitry Andric       Out << "DO";
35410b57cec5SDimitry Andric       mangleExpression(T->getNoexceptExpr());
35420b57cec5SDimitry Andric       Out << "E";
35430b57cec5SDimitry Andric     } else {
35440b57cec5SDimitry Andric       assert(T->getExceptionSpecType() == EST_Dynamic);
35450b57cec5SDimitry Andric       Out << "Dw";
35460b57cec5SDimitry Andric       for (auto ExceptTy : T->exceptions())
35470b57cec5SDimitry Andric         mangleType(ExceptTy);
35480b57cec5SDimitry Andric       Out << "E";
35490b57cec5SDimitry Andric     }
35500b57cec5SDimitry Andric   } else if (T->isNothrow()) {
35510b57cec5SDimitry Andric     Out << "Do";
35520b57cec5SDimitry Andric   }
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric   Out << 'F';
35550b57cec5SDimitry Andric 
35560b57cec5SDimitry Andric   // FIXME: We don't have enough information in the AST to produce the 'Y'
35570b57cec5SDimitry Andric   // encoding for extern "C" function types.
35580b57cec5SDimitry Andric   mangleBareFunctionType(T, /*MangleReturnType=*/true);
35590b57cec5SDimitry Andric 
35600b57cec5SDimitry Andric   // Mangle the ref-qualifier, if present.
35610b57cec5SDimitry Andric   mangleRefQualifier(T->getRefQualifier());
35620b57cec5SDimitry Andric 
35630b57cec5SDimitry Andric   Out << 'E';
35640b57cec5SDimitry Andric }
35650b57cec5SDimitry Andric 
mangleType(const FunctionNoProtoType * T)35660b57cec5SDimitry Andric void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
35670b57cec5SDimitry Andric   // Function types without prototypes can arise when mangling a function type
35680b57cec5SDimitry Andric   // within an overloadable function in C. We mangle these as the absence of any
35690b57cec5SDimitry Andric   // parameter types (not even an empty parameter list).
35700b57cec5SDimitry Andric   Out << 'F';
35710b57cec5SDimitry Andric 
35720b57cec5SDimitry Andric   FunctionTypeDepthState saved = FunctionTypeDepth.push();
35730b57cec5SDimitry Andric 
35740b57cec5SDimitry Andric   FunctionTypeDepth.enterResultType();
35750b57cec5SDimitry Andric   mangleType(T->getReturnType());
35760b57cec5SDimitry Andric   FunctionTypeDepth.leaveResultType();
35770b57cec5SDimitry Andric 
35780b57cec5SDimitry Andric   FunctionTypeDepth.pop(saved);
35790b57cec5SDimitry Andric   Out << 'E';
35800b57cec5SDimitry Andric }
35810b57cec5SDimitry Andric 
mangleBareFunctionType(const FunctionProtoType * Proto,bool MangleReturnType,const FunctionDecl * FD)35820b57cec5SDimitry Andric void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
35830b57cec5SDimitry Andric                                             bool MangleReturnType,
35840b57cec5SDimitry Andric                                             const FunctionDecl *FD) {
35850b57cec5SDimitry Andric   // Record that we're in a function type.  See mangleFunctionParam
35860b57cec5SDimitry Andric   // for details on what we're trying to achieve here.
35870b57cec5SDimitry Andric   FunctionTypeDepthState saved = FunctionTypeDepth.push();
35880b57cec5SDimitry Andric 
35890b57cec5SDimitry Andric   // <bare-function-type> ::= <signature type>+
35900b57cec5SDimitry Andric   if (MangleReturnType) {
35910b57cec5SDimitry Andric     FunctionTypeDepth.enterResultType();
35920b57cec5SDimitry Andric 
35930b57cec5SDimitry Andric     // Mangle ns_returns_retained as an order-sensitive qualifier here.
35940b57cec5SDimitry Andric     if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
35950b57cec5SDimitry Andric       mangleVendorQualifier("ns_returns_retained");
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric     // Mangle the return type without any direct ARC ownership qualifiers.
35980b57cec5SDimitry Andric     QualType ReturnTy = Proto->getReturnType();
35990b57cec5SDimitry Andric     if (ReturnTy.getObjCLifetime()) {
36000b57cec5SDimitry Andric       auto SplitReturnTy = ReturnTy.split();
36010b57cec5SDimitry Andric       SplitReturnTy.Quals.removeObjCLifetime();
36020b57cec5SDimitry Andric       ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
36030b57cec5SDimitry Andric     }
36040b57cec5SDimitry Andric     mangleType(ReturnTy);
36050b57cec5SDimitry Andric 
36060b57cec5SDimitry Andric     FunctionTypeDepth.leaveResultType();
36070b57cec5SDimitry Andric   }
36080b57cec5SDimitry Andric 
36090b57cec5SDimitry Andric   if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
36100b57cec5SDimitry Andric     //   <builtin-type> ::= v   # void
36110b57cec5SDimitry Andric     Out << 'v';
36125f757f3fSDimitry Andric   } else {
36130b57cec5SDimitry Andric     assert(!FD || FD->getNumParams() == Proto->getNumParams());
36140b57cec5SDimitry Andric     for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
36150b57cec5SDimitry Andric       // Mangle extended parameter info as order-sensitive qualifiers here.
36160b57cec5SDimitry Andric       if (Proto->hasExtParameterInfos() && FD == nullptr) {
36170b57cec5SDimitry Andric         mangleExtParameterInfo(Proto->getExtParameterInfo(I));
36180b57cec5SDimitry Andric       }
36190b57cec5SDimitry Andric 
36200b57cec5SDimitry Andric       // Mangle the type.
36210b57cec5SDimitry Andric       QualType ParamTy = Proto->getParamType(I);
36220b57cec5SDimitry Andric       mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
36230b57cec5SDimitry Andric 
36240b57cec5SDimitry Andric       if (FD) {
36250b57cec5SDimitry Andric         if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
36265f757f3fSDimitry Andric           // Attr can only take 1 character, so we can hardcode the length
36275f757f3fSDimitry Andric           // below.
36280b57cec5SDimitry Andric           assert(Attr->getType() <= 9 && Attr->getType() >= 0);
36290b57cec5SDimitry Andric           if (Attr->isDynamic())
36300b57cec5SDimitry Andric             Out << "U25pass_dynamic_object_size" << Attr->getType();
36310b57cec5SDimitry Andric           else
36320b57cec5SDimitry Andric             Out << "U17pass_object_size" << Attr->getType();
36330b57cec5SDimitry Andric         }
36340b57cec5SDimitry Andric       }
36350b57cec5SDimitry Andric     }
36360b57cec5SDimitry Andric 
36370b57cec5SDimitry Andric     // <builtin-type>      ::= z  # ellipsis
36380b57cec5SDimitry Andric     if (Proto->isVariadic())
36390b57cec5SDimitry Andric       Out << 'z';
36400b57cec5SDimitry Andric   }
36410b57cec5SDimitry Andric 
36425f757f3fSDimitry Andric   if (FD) {
36435f757f3fSDimitry Andric     FunctionTypeDepth.enterResultType();
36445f757f3fSDimitry Andric     mangleRequiresClause(FD->getTrailingRequiresClause());
36455f757f3fSDimitry Andric   }
36465f757f3fSDimitry Andric 
36475f757f3fSDimitry Andric   FunctionTypeDepth.pop(saved);
36485f757f3fSDimitry Andric }
36495f757f3fSDimitry Andric 
36500b57cec5SDimitry Andric // <type>            ::= <class-enum-type>
36510b57cec5SDimitry Andric // <class-enum-type> ::= <name>
mangleType(const UnresolvedUsingType * T)36520b57cec5SDimitry Andric void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
36530b57cec5SDimitry Andric   mangleName(T->getDecl());
36540b57cec5SDimitry Andric }
36550b57cec5SDimitry Andric 
36560b57cec5SDimitry Andric // <type>            ::= <class-enum-type>
36570b57cec5SDimitry Andric // <class-enum-type> ::= <name>
mangleType(const EnumType * T)36580b57cec5SDimitry Andric void CXXNameMangler::mangleType(const EnumType *T) {
36590b57cec5SDimitry Andric   mangleType(static_cast<const TagType*>(T));
36600b57cec5SDimitry Andric }
mangleType(const RecordType * T)36610b57cec5SDimitry Andric void CXXNameMangler::mangleType(const RecordType *T) {
36620b57cec5SDimitry Andric   mangleType(static_cast<const TagType*>(T));
36630b57cec5SDimitry Andric }
mangleType(const TagType * T)36640b57cec5SDimitry Andric void CXXNameMangler::mangleType(const TagType *T) {
36650b57cec5SDimitry Andric   mangleName(T->getDecl());
36660b57cec5SDimitry Andric }
36670b57cec5SDimitry Andric 
36680b57cec5SDimitry Andric // <type>       ::= <array-type>
36690b57cec5SDimitry Andric // <array-type> ::= A <positive dimension number> _ <element type>
36700b57cec5SDimitry Andric //              ::= A [<dimension expression>] _ <element type>
mangleType(const ConstantArrayType * T)36710b57cec5SDimitry Andric void CXXNameMangler::mangleType(const ConstantArrayType *T) {
36720b57cec5SDimitry Andric   Out << 'A' << T->getSize() << '_';
36730b57cec5SDimitry Andric   mangleType(T->getElementType());
36740b57cec5SDimitry Andric }
mangleType(const VariableArrayType * T)36750b57cec5SDimitry Andric void CXXNameMangler::mangleType(const VariableArrayType *T) {
36760b57cec5SDimitry Andric   Out << 'A';
36770b57cec5SDimitry Andric   // decayed vla types (size 0) will just be skipped.
36780b57cec5SDimitry Andric   if (T->getSizeExpr())
36790b57cec5SDimitry Andric     mangleExpression(T->getSizeExpr());
36800b57cec5SDimitry Andric   Out << '_';
36810b57cec5SDimitry Andric   mangleType(T->getElementType());
36820b57cec5SDimitry Andric }
mangleType(const DependentSizedArrayType * T)36830b57cec5SDimitry Andric void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
36840b57cec5SDimitry Andric   Out << 'A';
3685fe6060f1SDimitry Andric   // A DependentSizedArrayType might not have size expression as below
3686fe6060f1SDimitry Andric   //
3687fe6060f1SDimitry Andric   // template<int ...N> int arr[] = {N...};
3688fe6060f1SDimitry Andric   if (T->getSizeExpr())
36890b57cec5SDimitry Andric     mangleExpression(T->getSizeExpr());
36900b57cec5SDimitry Andric   Out << '_';
36910b57cec5SDimitry Andric   mangleType(T->getElementType());
36920b57cec5SDimitry Andric }
mangleType(const IncompleteArrayType * T)36930b57cec5SDimitry Andric void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
36940b57cec5SDimitry Andric   Out << "A_";
36950b57cec5SDimitry Andric   mangleType(T->getElementType());
36960b57cec5SDimitry Andric }
36970b57cec5SDimitry Andric 
36980b57cec5SDimitry Andric // <type>                   ::= <pointer-to-member-type>
36990b57cec5SDimitry Andric // <pointer-to-member-type> ::= M <class type> <member type>
mangleType(const MemberPointerType * T)37000b57cec5SDimitry Andric void CXXNameMangler::mangleType(const MemberPointerType *T) {
37010b57cec5SDimitry Andric   Out << 'M';
37020b57cec5SDimitry Andric   mangleType(QualType(T->getClass(), 0));
37030b57cec5SDimitry Andric   QualType PointeeType = T->getPointeeType();
37040b57cec5SDimitry Andric   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
37050b57cec5SDimitry Andric     mangleType(FPT);
37060b57cec5SDimitry Andric 
37070b57cec5SDimitry Andric     // Itanium C++ ABI 5.1.8:
37080b57cec5SDimitry Andric     //
37090b57cec5SDimitry Andric     //   The type of a non-static member function is considered to be different,
37100b57cec5SDimitry Andric     //   for the purposes of substitution, from the type of a namespace-scope or
37110b57cec5SDimitry Andric     //   static member function whose type appears similar. The types of two
37120b57cec5SDimitry Andric     //   non-static member functions are considered to be different, for the
37130b57cec5SDimitry Andric     //   purposes of substitution, if the functions are members of different
37140b57cec5SDimitry Andric     //   classes. In other words, for the purposes of substitution, the class of
37150b57cec5SDimitry Andric     //   which the function is a member is considered part of the type of
37160b57cec5SDimitry Andric     //   function.
37170b57cec5SDimitry Andric 
37180b57cec5SDimitry Andric     // Given that we already substitute member function pointers as a
37190b57cec5SDimitry Andric     // whole, the net effect of this rule is just to unconditionally
37200b57cec5SDimitry Andric     // suppress substitution on the function type in a member pointer.
37210b57cec5SDimitry Andric     // We increment the SeqID here to emulate adding an entry to the
37220b57cec5SDimitry Andric     // substitution table.
37230b57cec5SDimitry Andric     ++SeqID;
37240b57cec5SDimitry Andric   } else
37250b57cec5SDimitry Andric     mangleType(PointeeType);
37260b57cec5SDimitry Andric }
37270b57cec5SDimitry Andric 
37280b57cec5SDimitry Andric // <type>           ::= <template-param>
mangleType(const TemplateTypeParmType * T)37290b57cec5SDimitry Andric void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3730a7dea167SDimitry Andric   mangleTemplateParameter(T->getDepth(), T->getIndex());
37310b57cec5SDimitry Andric }
37320b57cec5SDimitry Andric 
37330b57cec5SDimitry Andric // <type>           ::= <template-param>
mangleType(const SubstTemplateTypeParmPackType * T)37340b57cec5SDimitry Andric void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
37350b57cec5SDimitry Andric   // FIXME: not clear how to mangle this!
37360b57cec5SDimitry Andric   // template <class T...> class A {
37370b57cec5SDimitry Andric   //   template <class U...> void foo(T(*)(U) x...);
37380b57cec5SDimitry Andric   // };
37390b57cec5SDimitry Andric   Out << "_SUBSTPACK_";
37400b57cec5SDimitry Andric }
37410b57cec5SDimitry Andric 
37420b57cec5SDimitry Andric // <type> ::= P <type>   # pointer-to
mangleType(const PointerType * T)37430b57cec5SDimitry Andric void CXXNameMangler::mangleType(const PointerType *T) {
37440b57cec5SDimitry Andric   Out << 'P';
37450b57cec5SDimitry Andric   mangleType(T->getPointeeType());
37460b57cec5SDimitry Andric }
mangleType(const ObjCObjectPointerType * T)37470b57cec5SDimitry Andric void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
37480b57cec5SDimitry Andric   Out << 'P';
37490b57cec5SDimitry Andric   mangleType(T->getPointeeType());
37500b57cec5SDimitry Andric }
37510b57cec5SDimitry Andric 
37520b57cec5SDimitry Andric // <type> ::= R <type>   # reference-to
mangleType(const LValueReferenceType * T)37530b57cec5SDimitry Andric void CXXNameMangler::mangleType(const LValueReferenceType *T) {
37540b57cec5SDimitry Andric   Out << 'R';
37550b57cec5SDimitry Andric   mangleType(T->getPointeeType());
37560b57cec5SDimitry Andric }
37570b57cec5SDimitry Andric 
37580b57cec5SDimitry Andric // <type> ::= O <type>   # rvalue reference-to (C++0x)
mangleType(const RValueReferenceType * T)37590b57cec5SDimitry Andric void CXXNameMangler::mangleType(const RValueReferenceType *T) {
37600b57cec5SDimitry Andric   Out << 'O';
37610b57cec5SDimitry Andric   mangleType(T->getPointeeType());
37620b57cec5SDimitry Andric }
37630b57cec5SDimitry Andric 
37640b57cec5SDimitry Andric // <type> ::= C <type>   # complex pair (C 2000)
mangleType(const ComplexType * T)37650b57cec5SDimitry Andric void CXXNameMangler::mangleType(const ComplexType *T) {
37660b57cec5SDimitry Andric   Out << 'C';
37670b57cec5SDimitry Andric   mangleType(T->getElementType());
37680b57cec5SDimitry Andric }
37690b57cec5SDimitry Andric 
37700b57cec5SDimitry Andric // ARM's ABI for Neon vector types specifies that they should be mangled as
37710b57cec5SDimitry Andric // if they are structs (to match ARM's initial implementation).  The
37720b57cec5SDimitry Andric // vector type must be one of the special types predefined by ARM.
mangleNeonVectorType(const VectorType * T)37730b57cec5SDimitry Andric void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
37740b57cec5SDimitry Andric   QualType EltType = T->getElementType();
37750b57cec5SDimitry Andric   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
37760b57cec5SDimitry Andric   const char *EltName = nullptr;
37775f757f3fSDimitry Andric   if (T->getVectorKind() == VectorKind::NeonPoly) {
37780b57cec5SDimitry Andric     switch (cast<BuiltinType>(EltType)->getKind()) {
37790b57cec5SDimitry Andric     case BuiltinType::SChar:
37800b57cec5SDimitry Andric     case BuiltinType::UChar:
37810b57cec5SDimitry Andric       EltName = "poly8_t";
37820b57cec5SDimitry Andric       break;
37830b57cec5SDimitry Andric     case BuiltinType::Short:
37840b57cec5SDimitry Andric     case BuiltinType::UShort:
37850b57cec5SDimitry Andric       EltName = "poly16_t";
37860b57cec5SDimitry Andric       break;
37875ffd83dbSDimitry Andric     case BuiltinType::LongLong:
37880b57cec5SDimitry Andric     case BuiltinType::ULongLong:
37890b57cec5SDimitry Andric       EltName = "poly64_t";
37900b57cec5SDimitry Andric       break;
37910b57cec5SDimitry Andric     default: llvm_unreachable("unexpected Neon polynomial vector element type");
37920b57cec5SDimitry Andric     }
37930b57cec5SDimitry Andric   } else {
37940b57cec5SDimitry Andric     switch (cast<BuiltinType>(EltType)->getKind()) {
37950b57cec5SDimitry Andric     case BuiltinType::SChar:     EltName = "int8_t"; break;
37960b57cec5SDimitry Andric     case BuiltinType::UChar:     EltName = "uint8_t"; break;
37970b57cec5SDimitry Andric     case BuiltinType::Short:     EltName = "int16_t"; break;
37980b57cec5SDimitry Andric     case BuiltinType::UShort:    EltName = "uint16_t"; break;
37990b57cec5SDimitry Andric     case BuiltinType::Int:       EltName = "int32_t"; break;
38000b57cec5SDimitry Andric     case BuiltinType::UInt:      EltName = "uint32_t"; break;
38010b57cec5SDimitry Andric     case BuiltinType::LongLong:  EltName = "int64_t"; break;
38020b57cec5SDimitry Andric     case BuiltinType::ULongLong: EltName = "uint64_t"; break;
38030b57cec5SDimitry Andric     case BuiltinType::Double:    EltName = "float64_t"; break;
38040b57cec5SDimitry Andric     case BuiltinType::Float:     EltName = "float32_t"; break;
38050b57cec5SDimitry Andric     case BuiltinType::Half:      EltName = "float16_t"; break;
38065ffd83dbSDimitry Andric     case BuiltinType::BFloat16:  EltName = "bfloat16_t"; break;
38070b57cec5SDimitry Andric     default:
38080b57cec5SDimitry Andric       llvm_unreachable("unexpected Neon vector element type");
38090b57cec5SDimitry Andric     }
38100b57cec5SDimitry Andric   }
38110b57cec5SDimitry Andric   const char *BaseName = nullptr;
38120b57cec5SDimitry Andric   unsigned BitSize = (T->getNumElements() *
38130b57cec5SDimitry Andric                       getASTContext().getTypeSize(EltType));
38140b57cec5SDimitry Andric   if (BitSize == 64)
38150b57cec5SDimitry Andric     BaseName = "__simd64_";
38160b57cec5SDimitry Andric   else {
38170b57cec5SDimitry Andric     assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
38180b57cec5SDimitry Andric     BaseName = "__simd128_";
38190b57cec5SDimitry Andric   }
38200b57cec5SDimitry Andric   Out << strlen(BaseName) + strlen(EltName);
38210b57cec5SDimitry Andric   Out << BaseName << EltName;
38220b57cec5SDimitry Andric }
38230b57cec5SDimitry Andric 
mangleNeonVectorType(const DependentVectorType * T)38240b57cec5SDimitry Andric void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
38250b57cec5SDimitry Andric   DiagnosticsEngine &Diags = Context.getDiags();
38260b57cec5SDimitry Andric   unsigned DiagID = Diags.getCustomDiagID(
38270b57cec5SDimitry Andric       DiagnosticsEngine::Error,
38280b57cec5SDimitry Andric       "cannot mangle this dependent neon vector type yet");
38290b57cec5SDimitry Andric   Diags.Report(T->getAttributeLoc(), DiagID);
38300b57cec5SDimitry Andric }
38310b57cec5SDimitry Andric 
mangleAArch64VectorBase(const BuiltinType * EltType)38320b57cec5SDimitry Andric static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
38330b57cec5SDimitry Andric   switch (EltType->getKind()) {
38340b57cec5SDimitry Andric   case BuiltinType::SChar:
38350b57cec5SDimitry Andric     return "Int8";
38360b57cec5SDimitry Andric   case BuiltinType::Short:
38370b57cec5SDimitry Andric     return "Int16";
38380b57cec5SDimitry Andric   case BuiltinType::Int:
38390b57cec5SDimitry Andric     return "Int32";
38400b57cec5SDimitry Andric   case BuiltinType::Long:
38410b57cec5SDimitry Andric   case BuiltinType::LongLong:
38420b57cec5SDimitry Andric     return "Int64";
38430b57cec5SDimitry Andric   case BuiltinType::UChar:
38440b57cec5SDimitry Andric     return "Uint8";
38450b57cec5SDimitry Andric   case BuiltinType::UShort:
38460b57cec5SDimitry Andric     return "Uint16";
38470b57cec5SDimitry Andric   case BuiltinType::UInt:
38480b57cec5SDimitry Andric     return "Uint32";
38490b57cec5SDimitry Andric   case BuiltinType::ULong:
38500b57cec5SDimitry Andric   case BuiltinType::ULongLong:
38510b57cec5SDimitry Andric     return "Uint64";
38520b57cec5SDimitry Andric   case BuiltinType::Half:
38530b57cec5SDimitry Andric     return "Float16";
38540b57cec5SDimitry Andric   case BuiltinType::Float:
38550b57cec5SDimitry Andric     return "Float32";
38560b57cec5SDimitry Andric   case BuiltinType::Double:
38570b57cec5SDimitry Andric     return "Float64";
38585ffd83dbSDimitry Andric   case BuiltinType::BFloat16:
385916d6b3b3SDimitry Andric     return "Bfloat16";
38600b57cec5SDimitry Andric   default:
38610b57cec5SDimitry Andric     llvm_unreachable("Unexpected vector element base type");
38620b57cec5SDimitry Andric   }
38630b57cec5SDimitry Andric }
38640b57cec5SDimitry Andric 
38650b57cec5SDimitry Andric // AArch64's ABI for Neon vector types specifies that they should be mangled as
38660b57cec5SDimitry Andric // the equivalent internal name. The vector type must be one of the special
38670b57cec5SDimitry Andric // types predefined by ARM.
mangleAArch64NeonVectorType(const VectorType * T)38680b57cec5SDimitry Andric void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
38690b57cec5SDimitry Andric   QualType EltType = T->getElementType();
38700b57cec5SDimitry Andric   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
38710b57cec5SDimitry Andric   unsigned BitSize =
38720b57cec5SDimitry Andric       (T->getNumElements() * getASTContext().getTypeSize(EltType));
38730b57cec5SDimitry Andric   (void)BitSize; // Silence warning.
38740b57cec5SDimitry Andric 
38750b57cec5SDimitry Andric   assert((BitSize == 64 || BitSize == 128) &&
38760b57cec5SDimitry Andric          "Neon vector type not 64 or 128 bits");
38770b57cec5SDimitry Andric 
38780b57cec5SDimitry Andric   StringRef EltName;
38795f757f3fSDimitry Andric   if (T->getVectorKind() == VectorKind::NeonPoly) {
38800b57cec5SDimitry Andric     switch (cast<BuiltinType>(EltType)->getKind()) {
38810b57cec5SDimitry Andric     case BuiltinType::UChar:
38820b57cec5SDimitry Andric       EltName = "Poly8";
38830b57cec5SDimitry Andric       break;
38840b57cec5SDimitry Andric     case BuiltinType::UShort:
38850b57cec5SDimitry Andric       EltName = "Poly16";
38860b57cec5SDimitry Andric       break;
38870b57cec5SDimitry Andric     case BuiltinType::ULong:
38880b57cec5SDimitry Andric     case BuiltinType::ULongLong:
38890b57cec5SDimitry Andric       EltName = "Poly64";
38900b57cec5SDimitry Andric       break;
38910b57cec5SDimitry Andric     default:
38920b57cec5SDimitry Andric       llvm_unreachable("unexpected Neon polynomial vector element type");
38930b57cec5SDimitry Andric     }
38940b57cec5SDimitry Andric   } else
38950b57cec5SDimitry Andric     EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
38960b57cec5SDimitry Andric 
38970b57cec5SDimitry Andric   std::string TypeName =
38980b57cec5SDimitry Andric       ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
38990b57cec5SDimitry Andric   Out << TypeName.length() << TypeName;
39000b57cec5SDimitry Andric }
mangleAArch64NeonVectorType(const DependentVectorType * T)39010b57cec5SDimitry Andric void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
39020b57cec5SDimitry Andric   DiagnosticsEngine &Diags = Context.getDiags();
39030b57cec5SDimitry Andric   unsigned DiagID = Diags.getCustomDiagID(
39040b57cec5SDimitry Andric       DiagnosticsEngine::Error,
39050b57cec5SDimitry Andric       "cannot mangle this dependent neon vector type yet");
39060b57cec5SDimitry Andric   Diags.Report(T->getAttributeLoc(), DiagID);
39070b57cec5SDimitry Andric }
39080b57cec5SDimitry Andric 
3909e8d8bef9SDimitry Andric // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3910e8d8bef9SDimitry Andric // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3911e8d8bef9SDimitry Andric // type as the sizeless variants.
3912e8d8bef9SDimitry Andric //
3913e8d8bef9SDimitry Andric // The mangling scheme for VLS types is implemented as a "pseudo" template:
3914e8d8bef9SDimitry Andric //
3915e8d8bef9SDimitry Andric //   '__SVE_VLS<<type>, <vector length>>'
3916e8d8bef9SDimitry Andric //
3917e8d8bef9SDimitry Andric // Combining the existing SVE type and a specific vector length (in bits).
3918e8d8bef9SDimitry Andric // For example:
3919e8d8bef9SDimitry Andric //
3920e8d8bef9SDimitry Andric //   typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3921e8d8bef9SDimitry Andric //
3922e8d8bef9SDimitry Andric // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3923e8d8bef9SDimitry Andric //
3924e8d8bef9SDimitry Andric //   "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3925e8d8bef9SDimitry Andric //
3926e8d8bef9SDimitry Andric //   i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3927e8d8bef9SDimitry Andric //
3928e8d8bef9SDimitry Andric // The latest ACLE specification (00bet5) does not contain details of this
3929e8d8bef9SDimitry Andric // mangling scheme, it will be specified in the next revision. The mangling
3930e8d8bef9SDimitry Andric // scheme is otherwise defined in the appendices to the Procedure Call Standard
3931e8d8bef9SDimitry Andric // for the Arm Architecture, see
3932349cc55cSDimitry Andric // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
mangleAArch64FixedSveVectorType(const VectorType * T)3933e8d8bef9SDimitry Andric void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
39345f757f3fSDimitry Andric   assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||
39355f757f3fSDimitry Andric           T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
3936e8d8bef9SDimitry Andric          "expected fixed-length SVE vector!");
3937e8d8bef9SDimitry Andric 
3938e8d8bef9SDimitry Andric   QualType EltType = T->getElementType();
3939e8d8bef9SDimitry Andric   assert(EltType->isBuiltinType() &&
3940e8d8bef9SDimitry Andric          "expected builtin type for fixed-length SVE vector!");
3941e8d8bef9SDimitry Andric 
3942e8d8bef9SDimitry Andric   StringRef TypeName;
3943e8d8bef9SDimitry Andric   switch (cast<BuiltinType>(EltType)->getKind()) {
3944e8d8bef9SDimitry Andric   case BuiltinType::SChar:
3945e8d8bef9SDimitry Andric     TypeName = "__SVInt8_t";
3946e8d8bef9SDimitry Andric     break;
3947e8d8bef9SDimitry Andric   case BuiltinType::UChar: {
39485f757f3fSDimitry Andric     if (T->getVectorKind() == VectorKind::SveFixedLengthData)
3949e8d8bef9SDimitry Andric       TypeName = "__SVUint8_t";
3950e8d8bef9SDimitry Andric     else
3951e8d8bef9SDimitry Andric       TypeName = "__SVBool_t";
3952e8d8bef9SDimitry Andric     break;
3953e8d8bef9SDimitry Andric   }
3954e8d8bef9SDimitry Andric   case BuiltinType::Short:
3955e8d8bef9SDimitry Andric     TypeName = "__SVInt16_t";
3956e8d8bef9SDimitry Andric     break;
3957e8d8bef9SDimitry Andric   case BuiltinType::UShort:
3958e8d8bef9SDimitry Andric     TypeName = "__SVUint16_t";
3959e8d8bef9SDimitry Andric     break;
3960e8d8bef9SDimitry Andric   case BuiltinType::Int:
3961e8d8bef9SDimitry Andric     TypeName = "__SVInt32_t";
3962e8d8bef9SDimitry Andric     break;
3963e8d8bef9SDimitry Andric   case BuiltinType::UInt:
3964e8d8bef9SDimitry Andric     TypeName = "__SVUint32_t";
3965e8d8bef9SDimitry Andric     break;
3966e8d8bef9SDimitry Andric   case BuiltinType::Long:
3967e8d8bef9SDimitry Andric     TypeName = "__SVInt64_t";
3968e8d8bef9SDimitry Andric     break;
3969e8d8bef9SDimitry Andric   case BuiltinType::ULong:
3970e8d8bef9SDimitry Andric     TypeName = "__SVUint64_t";
3971e8d8bef9SDimitry Andric     break;
3972e8d8bef9SDimitry Andric   case BuiltinType::Half:
3973e8d8bef9SDimitry Andric     TypeName = "__SVFloat16_t";
3974e8d8bef9SDimitry Andric     break;
3975e8d8bef9SDimitry Andric   case BuiltinType::Float:
3976e8d8bef9SDimitry Andric     TypeName = "__SVFloat32_t";
3977e8d8bef9SDimitry Andric     break;
3978e8d8bef9SDimitry Andric   case BuiltinType::Double:
3979e8d8bef9SDimitry Andric     TypeName = "__SVFloat64_t";
3980e8d8bef9SDimitry Andric     break;
3981e8d8bef9SDimitry Andric   case BuiltinType::BFloat16:
3982e8d8bef9SDimitry Andric     TypeName = "__SVBfloat16_t";
3983e8d8bef9SDimitry Andric     break;
3984e8d8bef9SDimitry Andric   default:
3985e8d8bef9SDimitry Andric     llvm_unreachable("unexpected element type for fixed-length SVE vector!");
3986e8d8bef9SDimitry Andric   }
3987e8d8bef9SDimitry Andric 
3988e8d8bef9SDimitry Andric   unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
3989e8d8bef9SDimitry Andric 
39905f757f3fSDimitry Andric   if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)
3991e8d8bef9SDimitry Andric     VecSizeInBits *= 8;
3992e8d8bef9SDimitry Andric 
3993e8d8bef9SDimitry Andric   Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
3994e8d8bef9SDimitry Andric       << VecSizeInBits << "EE";
3995e8d8bef9SDimitry Andric }
3996e8d8bef9SDimitry Andric 
mangleAArch64FixedSveVectorType(const DependentVectorType * T)3997e8d8bef9SDimitry Andric void CXXNameMangler::mangleAArch64FixedSveVectorType(
3998e8d8bef9SDimitry Andric     const DependentVectorType *T) {
3999e8d8bef9SDimitry Andric   DiagnosticsEngine &Diags = Context.getDiags();
4000e8d8bef9SDimitry Andric   unsigned DiagID = Diags.getCustomDiagID(
4001e8d8bef9SDimitry Andric       DiagnosticsEngine::Error,
4002e8d8bef9SDimitry Andric       "cannot mangle this dependent fixed-length SVE vector type yet");
4003e8d8bef9SDimitry Andric   Diags.Report(T->getAttributeLoc(), DiagID);
4004e8d8bef9SDimitry Andric }
4005e8d8bef9SDimitry Andric 
mangleRISCVFixedRVVVectorType(const VectorType * T)400606c3fb27SDimitry Andric void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {
4007b3edf446SDimitry Andric   assert((T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4008b3edf446SDimitry Andric           T->getVectorKind() == VectorKind::RVVFixedLengthMask) &&
400906c3fb27SDimitry Andric          "expected fixed-length RVV vector!");
401006c3fb27SDimitry Andric 
401106c3fb27SDimitry Andric   QualType EltType = T->getElementType();
401206c3fb27SDimitry Andric   assert(EltType->isBuiltinType() &&
401306c3fb27SDimitry Andric          "expected builtin type for fixed-length RVV vector!");
401406c3fb27SDimitry Andric 
401506c3fb27SDimitry Andric   SmallString<20> TypeNameStr;
401606c3fb27SDimitry Andric   llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
401706c3fb27SDimitry Andric   TypeNameOS << "__rvv_";
401806c3fb27SDimitry Andric   switch (cast<BuiltinType>(EltType)->getKind()) {
401906c3fb27SDimitry Andric   case BuiltinType::SChar:
402006c3fb27SDimitry Andric     TypeNameOS << "int8";
402106c3fb27SDimitry Andric     break;
402206c3fb27SDimitry Andric   case BuiltinType::UChar:
4023b3edf446SDimitry Andric     if (T->getVectorKind() == VectorKind::RVVFixedLengthData)
402406c3fb27SDimitry Andric       TypeNameOS << "uint8";
4025b3edf446SDimitry Andric     else
4026b3edf446SDimitry Andric       TypeNameOS << "bool";
402706c3fb27SDimitry Andric     break;
402806c3fb27SDimitry Andric   case BuiltinType::Short:
402906c3fb27SDimitry Andric     TypeNameOS << "int16";
403006c3fb27SDimitry Andric     break;
403106c3fb27SDimitry Andric   case BuiltinType::UShort:
403206c3fb27SDimitry Andric     TypeNameOS << "uint16";
403306c3fb27SDimitry Andric     break;
403406c3fb27SDimitry Andric   case BuiltinType::Int:
403506c3fb27SDimitry Andric     TypeNameOS << "int32";
403606c3fb27SDimitry Andric     break;
403706c3fb27SDimitry Andric   case BuiltinType::UInt:
403806c3fb27SDimitry Andric     TypeNameOS << "uint32";
403906c3fb27SDimitry Andric     break;
404006c3fb27SDimitry Andric   case BuiltinType::Long:
404106c3fb27SDimitry Andric     TypeNameOS << "int64";
404206c3fb27SDimitry Andric     break;
404306c3fb27SDimitry Andric   case BuiltinType::ULong:
404406c3fb27SDimitry Andric     TypeNameOS << "uint64";
404506c3fb27SDimitry Andric     break;
40465f757f3fSDimitry Andric   case BuiltinType::Float16:
404706c3fb27SDimitry Andric     TypeNameOS << "float16";
404806c3fb27SDimitry Andric     break;
404906c3fb27SDimitry Andric   case BuiltinType::Float:
405006c3fb27SDimitry Andric     TypeNameOS << "float32";
405106c3fb27SDimitry Andric     break;
405206c3fb27SDimitry Andric   case BuiltinType::Double:
405306c3fb27SDimitry Andric     TypeNameOS << "float64";
405406c3fb27SDimitry Andric     break;
405506c3fb27SDimitry Andric   default:
405606c3fb27SDimitry Andric     llvm_unreachable("unexpected element type for fixed-length RVV vector!");
405706c3fb27SDimitry Andric   }
405806c3fb27SDimitry Andric 
405906c3fb27SDimitry Andric   unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
406006c3fb27SDimitry Andric 
406106c3fb27SDimitry Andric   // Apend the LMUL suffix.
406206c3fb27SDimitry Andric   auto VScale = getASTContext().getTargetInfo().getVScaleRange(
406306c3fb27SDimitry Andric       getASTContext().getLangOpts());
406406c3fb27SDimitry Andric   unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;
4065b3edf446SDimitry Andric 
4066b3edf446SDimitry Andric   if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
406706c3fb27SDimitry Andric     TypeNameOS << 'm';
406806c3fb27SDimitry Andric     if (VecSizeInBits >= VLen)
406906c3fb27SDimitry Andric       TypeNameOS << (VecSizeInBits / VLen);
407006c3fb27SDimitry Andric     else
407106c3fb27SDimitry Andric       TypeNameOS << 'f' << (VLen / VecSizeInBits);
4072b3edf446SDimitry Andric   } else {
4073b3edf446SDimitry Andric     TypeNameOS << (VLen / VecSizeInBits);
4074b3edf446SDimitry Andric   }
407506c3fb27SDimitry Andric   TypeNameOS << "_t";
407606c3fb27SDimitry Andric 
407706c3fb27SDimitry Andric   Out << "9__RVV_VLSI" << 'u' << TypeNameStr.size() << TypeNameStr << "Lj"
407806c3fb27SDimitry Andric       << VecSizeInBits << "EE";
407906c3fb27SDimitry Andric }
408006c3fb27SDimitry Andric 
mangleRISCVFixedRVVVectorType(const DependentVectorType * T)408106c3fb27SDimitry Andric void CXXNameMangler::mangleRISCVFixedRVVVectorType(
408206c3fb27SDimitry Andric     const DependentVectorType *T) {
408306c3fb27SDimitry Andric   DiagnosticsEngine &Diags = Context.getDiags();
408406c3fb27SDimitry Andric   unsigned DiagID = Diags.getCustomDiagID(
408506c3fb27SDimitry Andric       DiagnosticsEngine::Error,
408606c3fb27SDimitry Andric       "cannot mangle this dependent fixed-length RVV vector type yet");
408706c3fb27SDimitry Andric   Diags.Report(T->getAttributeLoc(), DiagID);
408806c3fb27SDimitry Andric }
408906c3fb27SDimitry Andric 
40900b57cec5SDimitry Andric // GNU extension: vector types
40910b57cec5SDimitry Andric // <type>                  ::= <vector-type>
40920b57cec5SDimitry Andric // <vector-type>           ::= Dv <positive dimension number> _
40930b57cec5SDimitry Andric //                                    <extended element type>
40940b57cec5SDimitry Andric //                         ::= Dv [<dimension expression>] _ <element type>
40950b57cec5SDimitry Andric // <extended element type> ::= <element type>
40960b57cec5SDimitry Andric //                         ::= p # AltiVec vector pixel
40970b57cec5SDimitry Andric //                         ::= b # Altivec vector bool
mangleType(const VectorType * T)40980b57cec5SDimitry Andric void CXXNameMangler::mangleType(const VectorType *T) {
40995f757f3fSDimitry Andric   if ((T->getVectorKind() == VectorKind::Neon ||
41005f757f3fSDimitry Andric        T->getVectorKind() == VectorKind::NeonPoly)) {
41010b57cec5SDimitry Andric     llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
41020b57cec5SDimitry Andric     llvm::Triple::ArchType Arch =
41030b57cec5SDimitry Andric         getASTContext().getTargetInfo().getTriple().getArch();
41040b57cec5SDimitry Andric     if ((Arch == llvm::Triple::aarch64 ||
41050b57cec5SDimitry Andric          Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
41060b57cec5SDimitry Andric       mangleAArch64NeonVectorType(T);
41070b57cec5SDimitry Andric     else
41080b57cec5SDimitry Andric       mangleNeonVectorType(T);
41090b57cec5SDimitry Andric     return;
41105f757f3fSDimitry Andric   } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
41115f757f3fSDimitry Andric              T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4112e8d8bef9SDimitry Andric     mangleAArch64FixedSveVectorType(T);
4113e8d8bef9SDimitry Andric     return;
4114b3edf446SDimitry Andric   } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4115b3edf446SDimitry Andric              T->getVectorKind() == VectorKind::RVVFixedLengthMask) {
411606c3fb27SDimitry Andric     mangleRISCVFixedRVVVectorType(T);
411706c3fb27SDimitry Andric     return;
41180b57cec5SDimitry Andric   }
41190b57cec5SDimitry Andric   Out << "Dv" << T->getNumElements() << '_';
41205f757f3fSDimitry Andric   if (T->getVectorKind() == VectorKind::AltiVecPixel)
41210b57cec5SDimitry Andric     Out << 'p';
41225f757f3fSDimitry Andric   else if (T->getVectorKind() == VectorKind::AltiVecBool)
41230b57cec5SDimitry Andric     Out << 'b';
41240b57cec5SDimitry Andric   else
41250b57cec5SDimitry Andric     mangleType(T->getElementType());
41260b57cec5SDimitry Andric }
41270b57cec5SDimitry Andric 
mangleType(const DependentVectorType * T)41280b57cec5SDimitry Andric void CXXNameMangler::mangleType(const DependentVectorType *T) {
41295f757f3fSDimitry Andric   if ((T->getVectorKind() == VectorKind::Neon ||
41305f757f3fSDimitry Andric        T->getVectorKind() == VectorKind::NeonPoly)) {
41310b57cec5SDimitry Andric     llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
41320b57cec5SDimitry Andric     llvm::Triple::ArchType Arch =
41330b57cec5SDimitry Andric         getASTContext().getTargetInfo().getTriple().getArch();
41340b57cec5SDimitry Andric     if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
41350b57cec5SDimitry Andric         !Target.isOSDarwin())
41360b57cec5SDimitry Andric       mangleAArch64NeonVectorType(T);
41370b57cec5SDimitry Andric     else
41380b57cec5SDimitry Andric       mangleNeonVectorType(T);
41390b57cec5SDimitry Andric     return;
41405f757f3fSDimitry Andric   } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
41415f757f3fSDimitry Andric              T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4142e8d8bef9SDimitry Andric     mangleAArch64FixedSveVectorType(T);
4143e8d8bef9SDimitry Andric     return;
41445f757f3fSDimitry Andric   } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
414506c3fb27SDimitry Andric     mangleRISCVFixedRVVVectorType(T);
414606c3fb27SDimitry Andric     return;
41470b57cec5SDimitry Andric   }
41480b57cec5SDimitry Andric 
41490b57cec5SDimitry Andric   Out << "Dv";
41500b57cec5SDimitry Andric   mangleExpression(T->getSizeExpr());
41510b57cec5SDimitry Andric   Out << '_';
41525f757f3fSDimitry Andric   if (T->getVectorKind() == VectorKind::AltiVecPixel)
41530b57cec5SDimitry Andric     Out << 'p';
41545f757f3fSDimitry Andric   else if (T->getVectorKind() == VectorKind::AltiVecBool)
41550b57cec5SDimitry Andric     Out << 'b';
41560b57cec5SDimitry Andric   else
41570b57cec5SDimitry Andric     mangleType(T->getElementType());
41580b57cec5SDimitry Andric }
41590b57cec5SDimitry Andric 
mangleType(const ExtVectorType * T)41600b57cec5SDimitry Andric void CXXNameMangler::mangleType(const ExtVectorType *T) {
41610b57cec5SDimitry Andric   mangleType(static_cast<const VectorType*>(T));
41620b57cec5SDimitry Andric }
mangleType(const DependentSizedExtVectorType * T)41630b57cec5SDimitry Andric void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
41640b57cec5SDimitry Andric   Out << "Dv";
41650b57cec5SDimitry Andric   mangleExpression(T->getSizeExpr());
41660b57cec5SDimitry Andric   Out << '_';
41670b57cec5SDimitry Andric   mangleType(T->getElementType());
41680b57cec5SDimitry Andric }
41690b57cec5SDimitry Andric 
mangleType(const ConstantMatrixType * T)41705ffd83dbSDimitry Andric void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
4171e8d8bef9SDimitry Andric   // Mangle matrix types as a vendor extended type:
4172e8d8bef9SDimitry Andric   // u<Len>matrix_typeI<Rows><Columns><element type>E
4173e8d8bef9SDimitry Andric 
41745ffd83dbSDimitry Andric   StringRef VendorQualifier = "matrix_type";
4175e8d8bef9SDimitry Andric   Out << "u" << VendorQualifier.size() << VendorQualifier;
4176e8d8bef9SDimitry Andric 
4177e8d8bef9SDimitry Andric   Out << "I";
41785ffd83dbSDimitry Andric   auto &ASTCtx = getASTContext();
41795ffd83dbSDimitry Andric   unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
41805ffd83dbSDimitry Andric   llvm::APSInt Rows(BitWidth);
41815ffd83dbSDimitry Andric   Rows = T->getNumRows();
41825ffd83dbSDimitry Andric   mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
41835ffd83dbSDimitry Andric   llvm::APSInt Columns(BitWidth);
41845ffd83dbSDimitry Andric   Columns = T->getNumColumns();
41855ffd83dbSDimitry Andric   mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
41865ffd83dbSDimitry Andric   mangleType(T->getElementType());
4187e8d8bef9SDimitry Andric   Out << "E";
41885ffd83dbSDimitry Andric }
41895ffd83dbSDimitry Andric 
mangleType(const DependentSizedMatrixType * T)41905ffd83dbSDimitry Andric void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
4191e8d8bef9SDimitry Andric   // Mangle matrix types as a vendor extended type:
4192e8d8bef9SDimitry Andric   // u<Len>matrix_typeI<row expr><column expr><element type>E
41935ffd83dbSDimitry Andric   StringRef VendorQualifier = "matrix_type";
4194e8d8bef9SDimitry Andric   Out << "u" << VendorQualifier.size() << VendorQualifier;
4195e8d8bef9SDimitry Andric 
4196e8d8bef9SDimitry Andric   Out << "I";
4197d409305fSDimitry Andric   mangleTemplateArgExpr(T->getRowExpr());
4198d409305fSDimitry Andric   mangleTemplateArgExpr(T->getColumnExpr());
41995ffd83dbSDimitry Andric   mangleType(T->getElementType());
4200e8d8bef9SDimitry Andric   Out << "E";
42015ffd83dbSDimitry Andric }
42025ffd83dbSDimitry Andric 
mangleType(const DependentAddressSpaceType * T)42030b57cec5SDimitry Andric void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
42040b57cec5SDimitry Andric   SplitQualType split = T->getPointeeType().split();
42050b57cec5SDimitry Andric   mangleQualifiers(split.Quals, T);
42060b57cec5SDimitry Andric   mangleType(QualType(split.Ty, 0));
42070b57cec5SDimitry Andric }
42080b57cec5SDimitry Andric 
mangleType(const PackExpansionType * T)42090b57cec5SDimitry Andric void CXXNameMangler::mangleType(const PackExpansionType *T) {
42100b57cec5SDimitry Andric   // <type>  ::= Dp <type>          # pack expansion (C++0x)
42110b57cec5SDimitry Andric   Out << "Dp";
42120b57cec5SDimitry Andric   mangleType(T->getPattern());
42130b57cec5SDimitry Andric }
42140b57cec5SDimitry Andric 
mangleType(const PackIndexingType * T)42150fca6ea1SDimitry Andric void CXXNameMangler::mangleType(const PackIndexingType *T) {
42160fca6ea1SDimitry Andric   if (!T->hasSelectedType())
42170fca6ea1SDimitry Andric     mangleType(T->getPattern());
42180fca6ea1SDimitry Andric   else
42190fca6ea1SDimitry Andric     mangleType(T->getSelectedType());
42200fca6ea1SDimitry Andric }
42210fca6ea1SDimitry Andric 
mangleType(const ObjCInterfaceType * T)42220b57cec5SDimitry Andric void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
42230b57cec5SDimitry Andric   mangleSourceName(T->getDecl()->getIdentifier());
42240b57cec5SDimitry Andric }
42250b57cec5SDimitry Andric 
mangleType(const ObjCObjectType * T)42260b57cec5SDimitry Andric void CXXNameMangler::mangleType(const ObjCObjectType *T) {
42270b57cec5SDimitry Andric   // Treat __kindof as a vendor extended type qualifier.
42280b57cec5SDimitry Andric   if (T->isKindOfType())
42290b57cec5SDimitry Andric     Out << "U8__kindof";
42300b57cec5SDimitry Andric 
42310b57cec5SDimitry Andric   if (!T->qual_empty()) {
42320b57cec5SDimitry Andric     // Mangle protocol qualifiers.
42330b57cec5SDimitry Andric     SmallString<64> QualStr;
42340b57cec5SDimitry Andric     llvm::raw_svector_ostream QualOS(QualStr);
42350b57cec5SDimitry Andric     QualOS << "objcproto";
42360b57cec5SDimitry Andric     for (const auto *I : T->quals()) {
42370b57cec5SDimitry Andric       StringRef name = I->getName();
42380b57cec5SDimitry Andric       QualOS << name.size() << name;
42390b57cec5SDimitry Andric     }
42400b57cec5SDimitry Andric     Out << 'U' << QualStr.size() << QualStr;
42410b57cec5SDimitry Andric   }
42420b57cec5SDimitry Andric 
42430b57cec5SDimitry Andric   mangleType(T->getBaseType());
42440b57cec5SDimitry Andric 
42450b57cec5SDimitry Andric   if (T->isSpecialized()) {
42460b57cec5SDimitry Andric     // Mangle type arguments as I <type>+ E
42470b57cec5SDimitry Andric     Out << 'I';
42480b57cec5SDimitry Andric     for (auto typeArg : T->getTypeArgs())
42490b57cec5SDimitry Andric       mangleType(typeArg);
42500b57cec5SDimitry Andric     Out << 'E';
42510b57cec5SDimitry Andric   }
42520b57cec5SDimitry Andric }
42530b57cec5SDimitry Andric 
mangleType(const BlockPointerType * T)42540b57cec5SDimitry Andric void CXXNameMangler::mangleType(const BlockPointerType *T) {
42550b57cec5SDimitry Andric   Out << "U13block_pointer";
42560b57cec5SDimitry Andric   mangleType(T->getPointeeType());
42570b57cec5SDimitry Andric }
42580b57cec5SDimitry Andric 
mangleType(const InjectedClassNameType * T)42590b57cec5SDimitry Andric void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
42600b57cec5SDimitry Andric   // Mangle injected class name types as if the user had written the
42610b57cec5SDimitry Andric   // specialization out fully.  It may not actually be possible to see
42620b57cec5SDimitry Andric   // this mangling, though.
42630b57cec5SDimitry Andric   mangleType(T->getInjectedSpecializationType());
42640b57cec5SDimitry Andric }
42650b57cec5SDimitry Andric 
mangleType(const TemplateSpecializationType * T)42660b57cec5SDimitry Andric void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
42670b57cec5SDimitry Andric   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
4268bdd1243dSDimitry Andric     mangleTemplateName(TD, T->template_arguments());
42690b57cec5SDimitry Andric   } else {
42700b57cec5SDimitry Andric     if (mangleSubstitution(QualType(T, 0)))
42710b57cec5SDimitry Andric       return;
42720b57cec5SDimitry Andric 
42730b57cec5SDimitry Andric     mangleTemplatePrefix(T->getTemplateName());
42740b57cec5SDimitry Andric 
42750b57cec5SDimitry Andric     // FIXME: GCC does not appear to mangle the template arguments when
42760b57cec5SDimitry Andric     // the template in question is a dependent template name. Should we
42770b57cec5SDimitry Andric     // emulate that badness?
4278bdd1243dSDimitry Andric     mangleTemplateArgs(T->getTemplateName(), T->template_arguments());
42790b57cec5SDimitry Andric     addSubstitution(QualType(T, 0));
42800b57cec5SDimitry Andric   }
42810b57cec5SDimitry Andric }
42820b57cec5SDimitry Andric 
mangleType(const DependentNameType * T)42830b57cec5SDimitry Andric void CXXNameMangler::mangleType(const DependentNameType *T) {
42840b57cec5SDimitry Andric   // Proposal by cxx-abi-dev, 2014-03-26
42850b57cec5SDimitry Andric   // <class-enum-type> ::= <name>    # non-dependent or dependent type name or
42860b57cec5SDimitry Andric   //                                 # dependent elaborated type specifier using
42870b57cec5SDimitry Andric   //                                 # 'typename'
42880b57cec5SDimitry Andric   //                   ::= Ts <name> # dependent elaborated type specifier using
42890b57cec5SDimitry Andric   //                                 # 'struct' or 'class'
42900b57cec5SDimitry Andric   //                   ::= Tu <name> # dependent elaborated type specifier using
42910b57cec5SDimitry Andric   //                                 # 'union'
42920b57cec5SDimitry Andric   //                   ::= Te <name> # dependent elaborated type specifier using
42930b57cec5SDimitry Andric   //                                 # 'enum'
42940b57cec5SDimitry Andric   switch (T->getKeyword()) {
42955f757f3fSDimitry Andric   case ElaboratedTypeKeyword::None:
42965f757f3fSDimitry Andric   case ElaboratedTypeKeyword::Typename:
42970b57cec5SDimitry Andric     break;
42985f757f3fSDimitry Andric   case ElaboratedTypeKeyword::Struct:
42995f757f3fSDimitry Andric   case ElaboratedTypeKeyword::Class:
43005f757f3fSDimitry Andric   case ElaboratedTypeKeyword::Interface:
43010b57cec5SDimitry Andric     Out << "Ts";
43020b57cec5SDimitry Andric     break;
43035f757f3fSDimitry Andric   case ElaboratedTypeKeyword::Union:
43040b57cec5SDimitry Andric     Out << "Tu";
43050b57cec5SDimitry Andric     break;
43065f757f3fSDimitry Andric   case ElaboratedTypeKeyword::Enum:
43070b57cec5SDimitry Andric     Out << "Te";
43080b57cec5SDimitry Andric     break;
43090b57cec5SDimitry Andric   }
43100b57cec5SDimitry Andric   // Typename types are always nested
43110b57cec5SDimitry Andric   Out << 'N';
43120b57cec5SDimitry Andric   manglePrefix(T->getQualifier());
43130b57cec5SDimitry Andric   mangleSourceName(T->getIdentifier());
43140b57cec5SDimitry Andric   Out << 'E';
43150b57cec5SDimitry Andric }
43160b57cec5SDimitry Andric 
mangleType(const DependentTemplateSpecializationType * T)43170b57cec5SDimitry Andric void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
43180b57cec5SDimitry Andric   // Dependently-scoped template types are nested if they have a prefix.
43190b57cec5SDimitry Andric   Out << 'N';
43200b57cec5SDimitry Andric 
43210b57cec5SDimitry Andric   // TODO: avoid making this TemplateName.
43220b57cec5SDimitry Andric   TemplateName Prefix =
43230b57cec5SDimitry Andric     getASTContext().getDependentTemplateName(T->getQualifier(),
43240b57cec5SDimitry Andric                                              T->getIdentifier());
43250b57cec5SDimitry Andric   mangleTemplatePrefix(Prefix);
43260b57cec5SDimitry Andric 
43270b57cec5SDimitry Andric   // FIXME: GCC does not appear to mangle the template arguments when
43280b57cec5SDimitry Andric   // the template in question is a dependent template name. Should we
43290b57cec5SDimitry Andric   // emulate that badness?
4330bdd1243dSDimitry Andric   mangleTemplateArgs(Prefix, T->template_arguments());
43310b57cec5SDimitry Andric   Out << 'E';
43320b57cec5SDimitry Andric }
43330b57cec5SDimitry Andric 
mangleType(const TypeOfType * T)43340b57cec5SDimitry Andric void CXXNameMangler::mangleType(const TypeOfType *T) {
43350b57cec5SDimitry Andric   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
43360b57cec5SDimitry Andric   // "extension with parameters" mangling.
43370b57cec5SDimitry Andric   Out << "u6typeof";
43380b57cec5SDimitry Andric }
43390b57cec5SDimitry Andric 
mangleType(const TypeOfExprType * T)43400b57cec5SDimitry Andric void CXXNameMangler::mangleType(const TypeOfExprType *T) {
43410b57cec5SDimitry Andric   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
43420b57cec5SDimitry Andric   // "extension with parameters" mangling.
43430b57cec5SDimitry Andric   Out << "u6typeof";
43440b57cec5SDimitry Andric }
43450b57cec5SDimitry Andric 
mangleType(const DecltypeType * T)43460b57cec5SDimitry Andric void CXXNameMangler::mangleType(const DecltypeType *T) {
43470b57cec5SDimitry Andric   Expr *E = T->getUnderlyingExpr();
43480b57cec5SDimitry Andric 
43490b57cec5SDimitry Andric   // type ::= Dt <expression> E  # decltype of an id-expression
43500b57cec5SDimitry Andric   //                             #   or class member access
43510b57cec5SDimitry Andric   //      ::= DT <expression> E  # decltype of an expression
43520b57cec5SDimitry Andric 
43530b57cec5SDimitry Andric   // This purports to be an exhaustive list of id-expressions and
43540b57cec5SDimitry Andric   // class member accesses.  Note that we do not ignore parentheses;
43550b57cec5SDimitry Andric   // parentheses change the semantics of decltype for these
43560b57cec5SDimitry Andric   // expressions (and cause the mangler to use the other form).
43570b57cec5SDimitry Andric   if (isa<DeclRefExpr>(E) ||
43580b57cec5SDimitry Andric       isa<MemberExpr>(E) ||
43590b57cec5SDimitry Andric       isa<UnresolvedLookupExpr>(E) ||
43600b57cec5SDimitry Andric       isa<DependentScopeDeclRefExpr>(E) ||
43610b57cec5SDimitry Andric       isa<CXXDependentScopeMemberExpr>(E) ||
43620b57cec5SDimitry Andric       isa<UnresolvedMemberExpr>(E))
43630b57cec5SDimitry Andric     Out << "Dt";
43640b57cec5SDimitry Andric   else
43650b57cec5SDimitry Andric     Out << "DT";
43660b57cec5SDimitry Andric   mangleExpression(E);
43670b57cec5SDimitry Andric   Out << 'E';
43680b57cec5SDimitry Andric }
43690b57cec5SDimitry Andric 
mangleType(const UnaryTransformType * T)43700b57cec5SDimitry Andric void CXXNameMangler::mangleType(const UnaryTransformType *T) {
43710b57cec5SDimitry Andric   // If this is dependent, we need to record that. If not, we simply
43720b57cec5SDimitry Andric   // mangle it as the underlying type since they are equivalent.
43730b57cec5SDimitry Andric   if (T->isDependentType()) {
4374bdd1243dSDimitry Andric     Out << "u";
43750b57cec5SDimitry Andric 
4376bdd1243dSDimitry Andric     StringRef BuiltinName;
43770b57cec5SDimitry Andric     switch (T->getUTTKind()) {
4378bdd1243dSDimitry Andric #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait)                                  \
4379bdd1243dSDimitry Andric   case UnaryTransformType::Enum:                                               \
4380bdd1243dSDimitry Andric     BuiltinName = "__" #Trait;                                                 \
43810b57cec5SDimitry Andric     break;
4382bdd1243dSDimitry Andric #include "clang/Basic/TransformTypeTraits.def"
43830b57cec5SDimitry Andric     }
4384bdd1243dSDimitry Andric     Out << BuiltinName.size() << BuiltinName;
43850b57cec5SDimitry Andric   }
43860b57cec5SDimitry Andric 
4387bdd1243dSDimitry Andric   Out << "I";
43880b57cec5SDimitry Andric   mangleType(T->getBaseType());
4389bdd1243dSDimitry Andric   Out << "E";
43900b57cec5SDimitry Andric }
43910b57cec5SDimitry Andric 
mangleType(const AutoType * T)43920b57cec5SDimitry Andric void CXXNameMangler::mangleType(const AutoType *T) {
43930b57cec5SDimitry Andric   assert(T->getDeducedType().isNull() &&
43940b57cec5SDimitry Andric          "Deduced AutoType shouldn't be handled here!");
43950b57cec5SDimitry Andric   assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
43960b57cec5SDimitry Andric          "shouldn't need to mangle __auto_type!");
43970b57cec5SDimitry Andric   // <builtin-type> ::= Da # auto
43980b57cec5SDimitry Andric   //                ::= Dc # decltype(auto)
43995f757f3fSDimitry Andric   //                ::= Dk # constrained auto
44005f757f3fSDimitry Andric   //                ::= DK # constrained decltype(auto)
44015f757f3fSDimitry Andric   if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
44025f757f3fSDimitry Andric     Out << (T->isDecltypeAuto() ? "DK" : "Dk");
44035f757f3fSDimitry Andric     mangleTypeConstraint(T->getTypeConstraintConcept(),
44045f757f3fSDimitry Andric                          T->getTypeConstraintArguments());
44055f757f3fSDimitry Andric   } else {
44060b57cec5SDimitry Andric     Out << (T->isDecltypeAuto() ? "Dc" : "Da");
44070b57cec5SDimitry Andric   }
44085f757f3fSDimitry Andric }
44090b57cec5SDimitry Andric 
mangleType(const DeducedTemplateSpecializationType * T)44100b57cec5SDimitry Andric void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4411e8d8bef9SDimitry Andric   QualType Deduced = T->getDeducedType();
4412e8d8bef9SDimitry Andric   if (!Deduced.isNull())
4413e8d8bef9SDimitry Andric     return mangleType(Deduced);
4414e8d8bef9SDimitry Andric 
4415e8d8bef9SDimitry Andric   TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
4416e8d8bef9SDimitry Andric   assert(TD && "shouldn't form deduced TST unless we know we have a template");
4417e8d8bef9SDimitry Andric 
4418e8d8bef9SDimitry Andric   if (mangleSubstitution(TD))
4419e8d8bef9SDimitry Andric     return;
4420e8d8bef9SDimitry Andric 
4421e8d8bef9SDimitry Andric   mangleName(GlobalDecl(TD));
4422e8d8bef9SDimitry Andric   addSubstitution(TD);
44230b57cec5SDimitry Andric }
44240b57cec5SDimitry Andric 
mangleType(const AtomicType * T)44250b57cec5SDimitry Andric void CXXNameMangler::mangleType(const AtomicType *T) {
44260b57cec5SDimitry Andric   // <type> ::= U <source-name> <type>  # vendor extended type qualifier
44270b57cec5SDimitry Andric   // (Until there's a standardized mangling...)
44280b57cec5SDimitry Andric   Out << "U7_Atomic";
44290b57cec5SDimitry Andric   mangleType(T->getValueType());
44300b57cec5SDimitry Andric }
44310b57cec5SDimitry Andric 
mangleType(const PipeType * T)44320b57cec5SDimitry Andric void CXXNameMangler::mangleType(const PipeType *T) {
44330b57cec5SDimitry Andric   // Pipe type mangling rules are described in SPIR 2.0 specification
44340b57cec5SDimitry Andric   // A.1 Data types and A.3 Summary of changes
44350b57cec5SDimitry Andric   // <type> ::= 8ocl_pipe
44360b57cec5SDimitry Andric   Out << "8ocl_pipe";
44370b57cec5SDimitry Andric }
44380b57cec5SDimitry Andric 
mangleType(const BitIntType * T)44390eae32dcSDimitry Andric void CXXNameMangler::mangleType(const BitIntType *T) {
44400eae32dcSDimitry Andric   // 5.1.5.2 Builtin types
44410eae32dcSDimitry Andric   // <type> ::= DB <number | instantiation-dependent expression> _
44420eae32dcSDimitry Andric   //        ::= DU <number | instantiation-dependent expression> _
44430eae32dcSDimitry Andric   Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
44445ffd83dbSDimitry Andric }
44455ffd83dbSDimitry Andric 
mangleType(const DependentBitIntType * T)44460eae32dcSDimitry Andric void CXXNameMangler::mangleType(const DependentBitIntType *T) {
44470eae32dcSDimitry Andric   // 5.1.5.2 Builtin types
44480eae32dcSDimitry Andric   // <type> ::= DB <number | instantiation-dependent expression> _
44490eae32dcSDimitry Andric   //        ::= DU <number | instantiation-dependent expression> _
44500eae32dcSDimitry Andric   Out << "D" << (T->isUnsigned() ? "U" : "B");
44510eae32dcSDimitry Andric   mangleExpression(T->getNumBitsExpr());
44520eae32dcSDimitry Andric   Out << "_";
44535ffd83dbSDimitry Andric }
44545ffd83dbSDimitry Andric 
mangleType(const ArrayParameterType * T)44550fca6ea1SDimitry Andric void CXXNameMangler::mangleType(const ArrayParameterType *T) {
44560fca6ea1SDimitry Andric   mangleType(cast<ConstantArrayType>(T));
44570fca6ea1SDimitry Andric }
44580fca6ea1SDimitry Andric 
mangleIntegerLiteral(QualType T,const llvm::APSInt & Value)44590b57cec5SDimitry Andric void CXXNameMangler::mangleIntegerLiteral(QualType T,
44600b57cec5SDimitry Andric                                           const llvm::APSInt &Value) {
44610b57cec5SDimitry Andric   //  <expr-primary> ::= L <type> <value number> E # integer literal
44620b57cec5SDimitry Andric   Out << 'L';
44630b57cec5SDimitry Andric 
44640b57cec5SDimitry Andric   mangleType(T);
44650b57cec5SDimitry Andric   if (T->isBooleanType()) {
44660b57cec5SDimitry Andric     // Boolean values are encoded as 0/1.
44670b57cec5SDimitry Andric     Out << (Value.getBoolValue() ? '1' : '0');
44680b57cec5SDimitry Andric   } else {
44690b57cec5SDimitry Andric     mangleNumber(Value);
44700b57cec5SDimitry Andric   }
44710b57cec5SDimitry Andric   Out << 'E';
44720b57cec5SDimitry Andric 
44730b57cec5SDimitry Andric }
44740b57cec5SDimitry Andric 
mangleMemberExprBase(const Expr * Base,bool IsArrow)44750b57cec5SDimitry Andric void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
44760b57cec5SDimitry Andric   // Ignore member expressions involving anonymous unions.
44770b57cec5SDimitry Andric   while (const auto *RT = Base->getType()->getAs<RecordType>()) {
44780b57cec5SDimitry Andric     if (!RT->getDecl()->isAnonymousStructOrUnion())
44790b57cec5SDimitry Andric       break;
44800b57cec5SDimitry Andric     const auto *ME = dyn_cast<MemberExpr>(Base);
44810b57cec5SDimitry Andric     if (!ME)
44820b57cec5SDimitry Andric       break;
44830b57cec5SDimitry Andric     Base = ME->getBase();
44840b57cec5SDimitry Andric     IsArrow = ME->isArrow();
44850b57cec5SDimitry Andric   }
44860b57cec5SDimitry Andric 
44870b57cec5SDimitry Andric   if (Base->isImplicitCXXThis()) {
44880b57cec5SDimitry Andric     // Note: GCC mangles member expressions to the implicit 'this' as
44890b57cec5SDimitry Andric     // *this., whereas we represent them as this->. The Itanium C++ ABI
44900b57cec5SDimitry Andric     // does not specify anything here, so we follow GCC.
44910b57cec5SDimitry Andric     Out << "dtdefpT";
44920b57cec5SDimitry Andric   } else {
44930b57cec5SDimitry Andric     Out << (IsArrow ? "pt" : "dt");
44940b57cec5SDimitry Andric     mangleExpression(Base);
44950b57cec5SDimitry Andric   }
44960b57cec5SDimitry Andric }
44970b57cec5SDimitry Andric 
44980b57cec5SDimitry Andric /// Mangles a member expression.
mangleMemberExpr(const Expr * base,bool isArrow,NestedNameSpecifier * qualifier,NamedDecl * firstQualifierLookup,DeclarationName member,const TemplateArgumentLoc * TemplateArgs,unsigned NumTemplateArgs,unsigned arity)44990b57cec5SDimitry Andric void CXXNameMangler::mangleMemberExpr(const Expr *base,
45000b57cec5SDimitry Andric                                       bool isArrow,
45010b57cec5SDimitry Andric                                       NestedNameSpecifier *qualifier,
45020b57cec5SDimitry Andric                                       NamedDecl *firstQualifierLookup,
45030b57cec5SDimitry Andric                                       DeclarationName member,
45040b57cec5SDimitry Andric                                       const TemplateArgumentLoc *TemplateArgs,
45050b57cec5SDimitry Andric                                       unsigned NumTemplateArgs,
45060b57cec5SDimitry Andric                                       unsigned arity) {
45070b57cec5SDimitry Andric   // <expression> ::= dt <expression> <unresolved-name>
45080b57cec5SDimitry Andric   //              ::= pt <expression> <unresolved-name>
45090b57cec5SDimitry Andric   if (base)
45100b57cec5SDimitry Andric     mangleMemberExprBase(base, isArrow);
45110b57cec5SDimitry Andric   mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
45120b57cec5SDimitry Andric }
45130b57cec5SDimitry Andric 
45140b57cec5SDimitry Andric /// Look at the callee of the given call expression and determine if
45150b57cec5SDimitry Andric /// it's a parenthesized id-expression which would have triggered ADL
45160b57cec5SDimitry Andric /// otherwise.
isParenthesizedADLCallee(const CallExpr * call)45170b57cec5SDimitry Andric static bool isParenthesizedADLCallee(const CallExpr *call) {
45180b57cec5SDimitry Andric   const Expr *callee = call->getCallee();
45190b57cec5SDimitry Andric   const Expr *fn = callee->IgnoreParens();
45200b57cec5SDimitry Andric 
45210b57cec5SDimitry Andric   // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,
45220b57cec5SDimitry Andric   // too, but for those to appear in the callee, it would have to be
45230b57cec5SDimitry Andric   // parenthesized.
45240b57cec5SDimitry Andric   if (callee == fn) return false;
45250b57cec5SDimitry Andric 
45260b57cec5SDimitry Andric   // Must be an unresolved lookup.
45270b57cec5SDimitry Andric   const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
45280b57cec5SDimitry Andric   if (!lookup) return false;
45290b57cec5SDimitry Andric 
45300b57cec5SDimitry Andric   assert(!lookup->requiresADL());
45310b57cec5SDimitry Andric 
45320b57cec5SDimitry Andric   // Must be an unqualified lookup.
45330b57cec5SDimitry Andric   if (lookup->getQualifier()) return false;
45340b57cec5SDimitry Andric 
45350b57cec5SDimitry Andric   // Must not have found a class member.  Note that if one is a class
45360b57cec5SDimitry Andric   // member, they're all class members.
45370b57cec5SDimitry Andric   if (lookup->getNumDecls() > 0 &&
45380b57cec5SDimitry Andric       (*lookup->decls_begin())->isCXXClassMember())
45390b57cec5SDimitry Andric     return false;
45400b57cec5SDimitry Andric 
45410b57cec5SDimitry Andric   // Otherwise, ADL would have been triggered.
45420b57cec5SDimitry Andric   return true;
45430b57cec5SDimitry Andric }
45440b57cec5SDimitry Andric 
mangleCastExpression(const Expr * E,StringRef CastEncoding)45450b57cec5SDimitry Andric void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
45460b57cec5SDimitry Andric   const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
45470b57cec5SDimitry Andric   Out << CastEncoding;
45480b57cec5SDimitry Andric   mangleType(ECE->getType());
45490b57cec5SDimitry Andric   mangleExpression(ECE->getSubExpr());
45500b57cec5SDimitry Andric }
45510b57cec5SDimitry Andric 
mangleInitListElements(const InitListExpr * InitList)45520b57cec5SDimitry Andric void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
45530b57cec5SDimitry Andric   if (auto *Syntactic = InitList->getSyntacticForm())
45540b57cec5SDimitry Andric     InitList = Syntactic;
45550b57cec5SDimitry Andric   for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
45560b57cec5SDimitry Andric     mangleExpression(InitList->getInit(i));
45570b57cec5SDimitry Andric }
45580b57cec5SDimitry Andric 
mangleRequirement(SourceLocation RequiresExprLoc,const concepts::Requirement * Req)45595f757f3fSDimitry Andric void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc,
45605f757f3fSDimitry Andric                                        const concepts::Requirement *Req) {
45615f757f3fSDimitry Andric   using concepts::Requirement;
45625f757f3fSDimitry Andric 
45635f757f3fSDimitry Andric   // TODO: We can't mangle the result of a failed substitution. It's not clear
45645f757f3fSDimitry Andric   // whether we should be mangling the original form prior to any substitution
45655f757f3fSDimitry Andric   // instead. See https://lists.isocpp.org/core/2023/04/14118.php
45665f757f3fSDimitry Andric   auto HandleSubstitutionFailure =
45675f757f3fSDimitry Andric       [&](SourceLocation Loc) {
45685f757f3fSDimitry Andric         DiagnosticsEngine &Diags = Context.getDiags();
45695f757f3fSDimitry Andric         unsigned DiagID = Diags.getCustomDiagID(
45705f757f3fSDimitry Andric             DiagnosticsEngine::Error, "cannot mangle this requires-expression "
45715f757f3fSDimitry Andric                                       "containing a substitution failure");
45725f757f3fSDimitry Andric         Diags.Report(Loc, DiagID);
45735f757f3fSDimitry Andric         Out << 'F';
45745f757f3fSDimitry Andric       };
45755f757f3fSDimitry Andric 
45765f757f3fSDimitry Andric   switch (Req->getKind()) {
45775f757f3fSDimitry Andric   case Requirement::RK_Type: {
45785f757f3fSDimitry Andric     const auto *TR = cast<concepts::TypeRequirement>(Req);
45795f757f3fSDimitry Andric     if (TR->isSubstitutionFailure())
45805f757f3fSDimitry Andric       return HandleSubstitutionFailure(
45815f757f3fSDimitry Andric           TR->getSubstitutionDiagnostic()->DiagLoc);
45825f757f3fSDimitry Andric 
45835f757f3fSDimitry Andric     Out << 'T';
45845f757f3fSDimitry Andric     mangleType(TR->getType()->getType());
45855f757f3fSDimitry Andric     break;
45865f757f3fSDimitry Andric   }
45875f757f3fSDimitry Andric 
45885f757f3fSDimitry Andric   case Requirement::RK_Simple:
45895f757f3fSDimitry Andric   case Requirement::RK_Compound: {
45905f757f3fSDimitry Andric     const auto *ER = cast<concepts::ExprRequirement>(Req);
45915f757f3fSDimitry Andric     if (ER->isExprSubstitutionFailure())
45925f757f3fSDimitry Andric       return HandleSubstitutionFailure(
45935f757f3fSDimitry Andric           ER->getExprSubstitutionDiagnostic()->DiagLoc);
45945f757f3fSDimitry Andric 
45955f757f3fSDimitry Andric     Out << 'X';
45965f757f3fSDimitry Andric     mangleExpression(ER->getExpr());
45975f757f3fSDimitry Andric 
45985f757f3fSDimitry Andric     if (ER->hasNoexceptRequirement())
45995f757f3fSDimitry Andric       Out << 'N';
46005f757f3fSDimitry Andric 
46015f757f3fSDimitry Andric     if (!ER->getReturnTypeRequirement().isEmpty()) {
46025f757f3fSDimitry Andric       if (ER->getReturnTypeRequirement().isSubstitutionFailure())
46035f757f3fSDimitry Andric         return HandleSubstitutionFailure(ER->getReturnTypeRequirement()
46045f757f3fSDimitry Andric                                              .getSubstitutionDiagnostic()
46055f757f3fSDimitry Andric                                              ->DiagLoc);
46065f757f3fSDimitry Andric 
46075f757f3fSDimitry Andric       Out << 'R';
46085f757f3fSDimitry Andric       mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());
46095f757f3fSDimitry Andric     }
46105f757f3fSDimitry Andric     break;
46115f757f3fSDimitry Andric   }
46125f757f3fSDimitry Andric 
46135f757f3fSDimitry Andric   case Requirement::RK_Nested:
46145f757f3fSDimitry Andric     const auto *NR = cast<concepts::NestedRequirement>(Req);
46155f757f3fSDimitry Andric     if (NR->hasInvalidConstraint()) {
46165f757f3fSDimitry Andric       // FIXME: NestedRequirement should track the location of its requires
46175f757f3fSDimitry Andric       // keyword.
46185f757f3fSDimitry Andric       return HandleSubstitutionFailure(RequiresExprLoc);
46195f757f3fSDimitry Andric     }
46205f757f3fSDimitry Andric 
46215f757f3fSDimitry Andric     Out << 'Q';
46225f757f3fSDimitry Andric     mangleExpression(NR->getConstraintExpr());
46235f757f3fSDimitry Andric     break;
46245f757f3fSDimitry Andric   }
46255f757f3fSDimitry Andric }
46265f757f3fSDimitry Andric 
mangleExpression(const Expr * E,unsigned Arity,bool AsTemplateArg)4627d409305fSDimitry Andric void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4628d409305fSDimitry Andric                                       bool AsTemplateArg) {
46290b57cec5SDimitry Andric   // <expression> ::= <unary operator-name> <expression>
46300b57cec5SDimitry Andric   //              ::= <binary operator-name> <expression> <expression>
46310b57cec5SDimitry Andric   //              ::= <trinary operator-name> <expression> <expression> <expression>
46320b57cec5SDimitry Andric   //              ::= cv <type> expression           # conversion with one argument
46330b57cec5SDimitry Andric   //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
46340b57cec5SDimitry Andric   //              ::= dc <type> <expression>         # dynamic_cast<type> (expression)
46350b57cec5SDimitry Andric   //              ::= sc <type> <expression>         # static_cast<type> (expression)
46360b57cec5SDimitry Andric   //              ::= cc <type> <expression>         # const_cast<type> (expression)
46370b57cec5SDimitry Andric   //              ::= rc <type> <expression>         # reinterpret_cast<type> (expression)
46380b57cec5SDimitry Andric   //              ::= st <type>                      # sizeof (a type)
46390b57cec5SDimitry Andric   //              ::= at <type>                      # alignof (a type)
46400b57cec5SDimitry Andric   //              ::= <template-param>
46410b57cec5SDimitry Andric   //              ::= <function-param>
4642d409305fSDimitry Andric   //              ::= fpT                            # 'this' expression (part of <function-param>)
46430b57cec5SDimitry Andric   //              ::= sr <type> <unqualified-name>                   # dependent name
46440b57cec5SDimitry Andric   //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
46450b57cec5SDimitry Andric   //              ::= ds <expression> <expression>                   # expr.*expr
46460b57cec5SDimitry Andric   //              ::= sZ <template-param>                            # size of a parameter pack
46470b57cec5SDimitry Andric   //              ::= sZ <function-param>    # size of a function parameter pack
4648d409305fSDimitry Andric   //              ::= u <source-name> <template-arg>* E # vendor extended expression
46490b57cec5SDimitry Andric   //              ::= <expr-primary>
46500b57cec5SDimitry Andric   // <expr-primary> ::= L <type> <value number> E    # integer literal
4651d409305fSDimitry Andric   //                ::= L <type> <value float> E     # floating literal
4652d409305fSDimitry Andric   //                ::= L <type> <string type> E     # string literal
4653d409305fSDimitry Andric   //                ::= L <nullptr type> E           # nullptr literal "LDnE"
4654d409305fSDimitry Andric   //                ::= L <pointer type> 0 E         # null pointer template argument
4655d409305fSDimitry Andric   //                ::= L <type> <real-part float> _ <imag-part float> E    # complex floating point literal (C99); not used by clang
46560b57cec5SDimitry Andric   //                ::= L <mangled-name> E           # external name
46570b57cec5SDimitry Andric   QualType ImplicitlyConvertedToType;
46580b57cec5SDimitry Andric 
4659d409305fSDimitry Andric   // A top-level expression that's not <expr-primary> needs to be wrapped in
4660d409305fSDimitry Andric   // X...E in a template arg.
4661d409305fSDimitry Andric   bool IsPrimaryExpr = true;
4662d409305fSDimitry Andric   auto NotPrimaryExpr = [&] {
4663d409305fSDimitry Andric     if (AsTemplateArg && IsPrimaryExpr)
4664d409305fSDimitry Andric       Out << 'X';
4665d409305fSDimitry Andric     IsPrimaryExpr = false;
4666d409305fSDimitry Andric   };
4667d409305fSDimitry Andric 
4668d409305fSDimitry Andric   auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4669d409305fSDimitry Andric     switch (D->getKind()) {
4670d409305fSDimitry Andric     default:
4671d409305fSDimitry Andric       //  <expr-primary> ::= L <mangled-name> E # external name
4672d409305fSDimitry Andric       Out << 'L';
4673d409305fSDimitry Andric       mangle(D);
4674d409305fSDimitry Andric       Out << 'E';
4675d409305fSDimitry Andric       break;
4676d409305fSDimitry Andric 
4677d409305fSDimitry Andric     case Decl::ParmVar:
4678d409305fSDimitry Andric       NotPrimaryExpr();
4679d409305fSDimitry Andric       mangleFunctionParam(cast<ParmVarDecl>(D));
4680d409305fSDimitry Andric       break;
4681d409305fSDimitry Andric 
4682d409305fSDimitry Andric     case Decl::EnumConstant: {
4683d409305fSDimitry Andric       // <expr-primary>
4684d409305fSDimitry Andric       const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4685d409305fSDimitry Andric       mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4686d409305fSDimitry Andric       break;
4687d409305fSDimitry Andric     }
4688d409305fSDimitry Andric 
4689d409305fSDimitry Andric     case Decl::NonTypeTemplateParm:
4690d409305fSDimitry Andric       NotPrimaryExpr();
4691d409305fSDimitry Andric       const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4692d409305fSDimitry Andric       mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4693d409305fSDimitry Andric       break;
4694d409305fSDimitry Andric     }
4695d409305fSDimitry Andric   };
4696d409305fSDimitry Andric 
4697d409305fSDimitry Andric   // 'goto recurse' is used when handling a simple "unwrapping" node which
4698d409305fSDimitry Andric   // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4699d409305fSDimitry Andric   // to be preserved.
47000b57cec5SDimitry Andric recurse:
47010b57cec5SDimitry Andric   switch (E->getStmtClass()) {
47020b57cec5SDimitry Andric   case Expr::NoStmtClass:
47030b57cec5SDimitry Andric #define ABSTRACT_STMT(Type)
47040b57cec5SDimitry Andric #define EXPR(Type, Base)
47050b57cec5SDimitry Andric #define STMT(Type, Base) \
47060b57cec5SDimitry Andric   case Expr::Type##Class:
47070b57cec5SDimitry Andric #include "clang/AST/StmtNodes.inc"
47080b57cec5SDimitry Andric     // fallthrough
47090b57cec5SDimitry Andric 
47100b57cec5SDimitry Andric   // These all can only appear in local or variable-initialization
47110b57cec5SDimitry Andric   // contexts and so should never appear in a mangling.
47120b57cec5SDimitry Andric   case Expr::AddrLabelExprClass:
47130b57cec5SDimitry Andric   case Expr::DesignatedInitUpdateExprClass:
47140b57cec5SDimitry Andric   case Expr::ImplicitValueInitExprClass:
47150b57cec5SDimitry Andric   case Expr::ArrayInitLoopExprClass:
47160b57cec5SDimitry Andric   case Expr::ArrayInitIndexExprClass:
47170b57cec5SDimitry Andric   case Expr::NoInitExprClass:
47180b57cec5SDimitry Andric   case Expr::ParenListExprClass:
47190b57cec5SDimitry Andric   case Expr::MSPropertyRefExprClass:
47200b57cec5SDimitry Andric   case Expr::MSPropertySubscriptExprClass:
47210b57cec5SDimitry Andric   case Expr::TypoExprClass: // This should no longer exist in the AST by now.
47225ffd83dbSDimitry Andric   case Expr::RecoveryExprClass:
47230fca6ea1SDimitry Andric   case Expr::ArraySectionExprClass:
47245ffd83dbSDimitry Andric   case Expr::OMPArrayShapingExprClass:
47255ffd83dbSDimitry Andric   case Expr::OMPIteratorExprClass:
47260b57cec5SDimitry Andric   case Expr::CXXInheritedCtorInitExprClass:
4727bdd1243dSDimitry Andric   case Expr::CXXParenListInitExprClass:
47280fca6ea1SDimitry Andric   case Expr::PackIndexingExprClass:
47290b57cec5SDimitry Andric     llvm_unreachable("unexpected statement kind");
47300b57cec5SDimitry Andric 
47310b57cec5SDimitry Andric   case Expr::ConstantExprClass:
47320b57cec5SDimitry Andric     E = cast<ConstantExpr>(E)->getSubExpr();
47330b57cec5SDimitry Andric     goto recurse;
47340b57cec5SDimitry Andric 
47350b57cec5SDimitry Andric   // FIXME: invent manglings for all these.
47360b57cec5SDimitry Andric   case Expr::BlockExprClass:
47370b57cec5SDimitry Andric   case Expr::ChooseExprClass:
47380b57cec5SDimitry Andric   case Expr::CompoundLiteralExprClass:
47390b57cec5SDimitry Andric   case Expr::ExtVectorElementExprClass:
47400b57cec5SDimitry Andric   case Expr::GenericSelectionExprClass:
47410b57cec5SDimitry Andric   case Expr::ObjCEncodeExprClass:
47420b57cec5SDimitry Andric   case Expr::ObjCIsaExprClass:
47430b57cec5SDimitry Andric   case Expr::ObjCIvarRefExprClass:
47440b57cec5SDimitry Andric   case Expr::ObjCMessageExprClass:
47450b57cec5SDimitry Andric   case Expr::ObjCPropertyRefExprClass:
47460b57cec5SDimitry Andric   case Expr::ObjCProtocolExprClass:
47470b57cec5SDimitry Andric   case Expr::ObjCSelectorExprClass:
47480b57cec5SDimitry Andric   case Expr::ObjCStringLiteralClass:
47490b57cec5SDimitry Andric   case Expr::ObjCBoxedExprClass:
47500b57cec5SDimitry Andric   case Expr::ObjCArrayLiteralClass:
47510b57cec5SDimitry Andric   case Expr::ObjCDictionaryLiteralClass:
47520b57cec5SDimitry Andric   case Expr::ObjCSubscriptRefExprClass:
47530b57cec5SDimitry Andric   case Expr::ObjCIndirectCopyRestoreExprClass:
47540b57cec5SDimitry Andric   case Expr::ObjCAvailabilityCheckExprClass:
47550b57cec5SDimitry Andric   case Expr::OffsetOfExprClass:
47560b57cec5SDimitry Andric   case Expr::PredefinedExprClass:
47570b57cec5SDimitry Andric   case Expr::ShuffleVectorExprClass:
47580b57cec5SDimitry Andric   case Expr::ConvertVectorExprClass:
47590b57cec5SDimitry Andric   case Expr::StmtExprClass:
47600b57cec5SDimitry Andric   case Expr::ArrayTypeTraitExprClass:
47610b57cec5SDimitry Andric   case Expr::ExpressionTraitExprClass:
47620b57cec5SDimitry Andric   case Expr::VAArgExprClass:
47630b57cec5SDimitry Andric   case Expr::CUDAKernelCallExprClass:
47640b57cec5SDimitry Andric   case Expr::AsTypeExprClass:
47650b57cec5SDimitry Andric   case Expr::PseudoObjectExprClass:
47660b57cec5SDimitry Andric   case Expr::AtomicExprClass:
47670b57cec5SDimitry Andric   case Expr::SourceLocExprClass:
47680fca6ea1SDimitry Andric   case Expr::EmbedExprClass:
47690b57cec5SDimitry Andric   case Expr::BuiltinBitCastExprClass:
47700b57cec5SDimitry Andric   {
4771d409305fSDimitry Andric     NotPrimaryExpr();
47720b57cec5SDimitry Andric     if (!NullOut) {
47730b57cec5SDimitry Andric       // As bad as this diagnostic is, it's better than crashing.
47740b57cec5SDimitry Andric       DiagnosticsEngine &Diags = Context.getDiags();
47750b57cec5SDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
47760b57cec5SDimitry Andric                                        "cannot yet mangle expression type %0");
47770b57cec5SDimitry Andric       Diags.Report(E->getExprLoc(), DiagID)
47780b57cec5SDimitry Andric         << E->getStmtClassName() << E->getSourceRange();
4779d409305fSDimitry Andric       return;
47800b57cec5SDimitry Andric     }
47810b57cec5SDimitry Andric     break;
47820b57cec5SDimitry Andric   }
47830b57cec5SDimitry Andric 
47840b57cec5SDimitry Andric   case Expr::CXXUuidofExprClass: {
4785d409305fSDimitry Andric     NotPrimaryExpr();
47860b57cec5SDimitry Andric     const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4787d409305fSDimitry Andric     // As of clang 12, uuidof uses the vendor extended expression
4788d409305fSDimitry Andric     // mangling. Previously, it used a special-cased nonstandard extension.
47895f757f3fSDimitry Andric     if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
4790d409305fSDimitry Andric       Out << "u8__uuidof";
4791d409305fSDimitry Andric       if (UE->isTypeOperand())
4792d409305fSDimitry Andric         mangleType(UE->getTypeOperand(Context.getASTContext()));
4793d409305fSDimitry Andric       else
4794d409305fSDimitry Andric         mangleTemplateArgExpr(UE->getExprOperand());
4795d409305fSDimitry Andric       Out << 'E';
4796d409305fSDimitry Andric     } else {
47970b57cec5SDimitry Andric       if (UE->isTypeOperand()) {
47980b57cec5SDimitry Andric         QualType UuidT = UE->getTypeOperand(Context.getASTContext());
47990b57cec5SDimitry Andric         Out << "u8__uuidoft";
48000b57cec5SDimitry Andric         mangleType(UuidT);
48010b57cec5SDimitry Andric       } else {
48020b57cec5SDimitry Andric         Expr *UuidExp = UE->getExprOperand();
48030b57cec5SDimitry Andric         Out << "u8__uuidofz";
4804d409305fSDimitry Andric         mangleExpression(UuidExp);
4805d409305fSDimitry Andric       }
48060b57cec5SDimitry Andric     }
48070b57cec5SDimitry Andric     break;
48080b57cec5SDimitry Andric   }
48090b57cec5SDimitry Andric 
48100b57cec5SDimitry Andric   // Even gcc-4.5 doesn't mangle this.
48110b57cec5SDimitry Andric   case Expr::BinaryConditionalOperatorClass: {
4812d409305fSDimitry Andric     NotPrimaryExpr();
48130b57cec5SDimitry Andric     DiagnosticsEngine &Diags = Context.getDiags();
48140b57cec5SDimitry Andric     unsigned DiagID =
48150b57cec5SDimitry Andric       Diags.getCustomDiagID(DiagnosticsEngine::Error,
48160b57cec5SDimitry Andric                 "?: operator with omitted middle operand cannot be mangled");
48170b57cec5SDimitry Andric     Diags.Report(E->getExprLoc(), DiagID)
48180b57cec5SDimitry Andric       << E->getStmtClassName() << E->getSourceRange();
4819d409305fSDimitry Andric     return;
48200b57cec5SDimitry Andric   }
48210b57cec5SDimitry Andric 
48220b57cec5SDimitry Andric   // These are used for internal purposes and cannot be meaningfully mangled.
48230b57cec5SDimitry Andric   case Expr::OpaqueValueExprClass:
48240b57cec5SDimitry Andric     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
48250b57cec5SDimitry Andric 
48260b57cec5SDimitry Andric   case Expr::InitListExprClass: {
4827d409305fSDimitry Andric     NotPrimaryExpr();
48280b57cec5SDimitry Andric     Out << "il";
48290b57cec5SDimitry Andric     mangleInitListElements(cast<InitListExpr>(E));
48300b57cec5SDimitry Andric     Out << "E";
48310b57cec5SDimitry Andric     break;
48320b57cec5SDimitry Andric   }
48330b57cec5SDimitry Andric 
48340b57cec5SDimitry Andric   case Expr::DesignatedInitExprClass: {
4835d409305fSDimitry Andric     NotPrimaryExpr();
48360b57cec5SDimitry Andric     auto *DIE = cast<DesignatedInitExpr>(E);
48370b57cec5SDimitry Andric     for (const auto &Designator : DIE->designators()) {
48380b57cec5SDimitry Andric       if (Designator.isFieldDesignator()) {
48390b57cec5SDimitry Andric         Out << "di";
48400b57cec5SDimitry Andric         mangleSourceName(Designator.getFieldName());
48410b57cec5SDimitry Andric       } else if (Designator.isArrayDesignator()) {
48420b57cec5SDimitry Andric         Out << "dx";
48430b57cec5SDimitry Andric         mangleExpression(DIE->getArrayIndex(Designator));
48440b57cec5SDimitry Andric       } else {
48450b57cec5SDimitry Andric         assert(Designator.isArrayRangeDesignator() &&
48460b57cec5SDimitry Andric                "unknown designator kind");
48470b57cec5SDimitry Andric         Out << "dX";
48480b57cec5SDimitry Andric         mangleExpression(DIE->getArrayRangeStart(Designator));
48490b57cec5SDimitry Andric         mangleExpression(DIE->getArrayRangeEnd(Designator));
48500b57cec5SDimitry Andric       }
48510b57cec5SDimitry Andric     }
48520b57cec5SDimitry Andric     mangleExpression(DIE->getInit());
48530b57cec5SDimitry Andric     break;
48540b57cec5SDimitry Andric   }
48550b57cec5SDimitry Andric 
48560b57cec5SDimitry Andric   case Expr::CXXDefaultArgExprClass:
4857d409305fSDimitry Andric     E = cast<CXXDefaultArgExpr>(E)->getExpr();
4858d409305fSDimitry Andric     goto recurse;
48590b57cec5SDimitry Andric 
48600b57cec5SDimitry Andric   case Expr::CXXDefaultInitExprClass:
4861d409305fSDimitry Andric     E = cast<CXXDefaultInitExpr>(E)->getExpr();
4862d409305fSDimitry Andric     goto recurse;
48630b57cec5SDimitry Andric 
48640b57cec5SDimitry Andric   case Expr::CXXStdInitializerListExprClass:
4865d409305fSDimitry Andric     E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
4866d409305fSDimitry Andric     goto recurse;
48670b57cec5SDimitry Andric 
48687a6dacacSDimitry Andric   case Expr::SubstNonTypeTemplateParmExprClass: {
48697a6dacacSDimitry Andric     // Mangle a substituted parameter the same way we mangle the template
48707a6dacacSDimitry Andric     // argument.
48717a6dacacSDimitry Andric     auto *SNTTPE = cast<SubstNonTypeTemplateParmExpr>(E);
48727a6dacacSDimitry Andric     if (auto *CE = dyn_cast<ConstantExpr>(SNTTPE->getReplacement())) {
48737a6dacacSDimitry Andric       // Pull out the constant value and mangle it as a template argument.
48747a6dacacSDimitry Andric       QualType ParamType = SNTTPE->getParameterType(Context.getASTContext());
48757a6dacacSDimitry Andric       assert(CE->hasAPValueResult() && "expected the NTTP to have an APValue");
48767a6dacacSDimitry Andric       mangleValueInTemplateArg(ParamType, CE->getAPValueResult(), false,
48777a6dacacSDimitry Andric                                /*NeedExactType=*/true);
48787a6dacacSDimitry Andric       break;
48797a6dacacSDimitry Andric     }
48807a6dacacSDimitry Andric     // The remaining cases all happen to be substituted with expressions that
48817a6dacacSDimitry Andric     // mangle the same as a corresponding template argument anyway.
4882d409305fSDimitry Andric     E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
4883d409305fSDimitry Andric     goto recurse;
48847a6dacacSDimitry Andric   }
48850b57cec5SDimitry Andric 
48860b57cec5SDimitry Andric   case Expr::UserDefinedLiteralClass:
48870b57cec5SDimitry Andric     // We follow g++'s approach of mangling a UDL as a call to the literal
48880b57cec5SDimitry Andric     // operator.
48890b57cec5SDimitry Andric   case Expr::CXXMemberCallExprClass: // fallthrough
48900b57cec5SDimitry Andric   case Expr::CallExprClass: {
4891d409305fSDimitry Andric     NotPrimaryExpr();
48920b57cec5SDimitry Andric     const CallExpr *CE = cast<CallExpr>(E);
48930b57cec5SDimitry Andric 
48940b57cec5SDimitry Andric     // <expression> ::= cp <simple-id> <expression>* E
48950b57cec5SDimitry Andric     // We use this mangling only when the call would use ADL except
48960b57cec5SDimitry Andric     // for being parenthesized.  Per discussion with David
48970b57cec5SDimitry Andric     // Vandervoorde, 2011.04.25.
48980b57cec5SDimitry Andric     if (isParenthesizedADLCallee(CE)) {
48990b57cec5SDimitry Andric       Out << "cp";
49000b57cec5SDimitry Andric       // The callee here is a parenthesized UnresolvedLookupExpr with
49010b57cec5SDimitry Andric       // no qualifier and should always get mangled as a <simple-id>
49020b57cec5SDimitry Andric       // anyway.
49030b57cec5SDimitry Andric 
49040b57cec5SDimitry Andric     // <expression> ::= cl <expression>* E
49050b57cec5SDimitry Andric     } else {
49060b57cec5SDimitry Andric       Out << "cl";
49070b57cec5SDimitry Andric     }
49080b57cec5SDimitry Andric 
49090b57cec5SDimitry Andric     unsigned CallArity = CE->getNumArgs();
49100b57cec5SDimitry Andric     for (const Expr *Arg : CE->arguments())
49110b57cec5SDimitry Andric       if (isa<PackExpansionExpr>(Arg))
49120b57cec5SDimitry Andric         CallArity = UnknownArity;
49130b57cec5SDimitry Andric 
49140b57cec5SDimitry Andric     mangleExpression(CE->getCallee(), CallArity);
49150b57cec5SDimitry Andric     for (const Expr *Arg : CE->arguments())
49160b57cec5SDimitry Andric       mangleExpression(Arg);
49170b57cec5SDimitry Andric     Out << 'E';
49180b57cec5SDimitry Andric     break;
49190b57cec5SDimitry Andric   }
49200b57cec5SDimitry Andric 
49210b57cec5SDimitry Andric   case Expr::CXXNewExprClass: {
4922d409305fSDimitry Andric     NotPrimaryExpr();
49230b57cec5SDimitry Andric     const CXXNewExpr *New = cast<CXXNewExpr>(E);
49240b57cec5SDimitry Andric     if (New->isGlobalNew()) Out << "gs";
49250b57cec5SDimitry Andric     Out << (New->isArray() ? "na" : "nw");
49260b57cec5SDimitry Andric     for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
49270b57cec5SDimitry Andric            E = New->placement_arg_end(); I != E; ++I)
49280b57cec5SDimitry Andric       mangleExpression(*I);
49290b57cec5SDimitry Andric     Out << '_';
49300b57cec5SDimitry Andric     mangleType(New->getAllocatedType());
49310b57cec5SDimitry Andric     if (New->hasInitializer()) {
49327a6dacacSDimitry Andric       if (New->getInitializationStyle() == CXXNewInitializationStyle::Braces)
49330b57cec5SDimitry Andric         Out << "il";
49340b57cec5SDimitry Andric       else
49350b57cec5SDimitry Andric         Out << "pi";
49360b57cec5SDimitry Andric       const Expr *Init = New->getInitializer();
49370b57cec5SDimitry Andric       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
49380b57cec5SDimitry Andric         // Directly inline the initializers.
49390b57cec5SDimitry Andric         for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
49400b57cec5SDimitry Andric                                                   E = CCE->arg_end();
49410b57cec5SDimitry Andric              I != E; ++I)
49420b57cec5SDimitry Andric           mangleExpression(*I);
49430b57cec5SDimitry Andric       } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
49440b57cec5SDimitry Andric         for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
49450b57cec5SDimitry Andric           mangleExpression(PLE->getExpr(i));
49465f757f3fSDimitry Andric       } else if (New->getInitializationStyle() ==
49477a6dacacSDimitry Andric                      CXXNewInitializationStyle::Braces &&
49480b57cec5SDimitry Andric                  isa<InitListExpr>(Init)) {
49490b57cec5SDimitry Andric         // Only take InitListExprs apart for list-initialization.
49500b57cec5SDimitry Andric         mangleInitListElements(cast<InitListExpr>(Init));
49510b57cec5SDimitry Andric       } else
49520b57cec5SDimitry Andric         mangleExpression(Init);
49530b57cec5SDimitry Andric     }
49540b57cec5SDimitry Andric     Out << 'E';
49550b57cec5SDimitry Andric     break;
49560b57cec5SDimitry Andric   }
49570b57cec5SDimitry Andric 
49580b57cec5SDimitry Andric   case Expr::CXXPseudoDestructorExprClass: {
4959d409305fSDimitry Andric     NotPrimaryExpr();
49600b57cec5SDimitry Andric     const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
49610b57cec5SDimitry Andric     if (const Expr *Base = PDE->getBase())
49620b57cec5SDimitry Andric       mangleMemberExprBase(Base, PDE->isArrow());
49630b57cec5SDimitry Andric     NestedNameSpecifier *Qualifier = PDE->getQualifier();
49640b57cec5SDimitry Andric     if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
49650b57cec5SDimitry Andric       if (Qualifier) {
49660b57cec5SDimitry Andric         mangleUnresolvedPrefix(Qualifier,
49670b57cec5SDimitry Andric                                /*recursive=*/true);
49680b57cec5SDimitry Andric         mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
49690b57cec5SDimitry Andric         Out << 'E';
49700b57cec5SDimitry Andric       } else {
49710b57cec5SDimitry Andric         Out << "sr";
49720b57cec5SDimitry Andric         if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
49730b57cec5SDimitry Andric           Out << 'E';
49740b57cec5SDimitry Andric       }
49750b57cec5SDimitry Andric     } else if (Qualifier) {
49760b57cec5SDimitry Andric       mangleUnresolvedPrefix(Qualifier);
49770b57cec5SDimitry Andric     }
49780b57cec5SDimitry Andric     // <base-unresolved-name> ::= dn <destructor-name>
49790b57cec5SDimitry Andric     Out << "dn";
49800b57cec5SDimitry Andric     QualType DestroyedType = PDE->getDestroyedType();
49810b57cec5SDimitry Andric     mangleUnresolvedTypeOrSimpleId(DestroyedType);
49820b57cec5SDimitry Andric     break;
49830b57cec5SDimitry Andric   }
49840b57cec5SDimitry Andric 
49850b57cec5SDimitry Andric   case Expr::MemberExprClass: {
4986d409305fSDimitry Andric     NotPrimaryExpr();
49870b57cec5SDimitry Andric     const MemberExpr *ME = cast<MemberExpr>(E);
49880b57cec5SDimitry Andric     mangleMemberExpr(ME->getBase(), ME->isArrow(),
49890b57cec5SDimitry Andric                      ME->getQualifier(), nullptr,
49900b57cec5SDimitry Andric                      ME->getMemberDecl()->getDeclName(),
49910b57cec5SDimitry Andric                      ME->getTemplateArgs(), ME->getNumTemplateArgs(),
49920b57cec5SDimitry Andric                      Arity);
49930b57cec5SDimitry Andric     break;
49940b57cec5SDimitry Andric   }
49950b57cec5SDimitry Andric 
49960b57cec5SDimitry Andric   case Expr::UnresolvedMemberExprClass: {
4997d409305fSDimitry Andric     NotPrimaryExpr();
49980b57cec5SDimitry Andric     const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
49990b57cec5SDimitry Andric     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
50000b57cec5SDimitry Andric                      ME->isArrow(), ME->getQualifier(), nullptr,
50010b57cec5SDimitry Andric                      ME->getMemberName(),
50020b57cec5SDimitry Andric                      ME->getTemplateArgs(), ME->getNumTemplateArgs(),
50030b57cec5SDimitry Andric                      Arity);
50040b57cec5SDimitry Andric     break;
50050b57cec5SDimitry Andric   }
50060b57cec5SDimitry Andric 
50070b57cec5SDimitry Andric   case Expr::CXXDependentScopeMemberExprClass: {
5008d409305fSDimitry Andric     NotPrimaryExpr();
50090b57cec5SDimitry Andric     const CXXDependentScopeMemberExpr *ME
50100b57cec5SDimitry Andric       = cast<CXXDependentScopeMemberExpr>(E);
50110b57cec5SDimitry Andric     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
50120b57cec5SDimitry Andric                      ME->isArrow(), ME->getQualifier(),
50130b57cec5SDimitry Andric                      ME->getFirstQualifierFoundInScope(),
50140b57cec5SDimitry Andric                      ME->getMember(),
50150b57cec5SDimitry Andric                      ME->getTemplateArgs(), ME->getNumTemplateArgs(),
50160b57cec5SDimitry Andric                      Arity);
50170b57cec5SDimitry Andric     break;
50180b57cec5SDimitry Andric   }
50190b57cec5SDimitry Andric 
50200b57cec5SDimitry Andric   case Expr::UnresolvedLookupExprClass: {
5021d409305fSDimitry Andric     NotPrimaryExpr();
50220b57cec5SDimitry Andric     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
50230b57cec5SDimitry Andric     mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
50240b57cec5SDimitry Andric                          ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
50250b57cec5SDimitry Andric                          Arity);
50260b57cec5SDimitry Andric     break;
50270b57cec5SDimitry Andric   }
50280b57cec5SDimitry Andric 
50290b57cec5SDimitry Andric   case Expr::CXXUnresolvedConstructExprClass: {
5030d409305fSDimitry Andric     NotPrimaryExpr();
50310b57cec5SDimitry Andric     const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
5032e8d8bef9SDimitry Andric     unsigned N = CE->getNumArgs();
50330b57cec5SDimitry Andric 
50340b57cec5SDimitry Andric     if (CE->isListInitialization()) {
50350b57cec5SDimitry Andric       assert(N == 1 && "unexpected form for list initialization");
50360b57cec5SDimitry Andric       auto *IL = cast<InitListExpr>(CE->getArg(0));
50370b57cec5SDimitry Andric       Out << "tl";
50380b57cec5SDimitry Andric       mangleType(CE->getType());
50390b57cec5SDimitry Andric       mangleInitListElements(IL);
50400b57cec5SDimitry Andric       Out << "E";
5041d409305fSDimitry Andric       break;
50420b57cec5SDimitry Andric     }
50430b57cec5SDimitry Andric 
50440b57cec5SDimitry Andric     Out << "cv";
50450b57cec5SDimitry Andric     mangleType(CE->getType());
50460b57cec5SDimitry Andric     if (N != 1) Out << '_';
50470b57cec5SDimitry Andric     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
50480b57cec5SDimitry Andric     if (N != 1) Out << 'E';
50490b57cec5SDimitry Andric     break;
50500b57cec5SDimitry Andric   }
50510b57cec5SDimitry Andric 
50520b57cec5SDimitry Andric   case Expr::CXXConstructExprClass: {
5053d409305fSDimitry Andric     // An implicit cast is silent, thus may contain <expr-primary>.
50540b57cec5SDimitry Andric     const auto *CE = cast<CXXConstructExpr>(E);
50550b57cec5SDimitry Andric     if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
50560b57cec5SDimitry Andric       assert(
50570b57cec5SDimitry Andric           CE->getNumArgs() >= 1 &&
50580b57cec5SDimitry Andric           (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
50590b57cec5SDimitry Andric           "implicit CXXConstructExpr must have one argument");
5060d409305fSDimitry Andric       E = cast<CXXConstructExpr>(E)->getArg(0);
5061d409305fSDimitry Andric       goto recurse;
50620b57cec5SDimitry Andric     }
5063d409305fSDimitry Andric     NotPrimaryExpr();
50640b57cec5SDimitry Andric     Out << "il";
50650b57cec5SDimitry Andric     for (auto *E : CE->arguments())
50660b57cec5SDimitry Andric       mangleExpression(E);
50670b57cec5SDimitry Andric     Out << "E";
50680b57cec5SDimitry Andric     break;
50690b57cec5SDimitry Andric   }
50700b57cec5SDimitry Andric 
50710b57cec5SDimitry Andric   case Expr::CXXTemporaryObjectExprClass: {
5072d409305fSDimitry Andric     NotPrimaryExpr();
50730b57cec5SDimitry Andric     const auto *CE = cast<CXXTemporaryObjectExpr>(E);
50740b57cec5SDimitry Andric     unsigned N = CE->getNumArgs();
50750b57cec5SDimitry Andric     bool List = CE->isListInitialization();
50760b57cec5SDimitry Andric 
50770b57cec5SDimitry Andric     if (List)
50780b57cec5SDimitry Andric       Out << "tl";
50790b57cec5SDimitry Andric     else
50800b57cec5SDimitry Andric       Out << "cv";
50810b57cec5SDimitry Andric     mangleType(CE->getType());
50820b57cec5SDimitry Andric     if (!List && N != 1)
50830b57cec5SDimitry Andric       Out << '_';
50840b57cec5SDimitry Andric     if (CE->isStdInitListInitialization()) {
50850b57cec5SDimitry Andric       // We implicitly created a std::initializer_list<T> for the first argument
50860b57cec5SDimitry Andric       // of a constructor of type U in an expression of the form U{a, b, c}.
50870b57cec5SDimitry Andric       // Strip all the semantic gunk off the initializer list.
50880b57cec5SDimitry Andric       auto *SILE =
50890b57cec5SDimitry Andric           cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
50900b57cec5SDimitry Andric       auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
50910b57cec5SDimitry Andric       mangleInitListElements(ILE);
50920b57cec5SDimitry Andric     } else {
50930b57cec5SDimitry Andric       for (auto *E : CE->arguments())
50940b57cec5SDimitry Andric         mangleExpression(E);
50950b57cec5SDimitry Andric     }
50960b57cec5SDimitry Andric     if (List || N != 1)
50970b57cec5SDimitry Andric       Out << 'E';
50980b57cec5SDimitry Andric     break;
50990b57cec5SDimitry Andric   }
51000b57cec5SDimitry Andric 
51010b57cec5SDimitry Andric   case Expr::CXXScalarValueInitExprClass:
5102d409305fSDimitry Andric     NotPrimaryExpr();
51030b57cec5SDimitry Andric     Out << "cv";
51040b57cec5SDimitry Andric     mangleType(E->getType());
51050b57cec5SDimitry Andric     Out << "_E";
51060b57cec5SDimitry Andric     break;
51070b57cec5SDimitry Andric 
51080b57cec5SDimitry Andric   case Expr::CXXNoexceptExprClass:
5109d409305fSDimitry Andric     NotPrimaryExpr();
51100b57cec5SDimitry Andric     Out << "nx";
51110b57cec5SDimitry Andric     mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
51120b57cec5SDimitry Andric     break;
51130b57cec5SDimitry Andric 
51140b57cec5SDimitry Andric   case Expr::UnaryExprOrTypeTraitExprClass: {
5115d409305fSDimitry Andric     // Non-instantiation-dependent traits are an <expr-primary> integer literal.
51160b57cec5SDimitry Andric     const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
51170b57cec5SDimitry Andric 
51180b57cec5SDimitry Andric     if (!SAE->isInstantiationDependent()) {
51190b57cec5SDimitry Andric       // Itanium C++ ABI:
51200b57cec5SDimitry Andric       //   If the operand of a sizeof or alignof operator is not
51210b57cec5SDimitry Andric       //   instantiation-dependent it is encoded as an integer literal
51220b57cec5SDimitry Andric       //   reflecting the result of the operator.
51230b57cec5SDimitry Andric       //
51240b57cec5SDimitry Andric       //   If the result of the operator is implicitly converted to a known
51250b57cec5SDimitry Andric       //   integer type, that type is used for the literal; otherwise, the type
51260b57cec5SDimitry Andric       //   of std::size_t or std::ptrdiff_t is used.
51275f757f3fSDimitry Andric       //
51285f757f3fSDimitry Andric       // FIXME: We still include the operand in the profile in this case. This
51295f757f3fSDimitry Andric       // can lead to mangling collisions between function templates that we
51305f757f3fSDimitry Andric       // consider to be different.
51310b57cec5SDimitry Andric       QualType T = (ImplicitlyConvertedToType.isNull() ||
51320b57cec5SDimitry Andric                     !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
51330b57cec5SDimitry Andric                                                     : ImplicitlyConvertedToType;
51340b57cec5SDimitry Andric       llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
51350b57cec5SDimitry Andric       mangleIntegerLiteral(T, V);
51360b57cec5SDimitry Andric       break;
51370b57cec5SDimitry Andric     }
51380b57cec5SDimitry Andric 
5139d409305fSDimitry Andric     NotPrimaryExpr(); // But otherwise, they are not.
5140d409305fSDimitry Andric 
5141d409305fSDimitry Andric     auto MangleAlignofSizeofArg = [&] {
5142d409305fSDimitry Andric       if (SAE->isArgumentType()) {
5143d409305fSDimitry Andric         Out << 't';
5144d409305fSDimitry Andric         mangleType(SAE->getArgumentType());
5145d409305fSDimitry Andric       } else {
5146d409305fSDimitry Andric         Out << 'z';
5147d409305fSDimitry Andric         mangleExpression(SAE->getArgumentExpr());
5148d409305fSDimitry Andric       }
5149d409305fSDimitry Andric     };
5150d409305fSDimitry Andric 
51510b57cec5SDimitry Andric     switch(SAE->getKind()) {
51520b57cec5SDimitry Andric     case UETT_SizeOf:
51530b57cec5SDimitry Andric       Out << 's';
5154d409305fSDimitry Andric       MangleAlignofSizeofArg();
51550b57cec5SDimitry Andric       break;
51560b57cec5SDimitry Andric     case UETT_PreferredAlignOf:
5157d409305fSDimitry Andric       // As of clang 12, we mangle __alignof__ differently than alignof. (They
5158d409305fSDimitry Andric       // have acted differently since Clang 8, but were previously mangled the
5159d409305fSDimitry Andric       // same.)
51605f757f3fSDimitry Andric       if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
5161d409305fSDimitry Andric         Out << "u11__alignof__";
5162d409305fSDimitry Andric         if (SAE->isArgumentType())
5163d409305fSDimitry Andric           mangleType(SAE->getArgumentType());
5164d409305fSDimitry Andric         else
5165d409305fSDimitry Andric           mangleTemplateArgExpr(SAE->getArgumentExpr());
5166d409305fSDimitry Andric         Out << 'E';
5167d409305fSDimitry Andric         break;
5168d409305fSDimitry Andric       }
5169bdd1243dSDimitry Andric       [[fallthrough]];
51700b57cec5SDimitry Andric     case UETT_AlignOf:
51710b57cec5SDimitry Andric       Out << 'a';
5172d409305fSDimitry Andric       MangleAlignofSizeofArg();
51730b57cec5SDimitry Andric       break;
51745f757f3fSDimitry Andric     case UETT_DataSizeOf: {
51755f757f3fSDimitry Andric       DiagnosticsEngine &Diags = Context.getDiags();
51765f757f3fSDimitry Andric       unsigned DiagID =
51775f757f3fSDimitry Andric           Diags.getCustomDiagID(DiagnosticsEngine::Error,
51785f757f3fSDimitry Andric                                 "cannot yet mangle __datasizeof expression");
51795f757f3fSDimitry Andric       Diags.Report(DiagID);
51805f757f3fSDimitry Andric       return;
51815f757f3fSDimitry Andric     }
5182*36b606aeSDimitry Andric     case UETT_PtrAuthTypeDiscriminator: {
5183*36b606aeSDimitry Andric       DiagnosticsEngine &Diags = Context.getDiags();
5184*36b606aeSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(
5185*36b606aeSDimitry Andric           DiagnosticsEngine::Error,
5186*36b606aeSDimitry Andric           "cannot yet mangle __builtin_ptrauth_type_discriminator expression");
5187*36b606aeSDimitry Andric       Diags.Report(E->getExprLoc(), DiagID);
5188*36b606aeSDimitry Andric       return;
5189*36b606aeSDimitry Andric     }
51900b57cec5SDimitry Andric     case UETT_VecStep: {
51910b57cec5SDimitry Andric       DiagnosticsEngine &Diags = Context.getDiags();
51920b57cec5SDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
51930b57cec5SDimitry Andric                                      "cannot yet mangle vec_step expression");
51940b57cec5SDimitry Andric       Diags.Report(DiagID);
51950b57cec5SDimitry Andric       return;
51960b57cec5SDimitry Andric     }
51970b57cec5SDimitry Andric     case UETT_OpenMPRequiredSimdAlign: {
51980b57cec5SDimitry Andric       DiagnosticsEngine &Diags = Context.getDiags();
51990b57cec5SDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(
52000b57cec5SDimitry Andric           DiagnosticsEngine::Error,
52010b57cec5SDimitry Andric           "cannot yet mangle __builtin_omp_required_simd_align expression");
52020b57cec5SDimitry Andric       Diags.Report(DiagID);
52030b57cec5SDimitry Andric       return;
52040b57cec5SDimitry Andric     }
52055f757f3fSDimitry Andric     case UETT_VectorElements: {
52065f757f3fSDimitry Andric       DiagnosticsEngine &Diags = Context.getDiags();
52075f757f3fSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(
52085f757f3fSDimitry Andric           DiagnosticsEngine::Error,
52095f757f3fSDimitry Andric           "cannot yet mangle __builtin_vectorelements expression");
52105f757f3fSDimitry Andric       Diags.Report(DiagID);
52115f757f3fSDimitry Andric       return;
52120b57cec5SDimitry Andric     }
52135f757f3fSDimitry Andric     }
52145f757f3fSDimitry Andric     break;
52155f757f3fSDimitry Andric   }
52165f757f3fSDimitry Andric 
52175f757f3fSDimitry Andric   case Expr::TypeTraitExprClass: {
52185f757f3fSDimitry Andric     //  <expression> ::= u <source-name> <template-arg>* E # vendor extension
52195f757f3fSDimitry Andric     const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);
52205f757f3fSDimitry Andric     NotPrimaryExpr();
52215f757f3fSDimitry Andric     Out << 'u';
52225f757f3fSDimitry Andric     llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());
52235f757f3fSDimitry Andric     Out << Spelling.size() << Spelling;
52245f757f3fSDimitry Andric     for (TypeSourceInfo *TSI : TTE->getArgs()) {
52255f757f3fSDimitry Andric       mangleType(TSI->getType());
52265f757f3fSDimitry Andric     }
52275f757f3fSDimitry Andric     Out << 'E';
52280b57cec5SDimitry Andric     break;
52290b57cec5SDimitry Andric   }
52300b57cec5SDimitry Andric 
52310b57cec5SDimitry Andric   case Expr::CXXThrowExprClass: {
5232d409305fSDimitry Andric     NotPrimaryExpr();
52330b57cec5SDimitry Andric     const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
52340b57cec5SDimitry Andric     //  <expression> ::= tw <expression>  # throw expression
52350b57cec5SDimitry Andric     //               ::= tr               # rethrow
52360b57cec5SDimitry Andric     if (TE->getSubExpr()) {
52370b57cec5SDimitry Andric       Out << "tw";
52380b57cec5SDimitry Andric       mangleExpression(TE->getSubExpr());
52390b57cec5SDimitry Andric     } else {
52400b57cec5SDimitry Andric       Out << "tr";
52410b57cec5SDimitry Andric     }
52420b57cec5SDimitry Andric     break;
52430b57cec5SDimitry Andric   }
52440b57cec5SDimitry Andric 
52450b57cec5SDimitry Andric   case Expr::CXXTypeidExprClass: {
5246d409305fSDimitry Andric     NotPrimaryExpr();
52470b57cec5SDimitry Andric     const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
52480b57cec5SDimitry Andric     //  <expression> ::= ti <type>        # typeid (type)
52490b57cec5SDimitry Andric     //               ::= te <expression>  # typeid (expression)
52500b57cec5SDimitry Andric     if (TIE->isTypeOperand()) {
52510b57cec5SDimitry Andric       Out << "ti";
52520b57cec5SDimitry Andric       mangleType(TIE->getTypeOperand(Context.getASTContext()));
52530b57cec5SDimitry Andric     } else {
52540b57cec5SDimitry Andric       Out << "te";
52550b57cec5SDimitry Andric       mangleExpression(TIE->getExprOperand());
52560b57cec5SDimitry Andric     }
52570b57cec5SDimitry Andric     break;
52580b57cec5SDimitry Andric   }
52590b57cec5SDimitry Andric 
52600b57cec5SDimitry Andric   case Expr::CXXDeleteExprClass: {
5261d409305fSDimitry Andric     NotPrimaryExpr();
52620b57cec5SDimitry Andric     const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
52630b57cec5SDimitry Andric     //  <expression> ::= [gs] dl <expression>  # [::] delete expr
52640b57cec5SDimitry Andric     //               ::= [gs] da <expression>  # [::] delete [] expr
52650b57cec5SDimitry Andric     if (DE->isGlobalDelete()) Out << "gs";
52660b57cec5SDimitry Andric     Out << (DE->isArrayForm() ? "da" : "dl");
52670b57cec5SDimitry Andric     mangleExpression(DE->getArgument());
52680b57cec5SDimitry Andric     break;
52690b57cec5SDimitry Andric   }
52700b57cec5SDimitry Andric 
52710b57cec5SDimitry Andric   case Expr::UnaryOperatorClass: {
5272d409305fSDimitry Andric     NotPrimaryExpr();
52730b57cec5SDimitry Andric     const UnaryOperator *UO = cast<UnaryOperator>(E);
52740b57cec5SDimitry Andric     mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
52750b57cec5SDimitry Andric                        /*Arity=*/1);
52760b57cec5SDimitry Andric     mangleExpression(UO->getSubExpr());
52770b57cec5SDimitry Andric     break;
52780b57cec5SDimitry Andric   }
52790b57cec5SDimitry Andric 
52800b57cec5SDimitry Andric   case Expr::ArraySubscriptExprClass: {
5281d409305fSDimitry Andric     NotPrimaryExpr();
52820b57cec5SDimitry Andric     const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
52830b57cec5SDimitry Andric 
52840b57cec5SDimitry Andric     // Array subscript is treated as a syntactically weird form of
52850b57cec5SDimitry Andric     // binary operator.
52860b57cec5SDimitry Andric     Out << "ix";
52870b57cec5SDimitry Andric     mangleExpression(AE->getLHS());
52880b57cec5SDimitry Andric     mangleExpression(AE->getRHS());
52890b57cec5SDimitry Andric     break;
52900b57cec5SDimitry Andric   }
52910b57cec5SDimitry Andric 
52925ffd83dbSDimitry Andric   case Expr::MatrixSubscriptExprClass: {
5293d409305fSDimitry Andric     NotPrimaryExpr();
52945ffd83dbSDimitry Andric     const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
52955ffd83dbSDimitry Andric     Out << "ixix";
52965ffd83dbSDimitry Andric     mangleExpression(ME->getBase());
52975ffd83dbSDimitry Andric     mangleExpression(ME->getRowIdx());
52985ffd83dbSDimitry Andric     mangleExpression(ME->getColumnIdx());
52995ffd83dbSDimitry Andric     break;
53005ffd83dbSDimitry Andric   }
53015ffd83dbSDimitry Andric 
53020b57cec5SDimitry Andric   case Expr::CompoundAssignOperatorClass: // fallthrough
53030b57cec5SDimitry Andric   case Expr::BinaryOperatorClass: {
5304d409305fSDimitry Andric     NotPrimaryExpr();
53050b57cec5SDimitry Andric     const BinaryOperator *BO = cast<BinaryOperator>(E);
53060b57cec5SDimitry Andric     if (BO->getOpcode() == BO_PtrMemD)
53070b57cec5SDimitry Andric       Out << "ds";
53080b57cec5SDimitry Andric     else
53090b57cec5SDimitry Andric       mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
53100b57cec5SDimitry Andric                          /*Arity=*/2);
53110b57cec5SDimitry Andric     mangleExpression(BO->getLHS());
53120b57cec5SDimitry Andric     mangleExpression(BO->getRHS());
53130b57cec5SDimitry Andric     break;
53140b57cec5SDimitry Andric   }
53150b57cec5SDimitry Andric 
5316a7dea167SDimitry Andric   case Expr::CXXRewrittenBinaryOperatorClass: {
5317d409305fSDimitry Andric     NotPrimaryExpr();
5318a7dea167SDimitry Andric     // The mangled form represents the original syntax.
5319a7dea167SDimitry Andric     CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
5320a7dea167SDimitry Andric         cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
5321a7dea167SDimitry Andric     mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
5322a7dea167SDimitry Andric                        /*Arity=*/2);
5323a7dea167SDimitry Andric     mangleExpression(Decomposed.LHS);
5324a7dea167SDimitry Andric     mangleExpression(Decomposed.RHS);
5325a7dea167SDimitry Andric     break;
5326a7dea167SDimitry Andric   }
5327a7dea167SDimitry Andric 
53280b57cec5SDimitry Andric   case Expr::ConditionalOperatorClass: {
5329d409305fSDimitry Andric     NotPrimaryExpr();
53300b57cec5SDimitry Andric     const ConditionalOperator *CO = cast<ConditionalOperator>(E);
53310b57cec5SDimitry Andric     mangleOperatorName(OO_Conditional, /*Arity=*/3);
53320b57cec5SDimitry Andric     mangleExpression(CO->getCond());
53330b57cec5SDimitry Andric     mangleExpression(CO->getLHS(), Arity);
53340b57cec5SDimitry Andric     mangleExpression(CO->getRHS(), Arity);
53350b57cec5SDimitry Andric     break;
53360b57cec5SDimitry Andric   }
53370b57cec5SDimitry Andric 
53380b57cec5SDimitry Andric   case Expr::ImplicitCastExprClass: {
53390b57cec5SDimitry Andric     ImplicitlyConvertedToType = E->getType();
53400b57cec5SDimitry Andric     E = cast<ImplicitCastExpr>(E)->getSubExpr();
53410b57cec5SDimitry Andric     goto recurse;
53420b57cec5SDimitry Andric   }
53430b57cec5SDimitry Andric 
53440b57cec5SDimitry Andric   case Expr::ObjCBridgedCastExprClass: {
5345d409305fSDimitry Andric     NotPrimaryExpr();
53460b57cec5SDimitry Andric     // Mangle ownership casts as a vendor extended operator __bridge,
53470b57cec5SDimitry Andric     // __bridge_transfer, or __bridge_retain.
53480b57cec5SDimitry Andric     StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
53490b57cec5SDimitry Andric     Out << "v1U" << Kind.size() << Kind;
5350d409305fSDimitry Andric     mangleCastExpression(E, "cv");
5351d409305fSDimitry Andric     break;
53520b57cec5SDimitry Andric   }
53530b57cec5SDimitry Andric 
53540b57cec5SDimitry Andric   case Expr::CStyleCastExprClass:
5355d409305fSDimitry Andric     NotPrimaryExpr();
53560b57cec5SDimitry Andric     mangleCastExpression(E, "cv");
53570b57cec5SDimitry Andric     break;
53580b57cec5SDimitry Andric 
53590b57cec5SDimitry Andric   case Expr::CXXFunctionalCastExprClass: {
5360d409305fSDimitry Andric     NotPrimaryExpr();
53610b57cec5SDimitry Andric     auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
53620b57cec5SDimitry Andric     // FIXME: Add isImplicit to CXXConstructExpr.
53630b57cec5SDimitry Andric     if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
53640b57cec5SDimitry Andric       if (CCE->getParenOrBraceRange().isInvalid())
53650b57cec5SDimitry Andric         Sub = CCE->getArg(0)->IgnoreImplicit();
53660b57cec5SDimitry Andric     if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
53670b57cec5SDimitry Andric       Sub = StdInitList->getSubExpr()->IgnoreImplicit();
53680b57cec5SDimitry Andric     if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
53690b57cec5SDimitry Andric       Out << "tl";
53700b57cec5SDimitry Andric       mangleType(E->getType());
53710b57cec5SDimitry Andric       mangleInitListElements(IL);
53720b57cec5SDimitry Andric       Out << "E";
53730b57cec5SDimitry Andric     } else {
53740b57cec5SDimitry Andric       mangleCastExpression(E, "cv");
53750b57cec5SDimitry Andric     }
53760b57cec5SDimitry Andric     break;
53770b57cec5SDimitry Andric   }
53780b57cec5SDimitry Andric 
53790b57cec5SDimitry Andric   case Expr::CXXStaticCastExprClass:
5380d409305fSDimitry Andric     NotPrimaryExpr();
53810b57cec5SDimitry Andric     mangleCastExpression(E, "sc");
53820b57cec5SDimitry Andric     break;
53830b57cec5SDimitry Andric   case Expr::CXXDynamicCastExprClass:
5384d409305fSDimitry Andric     NotPrimaryExpr();
53850b57cec5SDimitry Andric     mangleCastExpression(E, "dc");
53860b57cec5SDimitry Andric     break;
53870b57cec5SDimitry Andric   case Expr::CXXReinterpretCastExprClass:
5388d409305fSDimitry Andric     NotPrimaryExpr();
53890b57cec5SDimitry Andric     mangleCastExpression(E, "rc");
53900b57cec5SDimitry Andric     break;
53910b57cec5SDimitry Andric   case Expr::CXXConstCastExprClass:
5392d409305fSDimitry Andric     NotPrimaryExpr();
53930b57cec5SDimitry Andric     mangleCastExpression(E, "cc");
53940b57cec5SDimitry Andric     break;
53955ffd83dbSDimitry Andric   case Expr::CXXAddrspaceCastExprClass:
5396d409305fSDimitry Andric     NotPrimaryExpr();
53975ffd83dbSDimitry Andric     mangleCastExpression(E, "ac");
53985ffd83dbSDimitry Andric     break;
53990b57cec5SDimitry Andric 
54000b57cec5SDimitry Andric   case Expr::CXXOperatorCallExprClass: {
5401d409305fSDimitry Andric     NotPrimaryExpr();
54020b57cec5SDimitry Andric     const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
54030b57cec5SDimitry Andric     unsigned NumArgs = CE->getNumArgs();
54040b57cec5SDimitry Andric     // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
54050b57cec5SDimitry Andric     // (the enclosing MemberExpr covers the syntactic portion).
54060b57cec5SDimitry Andric     if (CE->getOperator() != OO_Arrow)
54070b57cec5SDimitry Andric       mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
54080b57cec5SDimitry Andric     // Mangle the arguments.
54090b57cec5SDimitry Andric     for (unsigned i = 0; i != NumArgs; ++i)
54100b57cec5SDimitry Andric       mangleExpression(CE->getArg(i));
54110b57cec5SDimitry Andric     break;
54120b57cec5SDimitry Andric   }
54130b57cec5SDimitry Andric 
54140b57cec5SDimitry Andric   case Expr::ParenExprClass:
5415d409305fSDimitry Andric     E = cast<ParenExpr>(E)->getSubExpr();
5416d409305fSDimitry Andric     goto recurse;
5417a7dea167SDimitry Andric 
5418a7dea167SDimitry Andric   case Expr::ConceptSpecializationExprClass: {
5419a7dea167SDimitry Andric     auto *CSE = cast<ConceptSpecializationExpr>(E);
54205f757f3fSDimitry Andric     if (isCompatibleWith(LangOptions::ClangABI::Ver17)) {
54215f757f3fSDimitry Andric       // Clang 17 and before mangled concept-ids as if they resolved to an
54225f757f3fSDimitry Andric       // entity, meaning that references to enclosing template arguments don't
54235f757f3fSDimitry Andric       // work.
54245f757f3fSDimitry Andric       Out << "L_Z";
5425bdd1243dSDimitry Andric       mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
5426a7dea167SDimitry Andric       Out << 'E';
5427a7dea167SDimitry Andric       break;
5428a7dea167SDimitry Andric     }
54295f757f3fSDimitry Andric     // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
54305f757f3fSDimitry Andric     NotPrimaryExpr();
54315f757f3fSDimitry Andric     mangleUnresolvedName(
54325f757f3fSDimitry Andric         CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
54335f757f3fSDimitry Andric         CSE->getConceptNameInfo().getName(),
54345f757f3fSDimitry Andric         CSE->getTemplateArgsAsWritten()->getTemplateArgs(),
54355f757f3fSDimitry Andric         CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());
54365f757f3fSDimitry Andric     break;
54375f757f3fSDimitry Andric   }
54385f757f3fSDimitry Andric 
54395f757f3fSDimitry Andric   case Expr::RequiresExprClass: {
54405f757f3fSDimitry Andric     // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
54415f757f3fSDimitry Andric     auto *RE = cast<RequiresExpr>(E);
54425f757f3fSDimitry Andric     // This is a primary-expression in the C++ grammar, but does not have an
54435f757f3fSDimitry Andric     // <expr-primary> mangling (starting with 'L').
54445f757f3fSDimitry Andric     NotPrimaryExpr();
54455f757f3fSDimitry Andric     if (RE->getLParenLoc().isValid()) {
54465f757f3fSDimitry Andric       Out << "rQ";
54475f757f3fSDimitry Andric       FunctionTypeDepthState saved = FunctionTypeDepth.push();
54485f757f3fSDimitry Andric       if (RE->getLocalParameters().empty()) {
54495f757f3fSDimitry Andric         Out << 'v';
54505f757f3fSDimitry Andric       } else {
54515f757f3fSDimitry Andric         for (ParmVarDecl *Param : RE->getLocalParameters()) {
54525f757f3fSDimitry Andric           mangleType(Context.getASTContext().getSignatureParameterType(
54535f757f3fSDimitry Andric               Param->getType()));
54545f757f3fSDimitry Andric         }
54555f757f3fSDimitry Andric       }
54565f757f3fSDimitry Andric       Out << '_';
54575f757f3fSDimitry Andric 
54585f757f3fSDimitry Andric       // The rest of the mangling is in the immediate scope of the parameters.
54595f757f3fSDimitry Andric       FunctionTypeDepth.enterResultType();
54605f757f3fSDimitry Andric       for (const concepts::Requirement *Req : RE->getRequirements())
54615f757f3fSDimitry Andric         mangleRequirement(RE->getExprLoc(), Req);
54625f757f3fSDimitry Andric       FunctionTypeDepth.pop(saved);
54635f757f3fSDimitry Andric       Out << 'E';
54645f757f3fSDimitry Andric     } else {
54655f757f3fSDimitry Andric       Out << "rq";
54665f757f3fSDimitry Andric       for (const concepts::Requirement *Req : RE->getRequirements())
54675f757f3fSDimitry Andric         mangleRequirement(RE->getExprLoc(), Req);
54685f757f3fSDimitry Andric       Out << 'E';
54695f757f3fSDimitry Andric     }
54705f757f3fSDimitry Andric     break;
54715f757f3fSDimitry Andric   }
5472a7dea167SDimitry Andric 
54730b57cec5SDimitry Andric   case Expr::DeclRefExprClass:
5474d409305fSDimitry Andric     // MangleDeclRefExpr helper handles primary-vs-nonprimary
5475d409305fSDimitry Andric     MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
54760b57cec5SDimitry Andric     break;
54770b57cec5SDimitry Andric 
54780b57cec5SDimitry Andric   case Expr::SubstNonTypeTemplateParmPackExprClass:
5479d409305fSDimitry Andric     NotPrimaryExpr();
54800b57cec5SDimitry Andric     // FIXME: not clear how to mangle this!
54810b57cec5SDimitry Andric     // template <unsigned N...> class A {
54820b57cec5SDimitry Andric     //   template <class U...> void foo(U (&x)[N]...);
54830b57cec5SDimitry Andric     // };
54840b57cec5SDimitry Andric     Out << "_SUBSTPACK_";
54850b57cec5SDimitry Andric     break;
54860b57cec5SDimitry Andric 
54870b57cec5SDimitry Andric   case Expr::FunctionParmPackExprClass: {
5488d409305fSDimitry Andric     NotPrimaryExpr();
54890b57cec5SDimitry Andric     // FIXME: not clear how to mangle this!
54900b57cec5SDimitry Andric     const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
54910b57cec5SDimitry Andric     Out << "v110_SUBSTPACK";
5492d409305fSDimitry Andric     MangleDeclRefExpr(FPPE->getParameterPack());
54930b57cec5SDimitry Andric     break;
54940b57cec5SDimitry Andric   }
54950b57cec5SDimitry Andric 
54960b57cec5SDimitry Andric   case Expr::DependentScopeDeclRefExprClass: {
5497d409305fSDimitry Andric     NotPrimaryExpr();
54980b57cec5SDimitry Andric     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
54990b57cec5SDimitry Andric     mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
55000b57cec5SDimitry Andric                          DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
55010b57cec5SDimitry Andric                          Arity);
55020b57cec5SDimitry Andric     break;
55030b57cec5SDimitry Andric   }
55040b57cec5SDimitry Andric 
55050b57cec5SDimitry Andric   case Expr::CXXBindTemporaryExprClass:
5506d409305fSDimitry Andric     E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
5507d409305fSDimitry Andric     goto recurse;
55080b57cec5SDimitry Andric 
55090b57cec5SDimitry Andric   case Expr::ExprWithCleanupsClass:
5510d409305fSDimitry Andric     E = cast<ExprWithCleanups>(E)->getSubExpr();
5511d409305fSDimitry Andric     goto recurse;
55120b57cec5SDimitry Andric 
55130b57cec5SDimitry Andric   case Expr::FloatingLiteralClass: {
5514d409305fSDimitry Andric     // <expr-primary>
55150b57cec5SDimitry Andric     const FloatingLiteral *FL = cast<FloatingLiteral>(E);
5516e8d8bef9SDimitry Andric     mangleFloatLiteral(FL->getType(), FL->getValue());
55170b57cec5SDimitry Andric     break;
55180b57cec5SDimitry Andric   }
55190b57cec5SDimitry Andric 
5520e8d8bef9SDimitry Andric   case Expr::FixedPointLiteralClass:
5521d409305fSDimitry Andric     // Currently unimplemented -- might be <expr-primary> in future?
5522e8d8bef9SDimitry Andric     mangleFixedPointLiteral();
5523e8d8bef9SDimitry Andric     break;
5524e8d8bef9SDimitry Andric 
55250b57cec5SDimitry Andric   case Expr::CharacterLiteralClass:
5526d409305fSDimitry Andric     // <expr-primary>
55270b57cec5SDimitry Andric     Out << 'L';
55280b57cec5SDimitry Andric     mangleType(E->getType());
55290b57cec5SDimitry Andric     Out << cast<CharacterLiteral>(E)->getValue();
55300b57cec5SDimitry Andric     Out << 'E';
55310b57cec5SDimitry Andric     break;
55320b57cec5SDimitry Andric 
55330b57cec5SDimitry Andric   // FIXME. __objc_yes/__objc_no are mangled same as true/false
55340b57cec5SDimitry Andric   case Expr::ObjCBoolLiteralExprClass:
5535d409305fSDimitry Andric     // <expr-primary>
55360b57cec5SDimitry Andric     Out << "Lb";
55370b57cec5SDimitry Andric     Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
55380b57cec5SDimitry Andric     Out << 'E';
55390b57cec5SDimitry Andric     break;
55400b57cec5SDimitry Andric 
55410b57cec5SDimitry Andric   case Expr::CXXBoolLiteralExprClass:
5542d409305fSDimitry Andric     // <expr-primary>
55430b57cec5SDimitry Andric     Out << "Lb";
55440b57cec5SDimitry Andric     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
55450b57cec5SDimitry Andric     Out << 'E';
55460b57cec5SDimitry Andric     break;
55470b57cec5SDimitry Andric 
55480b57cec5SDimitry Andric   case Expr::IntegerLiteralClass: {
5549d409305fSDimitry Andric     // <expr-primary>
55500b57cec5SDimitry Andric     llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
55510b57cec5SDimitry Andric     if (E->getType()->isSignedIntegerType())
55520b57cec5SDimitry Andric       Value.setIsSigned(true);
55530b57cec5SDimitry Andric     mangleIntegerLiteral(E->getType(), Value);
55540b57cec5SDimitry Andric     break;
55550b57cec5SDimitry Andric   }
55560b57cec5SDimitry Andric 
55570b57cec5SDimitry Andric   case Expr::ImaginaryLiteralClass: {
5558d409305fSDimitry Andric     // <expr-primary>
55590b57cec5SDimitry Andric     const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
55600b57cec5SDimitry Andric     // Mangle as if a complex literal.
55610b57cec5SDimitry Andric     // Proposal from David Vandevoorde, 2010.06.30.
55620b57cec5SDimitry Andric     Out << 'L';
55630b57cec5SDimitry Andric     mangleType(E->getType());
55640b57cec5SDimitry Andric     if (const FloatingLiteral *Imag =
55650b57cec5SDimitry Andric           dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
55660b57cec5SDimitry Andric       // Mangle a floating-point zero of the appropriate type.
55670b57cec5SDimitry Andric       mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
55680b57cec5SDimitry Andric       Out << '_';
55690b57cec5SDimitry Andric       mangleFloat(Imag->getValue());
55700b57cec5SDimitry Andric     } else {
55710b57cec5SDimitry Andric       Out << "0_";
55720b57cec5SDimitry Andric       llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
55730b57cec5SDimitry Andric       if (IE->getSubExpr()->getType()->isSignedIntegerType())
55740b57cec5SDimitry Andric         Value.setIsSigned(true);
55750b57cec5SDimitry Andric       mangleNumber(Value);
55760b57cec5SDimitry Andric     }
55770b57cec5SDimitry Andric     Out << 'E';
55780b57cec5SDimitry Andric     break;
55790b57cec5SDimitry Andric   }
55800b57cec5SDimitry Andric 
55810b57cec5SDimitry Andric   case Expr::StringLiteralClass: {
5582d409305fSDimitry Andric     // <expr-primary>
55830b57cec5SDimitry Andric     // Revised proposal from David Vandervoorde, 2010.07.15.
55840b57cec5SDimitry Andric     Out << 'L';
55850b57cec5SDimitry Andric     assert(isa<ConstantArrayType>(E->getType()));
55860b57cec5SDimitry Andric     mangleType(E->getType());
55870b57cec5SDimitry Andric     Out << 'E';
55880b57cec5SDimitry Andric     break;
55890b57cec5SDimitry Andric   }
55900b57cec5SDimitry Andric 
55910b57cec5SDimitry Andric   case Expr::GNUNullExprClass:
5592d409305fSDimitry Andric     // <expr-primary>
5593a7dea167SDimitry Andric     // Mangle as if an integer literal 0.
5594e8d8bef9SDimitry Andric     mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
5595a7dea167SDimitry Andric     break;
55960b57cec5SDimitry Andric 
55970b57cec5SDimitry Andric   case Expr::CXXNullPtrLiteralExprClass: {
5598d409305fSDimitry Andric     // <expr-primary>
55990b57cec5SDimitry Andric     Out << "LDnE";
56000b57cec5SDimitry Andric     break;
56010b57cec5SDimitry Andric   }
56020b57cec5SDimitry Andric 
5603349cc55cSDimitry Andric   case Expr::LambdaExprClass: {
5604349cc55cSDimitry Andric     // A lambda-expression can't appear in the signature of an
5605349cc55cSDimitry Andric     // externally-visible declaration, so there's no standard mangling for
5606349cc55cSDimitry Andric     // this, but mangling as a literal of the closure type seems reasonable.
5607349cc55cSDimitry Andric     Out << "L";
5608349cc55cSDimitry Andric     mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
5609349cc55cSDimitry Andric     Out << "E";
5610349cc55cSDimitry Andric     break;
5611349cc55cSDimitry Andric   }
5612349cc55cSDimitry Andric 
56130b57cec5SDimitry Andric   case Expr::PackExpansionExprClass:
5614d409305fSDimitry Andric     NotPrimaryExpr();
56150b57cec5SDimitry Andric     Out << "sp";
56160b57cec5SDimitry Andric     mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
56170b57cec5SDimitry Andric     break;
56180b57cec5SDimitry Andric 
56190b57cec5SDimitry Andric   case Expr::SizeOfPackExprClass: {
5620d409305fSDimitry Andric     NotPrimaryExpr();
56210b57cec5SDimitry Andric     auto *SPE = cast<SizeOfPackExpr>(E);
56220b57cec5SDimitry Andric     if (SPE->isPartiallySubstituted()) {
56230b57cec5SDimitry Andric       Out << "sP";
56240b57cec5SDimitry Andric       for (const auto &A : SPE->getPartialArguments())
5625e8d8bef9SDimitry Andric         mangleTemplateArg(A, false);
56260b57cec5SDimitry Andric       Out << "E";
56270b57cec5SDimitry Andric       break;
56280b57cec5SDimitry Andric     }
56290b57cec5SDimitry Andric 
56300b57cec5SDimitry Andric     Out << "sZ";
56310b57cec5SDimitry Andric     const NamedDecl *Pack = SPE->getPack();
56320b57cec5SDimitry Andric     if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
5633a7dea167SDimitry Andric       mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
56340b57cec5SDimitry Andric     else if (const NonTypeTemplateParmDecl *NTTP
56350b57cec5SDimitry Andric                 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
5636a7dea167SDimitry Andric       mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
56370b57cec5SDimitry Andric     else if (const TemplateTemplateParmDecl *TempTP
56380b57cec5SDimitry Andric                                     = dyn_cast<TemplateTemplateParmDecl>(Pack))
5639a7dea167SDimitry Andric       mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
56400b57cec5SDimitry Andric     else
56410b57cec5SDimitry Andric       mangleFunctionParam(cast<ParmVarDecl>(Pack));
56420b57cec5SDimitry Andric     break;
56430b57cec5SDimitry Andric   }
56440b57cec5SDimitry Andric 
5645d409305fSDimitry Andric   case Expr::MaterializeTemporaryExprClass:
5646d409305fSDimitry Andric     E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5647d409305fSDimitry Andric     goto recurse;
56480b57cec5SDimitry Andric 
56490b57cec5SDimitry Andric   case Expr::CXXFoldExprClass: {
5650d409305fSDimitry Andric     NotPrimaryExpr();
56510b57cec5SDimitry Andric     auto *FE = cast<CXXFoldExpr>(E);
56520b57cec5SDimitry Andric     if (FE->isLeftFold())
56530b57cec5SDimitry Andric       Out << (FE->getInit() ? "fL" : "fl");
56540b57cec5SDimitry Andric     else
56550b57cec5SDimitry Andric       Out << (FE->getInit() ? "fR" : "fr");
56560b57cec5SDimitry Andric 
56570b57cec5SDimitry Andric     if (FE->getOperator() == BO_PtrMemD)
56580b57cec5SDimitry Andric       Out << "ds";
56590b57cec5SDimitry Andric     else
56600b57cec5SDimitry Andric       mangleOperatorName(
56610b57cec5SDimitry Andric           BinaryOperator::getOverloadedOperator(FE->getOperator()),
56620b57cec5SDimitry Andric           /*Arity=*/2);
56630b57cec5SDimitry Andric 
56640b57cec5SDimitry Andric     if (FE->getLHS())
56650b57cec5SDimitry Andric       mangleExpression(FE->getLHS());
56660b57cec5SDimitry Andric     if (FE->getRHS())
56670b57cec5SDimitry Andric       mangleExpression(FE->getRHS());
56680b57cec5SDimitry Andric     break;
56690b57cec5SDimitry Andric   }
56700b57cec5SDimitry Andric 
56710b57cec5SDimitry Andric   case Expr::CXXThisExprClass:
5672d409305fSDimitry Andric     NotPrimaryExpr();
56730b57cec5SDimitry Andric     Out << "fpT";
56740b57cec5SDimitry Andric     break;
56750b57cec5SDimitry Andric 
56760b57cec5SDimitry Andric   case Expr::CoawaitExprClass:
56770b57cec5SDimitry Andric     // FIXME: Propose a non-vendor mangling.
5678d409305fSDimitry Andric     NotPrimaryExpr();
56790b57cec5SDimitry Andric     Out << "v18co_await";
56800b57cec5SDimitry Andric     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
56810b57cec5SDimitry Andric     break;
56820b57cec5SDimitry Andric 
56830b57cec5SDimitry Andric   case Expr::DependentCoawaitExprClass:
56840b57cec5SDimitry Andric     // FIXME: Propose a non-vendor mangling.
5685d409305fSDimitry Andric     NotPrimaryExpr();
56860b57cec5SDimitry Andric     Out << "v18co_await";
56870b57cec5SDimitry Andric     mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
56880b57cec5SDimitry Andric     break;
56890b57cec5SDimitry Andric 
56900b57cec5SDimitry Andric   case Expr::CoyieldExprClass:
56910b57cec5SDimitry Andric     // FIXME: Propose a non-vendor mangling.
5692d409305fSDimitry Andric     NotPrimaryExpr();
56930b57cec5SDimitry Andric     Out << "v18co_yield";
56940b57cec5SDimitry Andric     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
56950b57cec5SDimitry Andric     break;
5696fe6060f1SDimitry Andric   case Expr::SYCLUniqueStableNameExprClass: {
5697fe6060f1SDimitry Andric     const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
5698fe6060f1SDimitry Andric     NotPrimaryExpr();
5699fe6060f1SDimitry Andric 
5700fe6060f1SDimitry Andric     Out << "u33__builtin_sycl_unique_stable_name";
5701fe6060f1SDimitry Andric     mangleType(USN->getTypeSourceInfo()->getType());
5702fe6060f1SDimitry Andric 
5703fe6060f1SDimitry Andric     Out << "E";
5704fe6060f1SDimitry Andric     break;
5705fe6060f1SDimitry Andric   }
57060b57cec5SDimitry Andric   }
5707d409305fSDimitry Andric 
5708d409305fSDimitry Andric   if (AsTemplateArg && !IsPrimaryExpr)
5709d409305fSDimitry Andric     Out << 'E';
57100b57cec5SDimitry Andric }
57110b57cec5SDimitry Andric 
57120b57cec5SDimitry Andric /// Mangle an expression which refers to a parameter variable.
57130b57cec5SDimitry Andric ///
57140b57cec5SDimitry Andric /// <expression>     ::= <function-param>
57150b57cec5SDimitry Andric /// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 0
57160b57cec5SDimitry Andric /// <function-param> ::= fp <top-level CV-qualifiers>
57170b57cec5SDimitry Andric ///                      <parameter-2 non-negative number> _ # L == 0, I > 0
57180b57cec5SDimitry Andric /// <function-param> ::= fL <L-1 non-negative number>
57190b57cec5SDimitry Andric ///                      p <top-level CV-qualifiers> _       # L > 0, I == 0
57200b57cec5SDimitry Andric /// <function-param> ::= fL <L-1 non-negative number>
57210b57cec5SDimitry Andric ///                      p <top-level CV-qualifiers>
57220b57cec5SDimitry Andric ///                      <I-1 non-negative number> _         # L > 0, I > 0
57230b57cec5SDimitry Andric ///
57240b57cec5SDimitry Andric /// L is the nesting depth of the parameter, defined as 1 if the
57250b57cec5SDimitry Andric /// parameter comes from the innermost function prototype scope
57260b57cec5SDimitry Andric /// enclosing the current context, 2 if from the next enclosing
57270b57cec5SDimitry Andric /// function prototype scope, and so on, with one special case: if
57280b57cec5SDimitry Andric /// we've processed the full parameter clause for the innermost
57290b57cec5SDimitry Andric /// function type, then L is one less.  This definition conveniently
57300b57cec5SDimitry Andric /// makes it irrelevant whether a function's result type was written
57310b57cec5SDimitry Andric /// trailing or leading, but is otherwise overly complicated; the
57320b57cec5SDimitry Andric /// numbering was first designed without considering references to
57330b57cec5SDimitry Andric /// parameter in locations other than return types, and then the
57340b57cec5SDimitry Andric /// mangling had to be generalized without changing the existing
57350b57cec5SDimitry Andric /// manglings.
57360b57cec5SDimitry Andric ///
57370b57cec5SDimitry Andric /// I is the zero-based index of the parameter within its parameter
57380b57cec5SDimitry Andric /// declaration clause.  Note that the original ABI document describes
57390b57cec5SDimitry Andric /// this using 1-based ordinals.
mangleFunctionParam(const ParmVarDecl * parm)57400b57cec5SDimitry Andric void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
57410b57cec5SDimitry Andric   unsigned parmDepth = parm->getFunctionScopeDepth();
57420b57cec5SDimitry Andric   unsigned parmIndex = parm->getFunctionScopeIndex();
57430b57cec5SDimitry Andric 
57440b57cec5SDimitry Andric   // Compute 'L'.
57450b57cec5SDimitry Andric   // parmDepth does not include the declaring function prototype.
57460b57cec5SDimitry Andric   // FunctionTypeDepth does account for that.
57470b57cec5SDimitry Andric   assert(parmDepth < FunctionTypeDepth.getDepth());
57480b57cec5SDimitry Andric   unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
57490b57cec5SDimitry Andric   if (FunctionTypeDepth.isInResultType())
57500b57cec5SDimitry Andric     nestingDepth--;
57510b57cec5SDimitry Andric 
57520b57cec5SDimitry Andric   if (nestingDepth == 0) {
57530b57cec5SDimitry Andric     Out << "fp";
57540b57cec5SDimitry Andric   } else {
57550b57cec5SDimitry Andric     Out << "fL" << (nestingDepth - 1) << 'p';
57560b57cec5SDimitry Andric   }
57570b57cec5SDimitry Andric 
57580b57cec5SDimitry Andric   // Top-level qualifiers.  We don't have to worry about arrays here,
57590b57cec5SDimitry Andric   // because parameters declared as arrays should already have been
57600b57cec5SDimitry Andric   // transformed to have pointer type. FIXME: apparently these don't
57610b57cec5SDimitry Andric   // get mangled if used as an rvalue of a known non-class type?
57620b57cec5SDimitry Andric   assert(!parm->getType()->isArrayType()
57630b57cec5SDimitry Andric          && "parameter's type is still an array type?");
57640b57cec5SDimitry Andric 
57650b57cec5SDimitry Andric   if (const DependentAddressSpaceType *DAST =
57660b57cec5SDimitry Andric       dyn_cast<DependentAddressSpaceType>(parm->getType())) {
57670b57cec5SDimitry Andric     mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
57680b57cec5SDimitry Andric   } else {
57690b57cec5SDimitry Andric     mangleQualifiers(parm->getType().getQualifiers());
57700b57cec5SDimitry Andric   }
57710b57cec5SDimitry Andric 
57720b57cec5SDimitry Andric   // Parameter index.
57730b57cec5SDimitry Andric   if (parmIndex != 0) {
57740b57cec5SDimitry Andric     Out << (parmIndex - 1);
57750b57cec5SDimitry Andric   }
57760b57cec5SDimitry Andric   Out << '_';
57770b57cec5SDimitry Andric }
57780b57cec5SDimitry Andric 
mangleCXXCtorType(CXXCtorType T,const CXXRecordDecl * InheritedFrom)57790b57cec5SDimitry Andric void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
57800b57cec5SDimitry Andric                                        const CXXRecordDecl *InheritedFrom) {
57810b57cec5SDimitry Andric   // <ctor-dtor-name> ::= C1  # complete object constructor
57820b57cec5SDimitry Andric   //                  ::= C2  # base object constructor
57830b57cec5SDimitry Andric   //                  ::= CI1 <type> # complete inheriting constructor
57840b57cec5SDimitry Andric   //                  ::= CI2 <type> # base inheriting constructor
57850b57cec5SDimitry Andric   //
57860b57cec5SDimitry Andric   // In addition, C5 is a comdat name with C1 and C2 in it.
57870b57cec5SDimitry Andric   Out << 'C';
57880b57cec5SDimitry Andric   if (InheritedFrom)
57890b57cec5SDimitry Andric     Out << 'I';
57900b57cec5SDimitry Andric   switch (T) {
57910b57cec5SDimitry Andric   case Ctor_Complete:
57920b57cec5SDimitry Andric     Out << '1';
57930b57cec5SDimitry Andric     break;
57940b57cec5SDimitry Andric   case Ctor_Base:
57950b57cec5SDimitry Andric     Out << '2';
57960b57cec5SDimitry Andric     break;
57970b57cec5SDimitry Andric   case Ctor_Comdat:
57980b57cec5SDimitry Andric     Out << '5';
57990b57cec5SDimitry Andric     break;
58000b57cec5SDimitry Andric   case Ctor_DefaultClosure:
58010b57cec5SDimitry Andric   case Ctor_CopyingClosure:
58020b57cec5SDimitry Andric     llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
58030b57cec5SDimitry Andric   }
58040b57cec5SDimitry Andric   if (InheritedFrom)
58050b57cec5SDimitry Andric     mangleName(InheritedFrom);
58060b57cec5SDimitry Andric }
58070b57cec5SDimitry Andric 
mangleCXXDtorType(CXXDtorType T)58080b57cec5SDimitry Andric void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
58090b57cec5SDimitry Andric   // <ctor-dtor-name> ::= D0  # deleting destructor
58100b57cec5SDimitry Andric   //                  ::= D1  # complete object destructor
58110b57cec5SDimitry Andric   //                  ::= D2  # base object destructor
58120b57cec5SDimitry Andric   //
58130b57cec5SDimitry Andric   // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
58140b57cec5SDimitry Andric   switch (T) {
58150b57cec5SDimitry Andric   case Dtor_Deleting:
58160b57cec5SDimitry Andric     Out << "D0";
58170b57cec5SDimitry Andric     break;
58180b57cec5SDimitry Andric   case Dtor_Complete:
58190b57cec5SDimitry Andric     Out << "D1";
58200b57cec5SDimitry Andric     break;
58210b57cec5SDimitry Andric   case Dtor_Base:
58220b57cec5SDimitry Andric     Out << "D2";
58230b57cec5SDimitry Andric     break;
58240b57cec5SDimitry Andric   case Dtor_Comdat:
58250b57cec5SDimitry Andric     Out << "D5";
58260b57cec5SDimitry Andric     break;
58270b57cec5SDimitry Andric   }
58280b57cec5SDimitry Andric }
58290b57cec5SDimitry Andric 
5830e8d8bef9SDimitry Andric // Helper to provide ancillary information on a template used to mangle its
5831e8d8bef9SDimitry Andric // arguments.
58325f757f3fSDimitry Andric struct CXXNameMangler::TemplateArgManglingInfo {
58335f757f3fSDimitry Andric   const CXXNameMangler &Mangler;
5834e8d8bef9SDimitry Andric   TemplateDecl *ResolvedTemplate = nullptr;
5835e8d8bef9SDimitry Andric   bool SeenPackExpansionIntoNonPack = false;
5836e8d8bef9SDimitry Andric   const NamedDecl *UnresolvedExpandedPack = nullptr;
5837e8d8bef9SDimitry Andric 
TemplateArgManglingInfoCXXNameMangler::TemplateArgManglingInfo58385f757f3fSDimitry Andric   TemplateArgManglingInfo(const CXXNameMangler &Mangler, TemplateName TN)
58395f757f3fSDimitry Andric       : Mangler(Mangler) {
5840e8d8bef9SDimitry Andric     if (TemplateDecl *TD = TN.getAsTemplateDecl())
5841e8d8bef9SDimitry Andric       ResolvedTemplate = TD;
5842e8d8bef9SDimitry Andric   }
5843e8d8bef9SDimitry Andric 
58445f757f3fSDimitry Andric   /// Information about how to mangle a template argument.
58455f757f3fSDimitry Andric   struct Info {
58465f757f3fSDimitry Andric     /// Do we need to mangle the template argument with an exactly correct type?
58475f757f3fSDimitry Andric     bool NeedExactType;
58485f757f3fSDimitry Andric     /// If we need to prefix the mangling with a mangling of the template
58495f757f3fSDimitry Andric     /// parameter, the corresponding parameter.
58505f757f3fSDimitry Andric     const NamedDecl *TemplateParameterToMangle;
58515f757f3fSDimitry Andric   };
58525f757f3fSDimitry Andric 
58535f757f3fSDimitry Andric   /// Determine whether the resolved template might be overloaded on its
58545f757f3fSDimitry Andric   /// template parameter list. If so, the mangling needs to include enough
58555f757f3fSDimitry Andric   /// information to reconstruct the template parameter list.
isOverloadableCXXNameMangler::TemplateArgManglingInfo58565f757f3fSDimitry Andric   bool isOverloadable() {
58575f757f3fSDimitry Andric     // Function templates are generally overloadable. As a special case, a
58585f757f3fSDimitry Andric     // member function template of a generic lambda is not overloadable.
58595f757f3fSDimitry Andric     if (auto *FTD = dyn_cast_or_null<FunctionTemplateDecl>(ResolvedTemplate)) {
58605f757f3fSDimitry Andric       auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
58615f757f3fSDimitry Andric       if (!RD || !RD->isGenericLambda())
58625f757f3fSDimitry Andric         return true;
58635f757f3fSDimitry Andric     }
58645f757f3fSDimitry Andric 
58655f757f3fSDimitry Andric     // All other templates are not overloadable. Partial specializations would
58665f757f3fSDimitry Andric     // be, but we never mangle them.
58675f757f3fSDimitry Andric     return false;
58685f757f3fSDimitry Andric   }
58695f757f3fSDimitry Andric 
58705f757f3fSDimitry Andric   /// Determine whether we need to prefix this <template-arg> mangling with a
58715f757f3fSDimitry Andric   /// <template-param-decl>. This happens if the natural template parameter for
58725f757f3fSDimitry Andric   /// the argument mangling is not the same as the actual template parameter.
needToMangleTemplateParamCXXNameMangler::TemplateArgManglingInfo58735f757f3fSDimitry Andric   bool needToMangleTemplateParam(const NamedDecl *Param,
58745f757f3fSDimitry Andric                                  const TemplateArgument &Arg) {
58755f757f3fSDimitry Andric     // For a template type parameter, the natural parameter is 'typename T'.
58765f757f3fSDimitry Andric     // The actual parameter might be constrained.
58775f757f3fSDimitry Andric     if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
58785f757f3fSDimitry Andric       return TTP->hasTypeConstraint();
58795f757f3fSDimitry Andric 
58805f757f3fSDimitry Andric     if (Arg.getKind() == TemplateArgument::Pack) {
58815f757f3fSDimitry Andric       // For an empty pack, the natural parameter is `typename...`.
58825f757f3fSDimitry Andric       if (Arg.pack_size() == 0)
58835f757f3fSDimitry Andric         return true;
58845f757f3fSDimitry Andric 
58855f757f3fSDimitry Andric       // For any other pack, we use the first argument to determine the natural
58865f757f3fSDimitry Andric       // template parameter.
58875f757f3fSDimitry Andric       return needToMangleTemplateParam(Param, *Arg.pack_begin());
58885f757f3fSDimitry Andric     }
58895f757f3fSDimitry Andric 
58905f757f3fSDimitry Andric     // For a non-type template parameter, the natural parameter is `T V` (for a
58915f757f3fSDimitry Andric     // prvalue argument) or `T &V` (for a glvalue argument), where `T` is the
58925f757f3fSDimitry Andric     // type of the argument, which we require to exactly match. If the actual
58935f757f3fSDimitry Andric     // parameter has a deduced or instantiation-dependent type, it is not
58945f757f3fSDimitry Andric     // equivalent to the natural parameter.
58955f757f3fSDimitry Andric     if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
58965f757f3fSDimitry Andric       return NTTP->getType()->isInstantiationDependentType() ||
58975f757f3fSDimitry Andric              NTTP->getType()->getContainedDeducedType();
58985f757f3fSDimitry Andric 
58995f757f3fSDimitry Andric     // For a template template parameter, the template-head might differ from
59005f757f3fSDimitry Andric     // that of the template.
59015f757f3fSDimitry Andric     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
59025f757f3fSDimitry Andric     TemplateName ArgTemplateName = Arg.getAsTemplateOrTemplatePattern();
59035f757f3fSDimitry Andric     const TemplateDecl *ArgTemplate = ArgTemplateName.getAsTemplateDecl();
59045f757f3fSDimitry Andric     if (!ArgTemplate)
59055f757f3fSDimitry Andric       return true;
59065f757f3fSDimitry Andric 
59075f757f3fSDimitry Andric     // Mangle the template parameter list of the parameter and argument to see
59085f757f3fSDimitry Andric     // if they are the same. We can't use Profile for this, because it can't
59095f757f3fSDimitry Andric     // model the depth difference between parameter and argument and might not
59105f757f3fSDimitry Andric     // necessarily have the same definition of "identical" that we use here --
59115f757f3fSDimitry Andric     // that is, same mangling.
59125f757f3fSDimitry Andric     auto MangleTemplateParamListToString =
59135f757f3fSDimitry Andric         [&](SmallVectorImpl<char> &Buffer, const TemplateParameterList *Params,
59145f757f3fSDimitry Andric             unsigned DepthOffset) {
59155f757f3fSDimitry Andric           llvm::raw_svector_ostream Stream(Buffer);
59165f757f3fSDimitry Andric           CXXNameMangler(Mangler.Context, Stream,
59175f757f3fSDimitry Andric                          WithTemplateDepthOffset{DepthOffset})
59185f757f3fSDimitry Andric               .mangleTemplateParameterList(Params);
59195f757f3fSDimitry Andric         };
59205f757f3fSDimitry Andric     llvm::SmallString<128> ParamTemplateHead, ArgTemplateHead;
59215f757f3fSDimitry Andric     MangleTemplateParamListToString(ParamTemplateHead,
59225f757f3fSDimitry Andric                                     TTP->getTemplateParameters(), 0);
59235f757f3fSDimitry Andric     // Add the depth of the parameter's template parameter list to all
59245f757f3fSDimitry Andric     // parameters appearing in the argument to make the indexes line up
59255f757f3fSDimitry Andric     // properly.
59265f757f3fSDimitry Andric     MangleTemplateParamListToString(ArgTemplateHead,
59275f757f3fSDimitry Andric                                     ArgTemplate->getTemplateParameters(),
59285f757f3fSDimitry Andric                                     TTP->getTemplateParameters()->getDepth());
59295f757f3fSDimitry Andric     return ParamTemplateHead != ArgTemplateHead;
59305f757f3fSDimitry Andric   }
59315f757f3fSDimitry Andric 
59325f757f3fSDimitry Andric   /// Determine information about how this template argument should be mangled.
5933e8d8bef9SDimitry Andric   /// This should be called exactly once for each parameter / argument pair, in
5934e8d8bef9SDimitry Andric   /// order.
getArgInfoCXXNameMangler::TemplateArgManglingInfo59355f757f3fSDimitry Andric   Info getArgInfo(unsigned ParamIdx, const TemplateArgument &Arg) {
5936e8d8bef9SDimitry Andric     // We need correct types when the template-name is unresolved or when it
5937e8d8bef9SDimitry Andric     // names a template that is able to be overloaded.
5938e8d8bef9SDimitry Andric     if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
59395f757f3fSDimitry Andric       return {true, nullptr};
5940e8d8bef9SDimitry Andric 
5941e8d8bef9SDimitry Andric     // Move to the next parameter.
5942e8d8bef9SDimitry Andric     const NamedDecl *Param = UnresolvedExpandedPack;
5943e8d8bef9SDimitry Andric     if (!Param) {
5944e8d8bef9SDimitry Andric       assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
5945e8d8bef9SDimitry Andric              "no parameter for argument");
5946e8d8bef9SDimitry Andric       Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
5947e8d8bef9SDimitry Andric 
59485f757f3fSDimitry Andric       // If we reach a parameter pack whose argument isn't in pack form, that
59495f757f3fSDimitry Andric       // means Sema couldn't or didn't figure out which arguments belonged to
59505f757f3fSDimitry Andric       // it, because it contains a pack expansion or because Sema bailed out of
59515f757f3fSDimitry Andric       // computing parameter / argument correspondence before this point. Track
59525f757f3fSDimitry Andric       // the pack as the corresponding parameter for all further template
59535f757f3fSDimitry Andric       // arguments until we hit a pack expansion, at which point we don't know
59545f757f3fSDimitry Andric       // the correspondence between parameters and arguments at all.
5955e8d8bef9SDimitry Andric       if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
5956e8d8bef9SDimitry Andric         UnresolvedExpandedPack = Param;
5957e8d8bef9SDimitry Andric       }
5958e8d8bef9SDimitry Andric     }
5959e8d8bef9SDimitry Andric 
5960e8d8bef9SDimitry Andric     // If we encounter a pack argument that is expanded into a non-pack
5961e8d8bef9SDimitry Andric     // parameter, we can no longer track parameter / argument correspondence,
5962e8d8bef9SDimitry Andric     // and need to use exact types from this point onwards.
5963e8d8bef9SDimitry Andric     if (Arg.isPackExpansion() &&
5964e8d8bef9SDimitry Andric         (!Param->isParameterPack() || UnresolvedExpandedPack)) {
5965e8d8bef9SDimitry Andric       SeenPackExpansionIntoNonPack = true;
59665f757f3fSDimitry Andric       return {true, nullptr};
5967e8d8bef9SDimitry Andric     }
5968e8d8bef9SDimitry Andric 
59695f757f3fSDimitry Andric     // We need exact types for arguments of a template that might be overloaded
59705f757f3fSDimitry Andric     // on template parameter type.
59715f757f3fSDimitry Andric     if (isOverloadable())
59725f757f3fSDimitry Andric       return {true, needToMangleTemplateParam(Param, Arg) ? Param : nullptr};
5973e8d8bef9SDimitry Andric 
5974e8d8bef9SDimitry Andric     // Otherwise, we only need a correct type if the parameter has a deduced
5975e8d8bef9SDimitry Andric     // type.
5976e8d8bef9SDimitry Andric     //
5977e8d8bef9SDimitry Andric     // Note: for an expanded parameter pack, getType() returns the type prior
5978e8d8bef9SDimitry Andric     // to expansion. We could ask for the expanded type with getExpansionType(),
5979e8d8bef9SDimitry Andric     // but it doesn't matter because substitution and expansion don't affect
5980e8d8bef9SDimitry Andric     // whether a deduced type appears in the type.
5981e8d8bef9SDimitry Andric     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
59825f757f3fSDimitry Andric     bool NeedExactType = NTTP && NTTP->getType()->getContainedDeducedType();
59835f757f3fSDimitry Andric     return {NeedExactType, nullptr};
59845f757f3fSDimitry Andric   }
59855f757f3fSDimitry Andric 
59865f757f3fSDimitry Andric   /// Determine if we should mangle a requires-clause after the template
59875f757f3fSDimitry Andric   /// argument list. If so, returns the expression to mangle.
getTrailingRequiresClauseToMangleCXXNameMangler::TemplateArgManglingInfo59885f757f3fSDimitry Andric   const Expr *getTrailingRequiresClauseToMangle() {
59895f757f3fSDimitry Andric     if (!isOverloadable())
59905f757f3fSDimitry Andric       return nullptr;
59915f757f3fSDimitry Andric     return ResolvedTemplate->getTemplateParameters()->getRequiresClause();
5992e8d8bef9SDimitry Andric   }
5993e8d8bef9SDimitry Andric };
5994e8d8bef9SDimitry Andric 
mangleTemplateArgs(TemplateName TN,const TemplateArgumentLoc * TemplateArgs,unsigned NumTemplateArgs)5995e8d8bef9SDimitry Andric void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5996e8d8bef9SDimitry Andric                                         const TemplateArgumentLoc *TemplateArgs,
59970b57cec5SDimitry Andric                                         unsigned NumTemplateArgs) {
59985f757f3fSDimitry Andric   // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
59990b57cec5SDimitry Andric   Out << 'I';
60005f757f3fSDimitry Andric   TemplateArgManglingInfo Info(*this, TN);
60015f757f3fSDimitry Andric   for (unsigned i = 0; i != NumTemplateArgs; ++i) {
60025f757f3fSDimitry Andric     mangleTemplateArg(Info, i, TemplateArgs[i].getArgument());
60035f757f3fSDimitry Andric   }
60045f757f3fSDimitry Andric   mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
60050b57cec5SDimitry Andric   Out << 'E';
60060b57cec5SDimitry Andric }
60070b57cec5SDimitry Andric 
mangleTemplateArgs(TemplateName TN,const TemplateArgumentList & AL)6008e8d8bef9SDimitry Andric void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6009e8d8bef9SDimitry Andric                                         const TemplateArgumentList &AL) {
60105f757f3fSDimitry Andric   // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
60110b57cec5SDimitry Andric   Out << 'I';
60125f757f3fSDimitry Andric   TemplateArgManglingInfo Info(*this, TN);
60135f757f3fSDimitry Andric   for (unsigned i = 0, e = AL.size(); i != e; ++i) {
60145f757f3fSDimitry Andric     mangleTemplateArg(Info, i, AL[i]);
60155f757f3fSDimitry Andric   }
60165f757f3fSDimitry Andric   mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
60170b57cec5SDimitry Andric   Out << 'E';
60180b57cec5SDimitry Andric }
60190b57cec5SDimitry Andric 
mangleTemplateArgs(TemplateName TN,ArrayRef<TemplateArgument> Args)6020e8d8bef9SDimitry Andric void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6021bdd1243dSDimitry Andric                                         ArrayRef<TemplateArgument> Args) {
60225f757f3fSDimitry Andric   // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
60230b57cec5SDimitry Andric   Out << 'I';
60245f757f3fSDimitry Andric   TemplateArgManglingInfo Info(*this, TN);
60255f757f3fSDimitry Andric   for (unsigned i = 0; i != Args.size(); ++i) {
60265f757f3fSDimitry Andric     mangleTemplateArg(Info, i, Args[i]);
60275f757f3fSDimitry Andric   }
60285f757f3fSDimitry Andric   mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
60290b57cec5SDimitry Andric   Out << 'E';
60300b57cec5SDimitry Andric }
60310b57cec5SDimitry Andric 
mangleTemplateArg(TemplateArgManglingInfo & Info,unsigned Index,TemplateArgument A)60325f757f3fSDimitry Andric void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo &Info,
60335f757f3fSDimitry Andric                                        unsigned Index, TemplateArgument A) {
60345f757f3fSDimitry Andric   TemplateArgManglingInfo::Info ArgInfo = Info.getArgInfo(Index, A);
60355f757f3fSDimitry Andric 
60365f757f3fSDimitry Andric   // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
60375f757f3fSDimitry Andric   if (ArgInfo.TemplateParameterToMangle &&
60385f757f3fSDimitry Andric       !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
60395f757f3fSDimitry Andric     // The template parameter is mangled if the mangling would otherwise be
60405f757f3fSDimitry Andric     // ambiguous.
60415f757f3fSDimitry Andric     //
60425f757f3fSDimitry Andric     // <template-arg> ::= <template-param-decl> <template-arg>
60435f757f3fSDimitry Andric     //
60445f757f3fSDimitry Andric     // Clang 17 and before did not do this.
60455f757f3fSDimitry Andric     mangleTemplateParamDecl(ArgInfo.TemplateParameterToMangle);
60465f757f3fSDimitry Andric   }
60475f757f3fSDimitry Andric 
60485f757f3fSDimitry Andric   mangleTemplateArg(A, ArgInfo.NeedExactType);
60495f757f3fSDimitry Andric }
60505f757f3fSDimitry Andric 
mangleTemplateArg(TemplateArgument A,bool NeedExactType)6051e8d8bef9SDimitry Andric void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
60520b57cec5SDimitry Andric   // <template-arg> ::= <type>              # type or template
60530b57cec5SDimitry Andric   //                ::= X <expression> E    # expression
60540b57cec5SDimitry Andric   //                ::= <expr-primary>      # simple expressions
60550b57cec5SDimitry Andric   //                ::= J <template-arg>* E # argument pack
60560b57cec5SDimitry Andric   if (!A.isInstantiationDependent() || A.isDependent())
60570b57cec5SDimitry Andric     A = Context.getASTContext().getCanonicalTemplateArgument(A);
60580b57cec5SDimitry Andric 
60590b57cec5SDimitry Andric   switch (A.getKind()) {
60600b57cec5SDimitry Andric   case TemplateArgument::Null:
60610b57cec5SDimitry Andric     llvm_unreachable("Cannot mangle NULL template argument");
60620b57cec5SDimitry Andric 
60630b57cec5SDimitry Andric   case TemplateArgument::Type:
60640b57cec5SDimitry Andric     mangleType(A.getAsType());
60650b57cec5SDimitry Andric     break;
60660b57cec5SDimitry Andric   case TemplateArgument::Template:
60670b57cec5SDimitry Andric     // This is mangled as <type>.
60680b57cec5SDimitry Andric     mangleType(A.getAsTemplate());
60690b57cec5SDimitry Andric     break;
60700b57cec5SDimitry Andric   case TemplateArgument::TemplateExpansion:
60710b57cec5SDimitry Andric     // <type>  ::= Dp <type>          # pack expansion (C++0x)
60720b57cec5SDimitry Andric     Out << "Dp";
60730b57cec5SDimitry Andric     mangleType(A.getAsTemplateOrTemplatePattern());
60740b57cec5SDimitry Andric     break;
6075d409305fSDimitry Andric   case TemplateArgument::Expression:
6076d409305fSDimitry Andric     mangleTemplateArgExpr(A.getAsExpr());
60770b57cec5SDimitry Andric     break;
60780b57cec5SDimitry Andric   case TemplateArgument::Integral:
60790b57cec5SDimitry Andric     mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
60800b57cec5SDimitry Andric     break;
60810b57cec5SDimitry Andric   case TemplateArgument::Declaration: {
60820b57cec5SDimitry Andric     //  <expr-primary> ::= L <mangled-name> E # external name
60830b57cec5SDimitry Andric     ValueDecl *D = A.getAsDecl();
6084e8d8bef9SDimitry Andric 
6085e8d8bef9SDimitry Andric     // Template parameter objects are modeled by reproducing a source form
6086e8d8bef9SDimitry Andric     // produced as if by aggregate initialization.
6087e8d8bef9SDimitry Andric     if (A.getParamTypeForDecl()->isRecordType()) {
6088e8d8bef9SDimitry Andric       auto *TPO = cast<TemplateParamObjectDecl>(D);
6089e8d8bef9SDimitry Andric       mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
6090e8d8bef9SDimitry Andric                                TPO->getValue(), /*TopLevel=*/true,
6091e8d8bef9SDimitry Andric                                NeedExactType);
6092e8d8bef9SDimitry Andric       break;
60930b57cec5SDimitry Andric     }
60940b57cec5SDimitry Andric 
6095e8d8bef9SDimitry Andric     ASTContext &Ctx = Context.getASTContext();
6096e8d8bef9SDimitry Andric     APValue Value;
6097e8d8bef9SDimitry Andric     if (D->isCXXInstanceMember())
6098e8d8bef9SDimitry Andric       // Simple pointer-to-member with no conversion.
6099e8d8bef9SDimitry Andric       Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
6100e8d8bef9SDimitry Andric     else if (D->getType()->isArrayType() &&
6101e8d8bef9SDimitry Andric              Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),
6102e8d8bef9SDimitry Andric                                 A.getParamTypeForDecl()) &&
61035f757f3fSDimitry Andric              !isCompatibleWith(LangOptions::ClangABI::Ver11))
6104e8d8bef9SDimitry Andric       // Build a value corresponding to this implicit array-to-pointer decay.
6105e8d8bef9SDimitry Andric       Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
6106e8d8bef9SDimitry Andric                       {APValue::LValuePathEntry::ArrayIndex(0)},
6107e8d8bef9SDimitry Andric                       /*OnePastTheEnd=*/false);
6108e8d8bef9SDimitry Andric     else
6109e8d8bef9SDimitry Andric       // Regular pointer or reference to a declaration.
6110e8d8bef9SDimitry Andric       Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
6111e8d8bef9SDimitry Andric                       ArrayRef<APValue::LValuePathEntry>(),
6112e8d8bef9SDimitry Andric                       /*OnePastTheEnd=*/false);
6113e8d8bef9SDimitry Andric     mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
6114e8d8bef9SDimitry Andric                              NeedExactType);
61150b57cec5SDimitry Andric     break;
61160b57cec5SDimitry Andric   }
61170b57cec5SDimitry Andric   case TemplateArgument::NullPtr: {
6118e8d8bef9SDimitry Andric     mangleNullPointer(A.getNullPtrType());
61190b57cec5SDimitry Andric     break;
61200b57cec5SDimitry Andric   }
61217a6dacacSDimitry Andric   case TemplateArgument::StructuralValue:
61227a6dacacSDimitry Andric     mangleValueInTemplateArg(A.getStructuralValueType(),
61237a6dacacSDimitry Andric                              A.getAsStructuralValue(),
61247a6dacacSDimitry Andric                              /*TopLevel=*/true, NeedExactType);
61257a6dacacSDimitry Andric     break;
61260b57cec5SDimitry Andric   case TemplateArgument::Pack: {
61270b57cec5SDimitry Andric     //  <template-arg> ::= J <template-arg>* E
61280b57cec5SDimitry Andric     Out << 'J';
61290b57cec5SDimitry Andric     for (const auto &P : A.pack_elements())
6130e8d8bef9SDimitry Andric       mangleTemplateArg(P, NeedExactType);
61310b57cec5SDimitry Andric     Out << 'E';
61320b57cec5SDimitry Andric   }
61330b57cec5SDimitry Andric   }
61340b57cec5SDimitry Andric }
61350b57cec5SDimitry Andric 
mangleTemplateArgExpr(const Expr * E)6136d409305fSDimitry Andric void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
61375f757f3fSDimitry Andric   if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6138d409305fSDimitry Andric     mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
6139d409305fSDimitry Andric     return;
6140d409305fSDimitry Andric   }
6141d409305fSDimitry Andric 
6142d409305fSDimitry Andric   // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
6143d409305fSDimitry Andric   // correctly in cases where the template argument was
6144d409305fSDimitry Andric   // constructed from an expression rather than an already-evaluated
6145d409305fSDimitry Andric   // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
6146d409305fSDimitry Andric   // 'Li0E'.
6147d409305fSDimitry Andric   //
6148d409305fSDimitry Andric   // We did special-case DeclRefExpr to attempt to DTRT for that one
6149d409305fSDimitry Andric   // expression-kind, but while doing so, unfortunately handled ParmVarDecl
6150d409305fSDimitry Andric   // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
6151d409305fSDimitry Andric   // the proper 'Xfp_E'.
6152d409305fSDimitry Andric   E = E->IgnoreParenImpCasts();
6153d409305fSDimitry Andric   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6154d409305fSDimitry Andric     const ValueDecl *D = DRE->getDecl();
6155d409305fSDimitry Andric     if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
6156d409305fSDimitry Andric       Out << 'L';
6157d409305fSDimitry Andric       mangle(D);
6158d409305fSDimitry Andric       Out << 'E';
6159d409305fSDimitry Andric       return;
6160d409305fSDimitry Andric     }
6161d409305fSDimitry Andric   }
6162d409305fSDimitry Andric   Out << 'X';
6163d409305fSDimitry Andric   mangleExpression(E);
6164d409305fSDimitry Andric   Out << 'E';
6165d409305fSDimitry Andric }
6166d409305fSDimitry Andric 
6167e8d8bef9SDimitry Andric /// Determine whether a given value is equivalent to zero-initialization for
6168e8d8bef9SDimitry Andric /// the purpose of discarding a trailing portion of a 'tl' mangling.
6169e8d8bef9SDimitry Andric ///
6170e8d8bef9SDimitry Andric /// Note that this is not in general equivalent to determining whether the
6171e8d8bef9SDimitry Andric /// value has an all-zeroes bit pattern.
isZeroInitialized(QualType T,const APValue & V)6172e8d8bef9SDimitry Andric static bool isZeroInitialized(QualType T, const APValue &V) {
6173e8d8bef9SDimitry Andric   // FIXME: mangleValueInTemplateArg has quadratic time complexity in
6174e8d8bef9SDimitry Andric   // pathological cases due to using this, but it's a little awkward
6175e8d8bef9SDimitry Andric   // to do this in linear time in general.
6176e8d8bef9SDimitry Andric   switch (V.getKind()) {
6177e8d8bef9SDimitry Andric   case APValue::None:
6178e8d8bef9SDimitry Andric   case APValue::Indeterminate:
6179e8d8bef9SDimitry Andric   case APValue::AddrLabelDiff:
6180e8d8bef9SDimitry Andric     return false;
6181e8d8bef9SDimitry Andric 
6182e8d8bef9SDimitry Andric   case APValue::Struct: {
6183e8d8bef9SDimitry Andric     const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6184e8d8bef9SDimitry Andric     assert(RD && "unexpected type for record value");
6185e8d8bef9SDimitry Andric     unsigned I = 0;
6186e8d8bef9SDimitry Andric     for (const CXXBaseSpecifier &BS : RD->bases()) {
6187e8d8bef9SDimitry Andric       if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
6188e8d8bef9SDimitry Andric         return false;
6189e8d8bef9SDimitry Andric       ++I;
6190e8d8bef9SDimitry Andric     }
6191e8d8bef9SDimitry Andric     I = 0;
6192e8d8bef9SDimitry Andric     for (const FieldDecl *FD : RD->fields()) {
61930fca6ea1SDimitry Andric       if (!FD->isUnnamedBitField() &&
6194e8d8bef9SDimitry Andric           !isZeroInitialized(FD->getType(), V.getStructField(I)))
6195e8d8bef9SDimitry Andric         return false;
6196e8d8bef9SDimitry Andric       ++I;
6197e8d8bef9SDimitry Andric     }
6198e8d8bef9SDimitry Andric     return true;
6199e8d8bef9SDimitry Andric   }
6200e8d8bef9SDimitry Andric 
6201e8d8bef9SDimitry Andric   case APValue::Union: {
6202e8d8bef9SDimitry Andric     const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6203e8d8bef9SDimitry Andric     assert(RD && "unexpected type for union value");
6204e8d8bef9SDimitry Andric     // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
6205e8d8bef9SDimitry Andric     for (const FieldDecl *FD : RD->fields()) {
62060fca6ea1SDimitry Andric       if (!FD->isUnnamedBitField())
6207e8d8bef9SDimitry Andric         return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
6208e8d8bef9SDimitry Andric                isZeroInitialized(FD->getType(), V.getUnionValue());
6209e8d8bef9SDimitry Andric     }
6210e8d8bef9SDimitry Andric     // If there are no fields (other than unnamed bitfields), the value is
6211e8d8bef9SDimitry Andric     // necessarily zero-initialized.
6212e8d8bef9SDimitry Andric     return true;
6213e8d8bef9SDimitry Andric   }
6214e8d8bef9SDimitry Andric 
6215e8d8bef9SDimitry Andric   case APValue::Array: {
6216e8d8bef9SDimitry Andric     QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6217e8d8bef9SDimitry Andric     for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
6218e8d8bef9SDimitry Andric       if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
6219e8d8bef9SDimitry Andric         return false;
6220e8d8bef9SDimitry Andric     return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
6221e8d8bef9SDimitry Andric   }
6222e8d8bef9SDimitry Andric 
6223e8d8bef9SDimitry Andric   case APValue::Vector: {
6224e8d8bef9SDimitry Andric     const VectorType *VT = T->castAs<VectorType>();
6225e8d8bef9SDimitry Andric     for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
6226e8d8bef9SDimitry Andric       if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
6227e8d8bef9SDimitry Andric         return false;
6228e8d8bef9SDimitry Andric     return true;
6229e8d8bef9SDimitry Andric   }
6230e8d8bef9SDimitry Andric 
6231e8d8bef9SDimitry Andric   case APValue::Int:
6232e8d8bef9SDimitry Andric     return !V.getInt();
6233e8d8bef9SDimitry Andric 
6234e8d8bef9SDimitry Andric   case APValue::Float:
6235e8d8bef9SDimitry Andric     return V.getFloat().isPosZero();
6236e8d8bef9SDimitry Andric 
6237e8d8bef9SDimitry Andric   case APValue::FixedPoint:
6238e8d8bef9SDimitry Andric     return !V.getFixedPoint().getValue();
6239e8d8bef9SDimitry Andric 
6240e8d8bef9SDimitry Andric   case APValue::ComplexFloat:
6241e8d8bef9SDimitry Andric     return V.getComplexFloatReal().isPosZero() &&
6242e8d8bef9SDimitry Andric            V.getComplexFloatImag().isPosZero();
6243e8d8bef9SDimitry Andric 
6244e8d8bef9SDimitry Andric   case APValue::ComplexInt:
6245e8d8bef9SDimitry Andric     return !V.getComplexIntReal() && !V.getComplexIntImag();
6246e8d8bef9SDimitry Andric 
6247e8d8bef9SDimitry Andric   case APValue::LValue:
6248e8d8bef9SDimitry Andric     return V.isNullPointer();
6249e8d8bef9SDimitry Andric 
6250e8d8bef9SDimitry Andric   case APValue::MemberPointer:
6251e8d8bef9SDimitry Andric     return !V.getMemberPointerDecl();
6252e8d8bef9SDimitry Andric   }
6253e8d8bef9SDimitry Andric 
6254e8d8bef9SDimitry Andric   llvm_unreachable("Unhandled APValue::ValueKind enum");
6255e8d8bef9SDimitry Andric }
6256e8d8bef9SDimitry Andric 
getLValueType(ASTContext & Ctx,const APValue & LV)6257e8d8bef9SDimitry Andric static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
6258e8d8bef9SDimitry Andric   QualType T = LV.getLValueBase().getType();
6259e8d8bef9SDimitry Andric   for (APValue::LValuePathEntry E : LV.getLValuePath()) {
6260e8d8bef9SDimitry Andric     if (const ArrayType *AT = Ctx.getAsArrayType(T))
6261e8d8bef9SDimitry Andric       T = AT->getElementType();
6262e8d8bef9SDimitry Andric     else if (const FieldDecl *FD =
6263e8d8bef9SDimitry Andric                  dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
6264e8d8bef9SDimitry Andric       T = FD->getType();
6265e8d8bef9SDimitry Andric     else
6266e8d8bef9SDimitry Andric       T = Ctx.getRecordType(
6267e8d8bef9SDimitry Andric           cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
6268e8d8bef9SDimitry Andric   }
6269e8d8bef9SDimitry Andric   return T;
6270e8d8bef9SDimitry Andric }
6271e8d8bef9SDimitry Andric 
getUnionInitName(SourceLocation UnionLoc,DiagnosticsEngine & Diags,const FieldDecl * FD)627281ad6265SDimitry Andric static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,
627381ad6265SDimitry Andric                                         DiagnosticsEngine &Diags,
627481ad6265SDimitry Andric                                         const FieldDecl *FD) {
627581ad6265SDimitry Andric   // According to:
627681ad6265SDimitry Andric   // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
627781ad6265SDimitry Andric   // For the purposes of mangling, the name of an anonymous union is considered
627881ad6265SDimitry Andric   // to be the name of the first named data member found by a pre-order,
627981ad6265SDimitry Andric   // depth-first, declaration-order walk of the data members of the anonymous
628081ad6265SDimitry Andric   // union.
628181ad6265SDimitry Andric 
628281ad6265SDimitry Andric   if (FD->getIdentifier())
628381ad6265SDimitry Andric     return FD->getIdentifier();
628481ad6265SDimitry Andric 
628581ad6265SDimitry Andric   // The only cases where the identifer of a FieldDecl would be blank is if the
628681ad6265SDimitry Andric   // field represents an anonymous record type or if it is an unnamed bitfield.
628781ad6265SDimitry Andric   // There is no type to descend into in the case of a bitfield, so we can just
628881ad6265SDimitry Andric   // return nullptr in that case.
628981ad6265SDimitry Andric   if (FD->isBitField())
629081ad6265SDimitry Andric     return nullptr;
629181ad6265SDimitry Andric   const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
629281ad6265SDimitry Andric 
629381ad6265SDimitry Andric   // Consider only the fields in declaration order, searched depth-first.  We
629481ad6265SDimitry Andric   // don't care about the active member of the union, as all we are doing is
629581ad6265SDimitry Andric   // looking for a valid name. We also don't check bases, due to guidance from
629681ad6265SDimitry Andric   // the Itanium ABI folks.
629781ad6265SDimitry Andric   for (const FieldDecl *RDField : RD->fields()) {
629881ad6265SDimitry Andric     if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
629981ad6265SDimitry Andric       return II;
630081ad6265SDimitry Andric   }
630181ad6265SDimitry Andric 
630281ad6265SDimitry Andric   // According to the Itanium ABI: If there is no such data member (i.e., if all
630381ad6265SDimitry Andric   // of the data members in the union are unnamed), then there is no way for a
630481ad6265SDimitry Andric   // program to refer to the anonymous union, and there is therefore no need to
630581ad6265SDimitry Andric   // mangle its name. However, we should diagnose this anyway.
630681ad6265SDimitry Andric   unsigned DiagID = Diags.getCustomDiagID(
630781ad6265SDimitry Andric       DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
630881ad6265SDimitry Andric   Diags.Report(UnionLoc, DiagID);
630981ad6265SDimitry Andric 
631081ad6265SDimitry Andric   return nullptr;
631181ad6265SDimitry Andric }
631281ad6265SDimitry Andric 
mangleValueInTemplateArg(QualType T,const APValue & V,bool TopLevel,bool NeedExactType)6313e8d8bef9SDimitry Andric void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
6314e8d8bef9SDimitry Andric                                               bool TopLevel,
6315e8d8bef9SDimitry Andric                                               bool NeedExactType) {
6316e8d8bef9SDimitry Andric   // Ignore all top-level cv-qualifiers, to match GCC.
6317e8d8bef9SDimitry Andric   Qualifiers Quals;
6318e8d8bef9SDimitry Andric   T = getASTContext().getUnqualifiedArrayType(T, Quals);
6319e8d8bef9SDimitry Andric 
6320e8d8bef9SDimitry Andric   // A top-level expression that's not a primary expression is wrapped in X...E.
6321e8d8bef9SDimitry Andric   bool IsPrimaryExpr = true;
6322e8d8bef9SDimitry Andric   auto NotPrimaryExpr = [&] {
6323e8d8bef9SDimitry Andric     if (TopLevel && IsPrimaryExpr)
6324e8d8bef9SDimitry Andric       Out << 'X';
6325e8d8bef9SDimitry Andric     IsPrimaryExpr = false;
6326e8d8bef9SDimitry Andric   };
6327e8d8bef9SDimitry Andric 
6328e8d8bef9SDimitry Andric   // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
6329e8d8bef9SDimitry Andric   switch (V.getKind()) {
6330e8d8bef9SDimitry Andric   case APValue::None:
6331e8d8bef9SDimitry Andric   case APValue::Indeterminate:
6332e8d8bef9SDimitry Andric     Out << 'L';
6333e8d8bef9SDimitry Andric     mangleType(T);
6334e8d8bef9SDimitry Andric     Out << 'E';
6335e8d8bef9SDimitry Andric     break;
6336e8d8bef9SDimitry Andric 
6337e8d8bef9SDimitry Andric   case APValue::AddrLabelDiff:
6338e8d8bef9SDimitry Andric     llvm_unreachable("unexpected value kind in template argument");
6339e8d8bef9SDimitry Andric 
6340e8d8bef9SDimitry Andric   case APValue::Struct: {
6341e8d8bef9SDimitry Andric     const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6342e8d8bef9SDimitry Andric     assert(RD && "unexpected type for record value");
6343e8d8bef9SDimitry Andric 
6344e8d8bef9SDimitry Andric     // Drop trailing zero-initialized elements.
634581ad6265SDimitry Andric     llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());
6346e8d8bef9SDimitry Andric     while (
6347e8d8bef9SDimitry Andric         !Fields.empty() &&
63480fca6ea1SDimitry Andric         (Fields.back()->isUnnamedBitField() ||
6349e8d8bef9SDimitry Andric          isZeroInitialized(Fields.back()->getType(),
6350e8d8bef9SDimitry Andric                            V.getStructField(Fields.back()->getFieldIndex())))) {
6351e8d8bef9SDimitry Andric       Fields.pop_back();
6352e8d8bef9SDimitry Andric     }
6353e8d8bef9SDimitry Andric     llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
6354e8d8bef9SDimitry Andric     if (Fields.empty()) {
6355e8d8bef9SDimitry Andric       while (!Bases.empty() &&
6356e8d8bef9SDimitry Andric              isZeroInitialized(Bases.back().getType(),
6357e8d8bef9SDimitry Andric                                V.getStructBase(Bases.size() - 1)))
6358e8d8bef9SDimitry Andric         Bases = Bases.drop_back();
6359e8d8bef9SDimitry Andric     }
6360e8d8bef9SDimitry Andric 
6361e8d8bef9SDimitry Andric     // <expression> ::= tl <type> <braced-expression>* E
6362e8d8bef9SDimitry Andric     NotPrimaryExpr();
6363e8d8bef9SDimitry Andric     Out << "tl";
6364e8d8bef9SDimitry Andric     mangleType(T);
6365e8d8bef9SDimitry Andric     for (unsigned I = 0, N = Bases.size(); I != N; ++I)
6366e8d8bef9SDimitry Andric       mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
6367e8d8bef9SDimitry Andric     for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
63680fca6ea1SDimitry Andric       if (Fields[I]->isUnnamedBitField())
6369e8d8bef9SDimitry Andric         continue;
6370e8d8bef9SDimitry Andric       mangleValueInTemplateArg(Fields[I]->getType(),
6371e8d8bef9SDimitry Andric                                V.getStructField(Fields[I]->getFieldIndex()),
6372e8d8bef9SDimitry Andric                                false);
6373e8d8bef9SDimitry Andric     }
6374e8d8bef9SDimitry Andric     Out << 'E';
6375e8d8bef9SDimitry Andric     break;
6376e8d8bef9SDimitry Andric   }
6377e8d8bef9SDimitry Andric 
6378e8d8bef9SDimitry Andric   case APValue::Union: {
6379e8d8bef9SDimitry Andric     assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
6380e8d8bef9SDimitry Andric     const FieldDecl *FD = V.getUnionField();
6381e8d8bef9SDimitry Andric 
6382e8d8bef9SDimitry Andric     if (!FD) {
6383e8d8bef9SDimitry Andric       Out << 'L';
6384e8d8bef9SDimitry Andric       mangleType(T);
6385e8d8bef9SDimitry Andric       Out << 'E';
6386e8d8bef9SDimitry Andric       break;
6387e8d8bef9SDimitry Andric     }
6388e8d8bef9SDimitry Andric 
6389e8d8bef9SDimitry Andric     // <braced-expression> ::= di <field source-name> <braced-expression>
6390e8d8bef9SDimitry Andric     NotPrimaryExpr();
6391e8d8bef9SDimitry Andric     Out << "tl";
6392e8d8bef9SDimitry Andric     mangleType(T);
6393e8d8bef9SDimitry Andric     if (!isZeroInitialized(T, V)) {
6394e8d8bef9SDimitry Andric       Out << "di";
639581ad6265SDimitry Andric       IdentifierInfo *II = (getUnionInitName(
639681ad6265SDimitry Andric           T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
639781ad6265SDimitry Andric       if (II)
639881ad6265SDimitry Andric         mangleSourceName(II);
6399e8d8bef9SDimitry Andric       mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
6400e8d8bef9SDimitry Andric     }
6401e8d8bef9SDimitry Andric     Out << 'E';
6402e8d8bef9SDimitry Andric     break;
6403e8d8bef9SDimitry Andric   }
6404e8d8bef9SDimitry Andric 
6405e8d8bef9SDimitry Andric   case APValue::Array: {
6406e8d8bef9SDimitry Andric     QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6407e8d8bef9SDimitry Andric 
6408e8d8bef9SDimitry Andric     NotPrimaryExpr();
6409e8d8bef9SDimitry Andric     Out << "tl";
6410e8d8bef9SDimitry Andric     mangleType(T);
6411e8d8bef9SDimitry Andric 
6412e8d8bef9SDimitry Andric     // Drop trailing zero-initialized elements.
6413e8d8bef9SDimitry Andric     unsigned N = V.getArraySize();
6414e8d8bef9SDimitry Andric     if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
6415e8d8bef9SDimitry Andric       N = V.getArrayInitializedElts();
6416e8d8bef9SDimitry Andric       while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
6417e8d8bef9SDimitry Andric         --N;
6418e8d8bef9SDimitry Andric     }
6419e8d8bef9SDimitry Andric 
6420e8d8bef9SDimitry Andric     for (unsigned I = 0; I != N; ++I) {
6421e8d8bef9SDimitry Andric       const APValue &Elem = I < V.getArrayInitializedElts()
6422e8d8bef9SDimitry Andric                                 ? V.getArrayInitializedElt(I)
6423e8d8bef9SDimitry Andric                                 : V.getArrayFiller();
6424e8d8bef9SDimitry Andric       mangleValueInTemplateArg(ElemT, Elem, false);
6425e8d8bef9SDimitry Andric     }
6426e8d8bef9SDimitry Andric     Out << 'E';
6427e8d8bef9SDimitry Andric     break;
6428e8d8bef9SDimitry Andric   }
6429e8d8bef9SDimitry Andric 
6430e8d8bef9SDimitry Andric   case APValue::Vector: {
6431e8d8bef9SDimitry Andric     const VectorType *VT = T->castAs<VectorType>();
6432e8d8bef9SDimitry Andric 
6433e8d8bef9SDimitry Andric     NotPrimaryExpr();
6434e8d8bef9SDimitry Andric     Out << "tl";
6435e8d8bef9SDimitry Andric     mangleType(T);
6436e8d8bef9SDimitry Andric     unsigned N = V.getVectorLength();
6437e8d8bef9SDimitry Andric     while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
6438e8d8bef9SDimitry Andric       --N;
6439e8d8bef9SDimitry Andric     for (unsigned I = 0; I != N; ++I)
6440e8d8bef9SDimitry Andric       mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
6441e8d8bef9SDimitry Andric     Out << 'E';
6442e8d8bef9SDimitry Andric     break;
6443e8d8bef9SDimitry Andric   }
6444e8d8bef9SDimitry Andric 
6445e8d8bef9SDimitry Andric   case APValue::Int:
6446e8d8bef9SDimitry Andric     mangleIntegerLiteral(T, V.getInt());
6447e8d8bef9SDimitry Andric     break;
6448e8d8bef9SDimitry Andric 
6449e8d8bef9SDimitry Andric   case APValue::Float:
6450e8d8bef9SDimitry Andric     mangleFloatLiteral(T, V.getFloat());
6451e8d8bef9SDimitry Andric     break;
6452e8d8bef9SDimitry Andric 
6453e8d8bef9SDimitry Andric   case APValue::FixedPoint:
6454e8d8bef9SDimitry Andric     mangleFixedPointLiteral();
6455e8d8bef9SDimitry Andric     break;
6456e8d8bef9SDimitry Andric 
6457e8d8bef9SDimitry Andric   case APValue::ComplexFloat: {
6458e8d8bef9SDimitry Andric     const ComplexType *CT = T->castAs<ComplexType>();
6459e8d8bef9SDimitry Andric     NotPrimaryExpr();
6460e8d8bef9SDimitry Andric     Out << "tl";
6461e8d8bef9SDimitry Andric     mangleType(T);
6462e8d8bef9SDimitry Andric     if (!V.getComplexFloatReal().isPosZero() ||
6463e8d8bef9SDimitry Andric         !V.getComplexFloatImag().isPosZero())
6464e8d8bef9SDimitry Andric       mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
6465e8d8bef9SDimitry Andric     if (!V.getComplexFloatImag().isPosZero())
6466e8d8bef9SDimitry Andric       mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
6467e8d8bef9SDimitry Andric     Out << 'E';
6468e8d8bef9SDimitry Andric     break;
6469e8d8bef9SDimitry Andric   }
6470e8d8bef9SDimitry Andric 
6471e8d8bef9SDimitry Andric   case APValue::ComplexInt: {
6472e8d8bef9SDimitry Andric     const ComplexType *CT = T->castAs<ComplexType>();
6473e8d8bef9SDimitry Andric     NotPrimaryExpr();
6474e8d8bef9SDimitry Andric     Out << "tl";
6475e8d8bef9SDimitry Andric     mangleType(T);
6476e8d8bef9SDimitry Andric     if (V.getComplexIntReal().getBoolValue() ||
6477e8d8bef9SDimitry Andric         V.getComplexIntImag().getBoolValue())
6478e8d8bef9SDimitry Andric       mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
6479e8d8bef9SDimitry Andric     if (V.getComplexIntImag().getBoolValue())
6480e8d8bef9SDimitry Andric       mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
6481e8d8bef9SDimitry Andric     Out << 'E';
6482e8d8bef9SDimitry Andric     break;
6483e8d8bef9SDimitry Andric   }
6484e8d8bef9SDimitry Andric 
6485e8d8bef9SDimitry Andric   case APValue::LValue: {
6486e8d8bef9SDimitry Andric     // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6487e8d8bef9SDimitry Andric     assert((T->isPointerType() || T->isReferenceType()) &&
6488e8d8bef9SDimitry Andric            "unexpected type for LValue template arg");
6489e8d8bef9SDimitry Andric 
6490e8d8bef9SDimitry Andric     if (V.isNullPointer()) {
6491e8d8bef9SDimitry Andric       mangleNullPointer(T);
6492e8d8bef9SDimitry Andric       break;
6493e8d8bef9SDimitry Andric     }
6494e8d8bef9SDimitry Andric 
6495e8d8bef9SDimitry Andric     APValue::LValueBase B = V.getLValueBase();
6496e8d8bef9SDimitry Andric     if (!B) {
6497e8d8bef9SDimitry Andric       // Non-standard mangling for integer cast to a pointer; this can only
6498e8d8bef9SDimitry Andric       // occur as an extension.
6499e8d8bef9SDimitry Andric       CharUnits Offset = V.getLValueOffset();
6500e8d8bef9SDimitry Andric       if (Offset.isZero()) {
6501e8d8bef9SDimitry Andric         // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
6502e8d8bef9SDimitry Andric         // a cast, because L <type> 0 E means something else.
6503e8d8bef9SDimitry Andric         NotPrimaryExpr();
6504e8d8bef9SDimitry Andric         Out << "rc";
6505e8d8bef9SDimitry Andric         mangleType(T);
6506e8d8bef9SDimitry Andric         Out << "Li0E";
6507e8d8bef9SDimitry Andric         if (TopLevel)
6508e8d8bef9SDimitry Andric           Out << 'E';
6509e8d8bef9SDimitry Andric       } else {
6510e8d8bef9SDimitry Andric         Out << "L";
6511e8d8bef9SDimitry Andric         mangleType(T);
6512e8d8bef9SDimitry Andric         Out << Offset.getQuantity() << 'E';
6513e8d8bef9SDimitry Andric       }
6514e8d8bef9SDimitry Andric       break;
6515e8d8bef9SDimitry Andric     }
6516e8d8bef9SDimitry Andric 
6517e8d8bef9SDimitry Andric     ASTContext &Ctx = Context.getASTContext();
6518e8d8bef9SDimitry Andric 
6519e8d8bef9SDimitry Andric     enum { Base, Offset, Path } Kind;
6520e8d8bef9SDimitry Andric     if (!V.hasLValuePath()) {
6521e8d8bef9SDimitry Andric       // Mangle as (T*)((char*)&base + N).
6522e8d8bef9SDimitry Andric       if (T->isReferenceType()) {
6523e8d8bef9SDimitry Andric         NotPrimaryExpr();
6524e8d8bef9SDimitry Andric         Out << "decvP";
6525e8d8bef9SDimitry Andric         mangleType(T->getPointeeType());
6526e8d8bef9SDimitry Andric       } else {
6527e8d8bef9SDimitry Andric         NotPrimaryExpr();
6528e8d8bef9SDimitry Andric         Out << "cv";
6529e8d8bef9SDimitry Andric         mangleType(T);
6530e8d8bef9SDimitry Andric       }
6531e8d8bef9SDimitry Andric       Out << "plcvPcad";
6532e8d8bef9SDimitry Andric       Kind = Offset;
6533e8d8bef9SDimitry Andric     } else {
65347a6dacacSDimitry Andric       // Clang 11 and before mangled an array subject to array-to-pointer decay
65357a6dacacSDimitry Andric       // as if it were the declaration itself.
65367a6dacacSDimitry Andric       bool IsArrayToPointerDecayMangledAsDecl = false;
65377a6dacacSDimitry Andric       if (TopLevel && Ctx.getLangOpts().getClangABICompat() <=
65387a6dacacSDimitry Andric                           LangOptions::ClangABI::Ver11) {
65397a6dacacSDimitry Andric         QualType BType = B.getType();
65407a6dacacSDimitry Andric         IsArrayToPointerDecayMangledAsDecl =
65417a6dacacSDimitry Andric             BType->isArrayType() && V.getLValuePath().size() == 1 &&
65427a6dacacSDimitry Andric             V.getLValuePath()[0].getAsArrayIndex() == 0 &&
65437a6dacacSDimitry Andric             Ctx.hasSimilarType(T, Ctx.getDecayedType(BType));
65447a6dacacSDimitry Andric       }
65457a6dacacSDimitry Andric 
65467a6dacacSDimitry Andric       if ((!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) &&
65477a6dacacSDimitry Andric           !IsArrayToPointerDecayMangledAsDecl) {
6548e8d8bef9SDimitry Andric         NotPrimaryExpr();
6549e8d8bef9SDimitry Andric         // A final conversion to the template parameter's type is usually
6550e8d8bef9SDimitry Andric         // folded into the 'so' mangling, but we can't do that for 'void*'
6551e8d8bef9SDimitry Andric         // parameters without introducing collisions.
6552e8d8bef9SDimitry Andric         if (NeedExactType && T->isVoidPointerType()) {
6553e8d8bef9SDimitry Andric           Out << "cv";
6554e8d8bef9SDimitry Andric           mangleType(T);
6555e8d8bef9SDimitry Andric         }
6556e8d8bef9SDimitry Andric         if (T->isPointerType())
6557e8d8bef9SDimitry Andric           Out << "ad";
6558e8d8bef9SDimitry Andric         Out << "so";
6559e8d8bef9SDimitry Andric         mangleType(T->isVoidPointerType()
6560e8d8bef9SDimitry Andric                        ? getLValueType(Ctx, V).getUnqualifiedType()
6561e8d8bef9SDimitry Andric                        : T->getPointeeType());
6562e8d8bef9SDimitry Andric         Kind = Path;
6563e8d8bef9SDimitry Andric       } else {
6564e8d8bef9SDimitry Andric         if (NeedExactType &&
6565e8d8bef9SDimitry Andric             !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
65665f757f3fSDimitry Andric             !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6567e8d8bef9SDimitry Andric           NotPrimaryExpr();
6568e8d8bef9SDimitry Andric           Out << "cv";
6569e8d8bef9SDimitry Andric           mangleType(T);
6570e8d8bef9SDimitry Andric         }
6571e8d8bef9SDimitry Andric         if (T->isPointerType()) {
6572e8d8bef9SDimitry Andric           NotPrimaryExpr();
6573e8d8bef9SDimitry Andric           Out << "ad";
6574e8d8bef9SDimitry Andric         }
6575e8d8bef9SDimitry Andric         Kind = Base;
6576e8d8bef9SDimitry Andric       }
6577e8d8bef9SDimitry Andric     }
6578e8d8bef9SDimitry Andric 
6579e8d8bef9SDimitry Andric     QualType TypeSoFar = B.getType();
6580e8d8bef9SDimitry Andric     if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
6581e8d8bef9SDimitry Andric       Out << 'L';
6582e8d8bef9SDimitry Andric       mangle(VD);
6583e8d8bef9SDimitry Andric       Out << 'E';
6584e8d8bef9SDimitry Andric     } else if (auto *E = B.dyn_cast<const Expr*>()) {
6585e8d8bef9SDimitry Andric       NotPrimaryExpr();
6586e8d8bef9SDimitry Andric       mangleExpression(E);
6587e8d8bef9SDimitry Andric     } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
6588e8d8bef9SDimitry Andric       NotPrimaryExpr();
6589e8d8bef9SDimitry Andric       Out << "ti";
6590e8d8bef9SDimitry Andric       mangleType(QualType(TI.getType(), 0));
6591e8d8bef9SDimitry Andric     } else {
6592e8d8bef9SDimitry Andric       // We should never see dynamic allocations here.
6593e8d8bef9SDimitry Andric       llvm_unreachable("unexpected lvalue base kind in template argument");
6594e8d8bef9SDimitry Andric     }
6595e8d8bef9SDimitry Andric 
6596e8d8bef9SDimitry Andric     switch (Kind) {
6597e8d8bef9SDimitry Andric     case Base:
6598e8d8bef9SDimitry Andric       break;
6599e8d8bef9SDimitry Andric 
6600e8d8bef9SDimitry Andric     case Offset:
6601e8d8bef9SDimitry Andric       Out << 'L';
6602e8d8bef9SDimitry Andric       mangleType(Ctx.getPointerDiffType());
6603e8d8bef9SDimitry Andric       mangleNumber(V.getLValueOffset().getQuantity());
6604e8d8bef9SDimitry Andric       Out << 'E';
6605e8d8bef9SDimitry Andric       break;
6606e8d8bef9SDimitry Andric 
6607e8d8bef9SDimitry Andric     case Path:
6608e8d8bef9SDimitry Andric       // <expression> ::= so <referent type> <expr> [<offset number>]
6609e8d8bef9SDimitry Andric       //                  <union-selector>* [p] E
6610e8d8bef9SDimitry Andric       if (!V.getLValueOffset().isZero())
6611e8d8bef9SDimitry Andric         mangleNumber(V.getLValueOffset().getQuantity());
6612e8d8bef9SDimitry Andric 
6613e8d8bef9SDimitry Andric       // We model a past-the-end array pointer as array indexing with index N,
6614e8d8bef9SDimitry Andric       // not with the "past the end" flag. Compensate for that.
6615e8d8bef9SDimitry Andric       bool OnePastTheEnd = V.isLValueOnePastTheEnd();
6616e8d8bef9SDimitry Andric 
6617e8d8bef9SDimitry Andric       for (APValue::LValuePathEntry E : V.getLValuePath()) {
6618e8d8bef9SDimitry Andric         if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
6619e8d8bef9SDimitry Andric           if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
6620e8d8bef9SDimitry Andric             OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
6621e8d8bef9SDimitry Andric           TypeSoFar = AT->getElementType();
6622e8d8bef9SDimitry Andric         } else {
6623e8d8bef9SDimitry Andric           const Decl *D = E.getAsBaseOrMember().getPointer();
6624e8d8bef9SDimitry Andric           if (auto *FD = dyn_cast<FieldDecl>(D)) {
6625e8d8bef9SDimitry Andric             // <union-selector> ::= _ <number>
6626e8d8bef9SDimitry Andric             if (FD->getParent()->isUnion()) {
6627e8d8bef9SDimitry Andric               Out << '_';
6628e8d8bef9SDimitry Andric               if (FD->getFieldIndex())
6629e8d8bef9SDimitry Andric                 Out << (FD->getFieldIndex() - 1);
6630e8d8bef9SDimitry Andric             }
6631e8d8bef9SDimitry Andric             TypeSoFar = FD->getType();
6632e8d8bef9SDimitry Andric           } else {
6633e8d8bef9SDimitry Andric             TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));
6634e8d8bef9SDimitry Andric           }
6635e8d8bef9SDimitry Andric         }
6636e8d8bef9SDimitry Andric       }
6637e8d8bef9SDimitry Andric 
6638e8d8bef9SDimitry Andric       if (OnePastTheEnd)
6639e8d8bef9SDimitry Andric         Out << 'p';
6640e8d8bef9SDimitry Andric       Out << 'E';
6641e8d8bef9SDimitry Andric       break;
6642e8d8bef9SDimitry Andric     }
6643e8d8bef9SDimitry Andric 
6644e8d8bef9SDimitry Andric     break;
6645e8d8bef9SDimitry Andric   }
6646e8d8bef9SDimitry Andric 
6647e8d8bef9SDimitry Andric   case APValue::MemberPointer:
6648e8d8bef9SDimitry Andric     // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6649e8d8bef9SDimitry Andric     if (!V.getMemberPointerDecl()) {
6650e8d8bef9SDimitry Andric       mangleNullPointer(T);
6651e8d8bef9SDimitry Andric       break;
6652e8d8bef9SDimitry Andric     }
6653e8d8bef9SDimitry Andric 
6654e8d8bef9SDimitry Andric     ASTContext &Ctx = Context.getASTContext();
6655e8d8bef9SDimitry Andric 
6656e8d8bef9SDimitry Andric     NotPrimaryExpr();
6657e8d8bef9SDimitry Andric     if (!V.getMemberPointerPath().empty()) {
6658e8d8bef9SDimitry Andric       Out << "mc";
6659e8d8bef9SDimitry Andric       mangleType(T);
6660e8d8bef9SDimitry Andric     } else if (NeedExactType &&
6661e8d8bef9SDimitry Andric                !Ctx.hasSameType(
6662e8d8bef9SDimitry Andric                    T->castAs<MemberPointerType>()->getPointeeType(),
6663e8d8bef9SDimitry Andric                    V.getMemberPointerDecl()->getType()) &&
66645f757f3fSDimitry Andric                !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6665e8d8bef9SDimitry Andric       Out << "cv";
6666e8d8bef9SDimitry Andric       mangleType(T);
6667e8d8bef9SDimitry Andric     }
6668e8d8bef9SDimitry Andric     Out << "adL";
6669e8d8bef9SDimitry Andric     mangle(V.getMemberPointerDecl());
6670e8d8bef9SDimitry Andric     Out << 'E';
6671e8d8bef9SDimitry Andric     if (!V.getMemberPointerPath().empty()) {
6672e8d8bef9SDimitry Andric       CharUnits Offset =
6673e8d8bef9SDimitry Andric           Context.getASTContext().getMemberPointerPathAdjustment(V);
6674e8d8bef9SDimitry Andric       if (!Offset.isZero())
6675e8d8bef9SDimitry Andric         mangleNumber(Offset.getQuantity());
6676e8d8bef9SDimitry Andric       Out << 'E';
6677e8d8bef9SDimitry Andric     }
6678e8d8bef9SDimitry Andric     break;
6679e8d8bef9SDimitry Andric   }
6680e8d8bef9SDimitry Andric 
6681e8d8bef9SDimitry Andric   if (TopLevel && !IsPrimaryExpr)
6682e8d8bef9SDimitry Andric     Out << 'E';
6683e8d8bef9SDimitry Andric }
6684e8d8bef9SDimitry Andric 
mangleTemplateParameter(unsigned Depth,unsigned Index)6685a7dea167SDimitry Andric void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
66860b57cec5SDimitry Andric   // <template-param> ::= T_    # first template parameter
66870b57cec5SDimitry Andric   //                  ::= T <parameter-2 non-negative number> _
6688a7dea167SDimitry Andric   //                  ::= TL <L-1 non-negative number> __
6689a7dea167SDimitry Andric   //                  ::= TL <L-1 non-negative number> _
6690a7dea167SDimitry Andric   //                         <parameter-2 non-negative number> _
6691a7dea167SDimitry Andric   //
6692a7dea167SDimitry Andric   // The latter two manglings are from a proposal here:
6693a7dea167SDimitry Andric   // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
6694a7dea167SDimitry Andric   Out << 'T';
66955f757f3fSDimitry Andric   Depth += TemplateDepthOffset;
6696a7dea167SDimitry Andric   if (Depth != 0)
6697a7dea167SDimitry Andric     Out << 'L' << (Depth - 1) << '_';
6698a7dea167SDimitry Andric   if (Index != 0)
6699a7dea167SDimitry Andric     Out << (Index - 1);
6700a7dea167SDimitry Andric   Out << '_';
67010b57cec5SDimitry Andric }
67020b57cec5SDimitry Andric 
mangleSeqID(unsigned SeqID)67030b57cec5SDimitry Andric void CXXNameMangler::mangleSeqID(unsigned SeqID) {
670404eeddc0SDimitry Andric   if (SeqID == 0) {
670504eeddc0SDimitry Andric     // Nothing.
670604eeddc0SDimitry Andric   } else if (SeqID == 1) {
67070b57cec5SDimitry Andric     Out << '0';
670804eeddc0SDimitry Andric   } else {
67090b57cec5SDimitry Andric     SeqID--;
67100b57cec5SDimitry Andric 
67110b57cec5SDimitry Andric     // <seq-id> is encoded in base-36, using digits and upper case letters.
67120b57cec5SDimitry Andric     char Buffer[7]; // log(2**32) / log(36) ~= 7
67130b57cec5SDimitry Andric     MutableArrayRef<char> BufferRef(Buffer);
67140b57cec5SDimitry Andric     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
67150b57cec5SDimitry Andric 
67160b57cec5SDimitry Andric     for (; SeqID != 0; SeqID /= 36) {
67170b57cec5SDimitry Andric       unsigned C = SeqID % 36;
67180b57cec5SDimitry Andric       *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
67190b57cec5SDimitry Andric     }
67200b57cec5SDimitry Andric 
67210b57cec5SDimitry Andric     Out.write(I.base(), I - BufferRef.rbegin());
67220b57cec5SDimitry Andric   }
67230b57cec5SDimitry Andric   Out << '_';
67240b57cec5SDimitry Andric }
67250b57cec5SDimitry Andric 
mangleExistingSubstitution(TemplateName tname)67260b57cec5SDimitry Andric void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
67270b57cec5SDimitry Andric   bool result = mangleSubstitution(tname);
67280b57cec5SDimitry Andric   assert(result && "no existing substitution for template name");
67290b57cec5SDimitry Andric   (void) result;
67300b57cec5SDimitry Andric }
67310b57cec5SDimitry Andric 
67320b57cec5SDimitry Andric // <substitution> ::= S <seq-id> _
67330b57cec5SDimitry Andric //                ::= S_
mangleSubstitution(const NamedDecl * ND)67340b57cec5SDimitry Andric bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
67350b57cec5SDimitry Andric   // Try one of the standard substitutions first.
67360b57cec5SDimitry Andric   if (mangleStandardSubstitution(ND))
67370b57cec5SDimitry Andric     return true;
67380b57cec5SDimitry Andric 
67390b57cec5SDimitry Andric   ND = cast<NamedDecl>(ND->getCanonicalDecl());
67400b57cec5SDimitry Andric   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
67410b57cec5SDimitry Andric }
67420b57cec5SDimitry Andric 
mangleSubstitution(NestedNameSpecifier * NNS)674381ad6265SDimitry Andric bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {
674481ad6265SDimitry Andric   assert(NNS->getKind() == NestedNameSpecifier::Identifier &&
674581ad6265SDimitry Andric          "mangleSubstitution(NestedNameSpecifier *) is only used for "
674681ad6265SDimitry Andric          "identifier nested name specifiers.");
674781ad6265SDimitry Andric   NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
674881ad6265SDimitry Andric   return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS));
674981ad6265SDimitry Andric }
675081ad6265SDimitry Andric 
67510b57cec5SDimitry Andric /// Determine whether the given type has any qualifiers that are relevant for
67520b57cec5SDimitry Andric /// substitutions.
hasMangledSubstitutionQualifiers(QualType T)67530b57cec5SDimitry Andric static bool hasMangledSubstitutionQualifiers(QualType T) {
67540b57cec5SDimitry Andric   Qualifiers Qs = T.getQualifiers();
67550b57cec5SDimitry Andric   return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
67560b57cec5SDimitry Andric }
67570b57cec5SDimitry Andric 
mangleSubstitution(QualType T)67580b57cec5SDimitry Andric bool CXXNameMangler::mangleSubstitution(QualType T) {
67590b57cec5SDimitry Andric   if (!hasMangledSubstitutionQualifiers(T)) {
67600b57cec5SDimitry Andric     if (const RecordType *RT = T->getAs<RecordType>())
67610b57cec5SDimitry Andric       return mangleSubstitution(RT->getDecl());
67620b57cec5SDimitry Andric   }
67630b57cec5SDimitry Andric 
67640b57cec5SDimitry Andric   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
67650b57cec5SDimitry Andric 
67660b57cec5SDimitry Andric   return mangleSubstitution(TypePtr);
67670b57cec5SDimitry Andric }
67680b57cec5SDimitry Andric 
mangleSubstitution(TemplateName Template)67690b57cec5SDimitry Andric bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
67700b57cec5SDimitry Andric   if (TemplateDecl *TD = Template.getAsTemplateDecl())
67710b57cec5SDimitry Andric     return mangleSubstitution(TD);
67720b57cec5SDimitry Andric 
67730b57cec5SDimitry Andric   Template = Context.getASTContext().getCanonicalTemplateName(Template);
67740b57cec5SDimitry Andric   return mangleSubstitution(
67750b57cec5SDimitry Andric                       reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
67760b57cec5SDimitry Andric }
67770b57cec5SDimitry Andric 
mangleSubstitution(uintptr_t Ptr)67780b57cec5SDimitry Andric bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
67790b57cec5SDimitry Andric   llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
67800b57cec5SDimitry Andric   if (I == Substitutions.end())
67810b57cec5SDimitry Andric     return false;
67820b57cec5SDimitry Andric 
67830b57cec5SDimitry Andric   unsigned SeqID = I->second;
67840b57cec5SDimitry Andric   Out << 'S';
67850b57cec5SDimitry Andric   mangleSeqID(SeqID);
67860b57cec5SDimitry Andric 
67870b57cec5SDimitry Andric   return true;
67880b57cec5SDimitry Andric }
67890b57cec5SDimitry Andric 
67902a66634dSDimitry Andric /// Returns whether S is a template specialization of std::Name with a single
67912a66634dSDimitry Andric /// argument of type A.
isSpecializedAs(QualType S,llvm::StringRef Name,QualType A)67922a66634dSDimitry Andric bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,
67932a66634dSDimitry Andric                                      QualType A) {
67942a66634dSDimitry Andric   if (S.isNull())
67950b57cec5SDimitry Andric     return false;
67960b57cec5SDimitry Andric 
67972a66634dSDimitry Andric   const RecordType *RT = S->getAs<RecordType>();
67980b57cec5SDimitry Andric   if (!RT)
67990b57cec5SDimitry Andric     return false;
68000b57cec5SDimitry Andric 
68010b57cec5SDimitry Andric   const ClassTemplateSpecializationDecl *SD =
68020b57cec5SDimitry Andric     dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
68032a66634dSDimitry Andric   if (!SD || !SD->getIdentifier()->isStr(Name))
68040b57cec5SDimitry Andric     return false;
68050b57cec5SDimitry Andric 
68062a66634dSDimitry Andric   if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
68070b57cec5SDimitry Andric     return false;
68080b57cec5SDimitry Andric 
68090b57cec5SDimitry Andric   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
68100b57cec5SDimitry Andric   if (TemplateArgs.size() != 1)
68110b57cec5SDimitry Andric     return false;
68120b57cec5SDimitry Andric 
68132a66634dSDimitry Andric   if (TemplateArgs[0].getAsType() != A)
68140b57cec5SDimitry Andric     return false;
68150b57cec5SDimitry Andric 
681681ad6265SDimitry Andric   if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
681781ad6265SDimitry Andric     return false;
681881ad6265SDimitry Andric 
68192a66634dSDimitry Andric   return true;
68200b57cec5SDimitry Andric }
68210b57cec5SDimitry Andric 
68222a66634dSDimitry Andric /// Returns whether SD is a template specialization std::Name<char,
68232a66634dSDimitry Andric /// std::char_traits<char> [, std::allocator<char>]>
68242a66634dSDimitry Andric /// HasAllocator controls whether the 3rd template argument is needed.
isStdCharSpecialization(const ClassTemplateSpecializationDecl * SD,llvm::StringRef Name,bool HasAllocator)68252a66634dSDimitry Andric bool CXXNameMangler::isStdCharSpecialization(
68262a66634dSDimitry Andric     const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,
68272a66634dSDimitry Andric     bool HasAllocator) {
68282a66634dSDimitry Andric   if (!SD->getIdentifier()->isStr(Name))
68290b57cec5SDimitry Andric     return false;
68300b57cec5SDimitry Andric 
68310b57cec5SDimitry Andric   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
68322a66634dSDimitry Andric   if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
68330b57cec5SDimitry Andric     return false;
68340b57cec5SDimitry Andric 
68352a66634dSDimitry Andric   QualType A = TemplateArgs[0].getAsType();
68362a66634dSDimitry Andric   if (A.isNull())
68372a66634dSDimitry Andric     return false;
68382a66634dSDimitry Andric   // Plain 'char' is named Char_S or Char_U depending on the target ABI.
68392a66634dSDimitry Andric   if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&
68402a66634dSDimitry Andric       !A->isSpecificBuiltinType(BuiltinType::Char_U))
68410b57cec5SDimitry Andric     return false;
68420b57cec5SDimitry Andric 
68432a66634dSDimitry Andric   if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))
68442a66634dSDimitry Andric     return false;
68452a66634dSDimitry Andric 
68462a66634dSDimitry Andric   if (HasAllocator &&
68472a66634dSDimitry Andric       !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))
68480b57cec5SDimitry Andric     return false;
68490b57cec5SDimitry Andric 
685081ad6265SDimitry Andric   if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
685181ad6265SDimitry Andric     return false;
685281ad6265SDimitry Andric 
68530b57cec5SDimitry Andric   return true;
68540b57cec5SDimitry Andric }
68550b57cec5SDimitry Andric 
mangleStandardSubstitution(const NamedDecl * ND)68560b57cec5SDimitry Andric bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
68570b57cec5SDimitry Andric   // <substitution> ::= St # ::std::
68580b57cec5SDimitry Andric   if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
68590b57cec5SDimitry Andric     if (isStd(NS)) {
68600b57cec5SDimitry Andric       Out << "St";
68610b57cec5SDimitry Andric       return true;
68620b57cec5SDimitry Andric     }
68632a66634dSDimitry Andric     return false;
68640b57cec5SDimitry Andric   }
68650b57cec5SDimitry Andric 
68660b57cec5SDimitry Andric   if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
68672a66634dSDimitry Andric     if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))
68680b57cec5SDimitry Andric       return false;
68690b57cec5SDimitry Andric 
687081ad6265SDimitry Andric     if (TD->getOwningModuleForLinkage())
687181ad6265SDimitry Andric       return false;
687281ad6265SDimitry Andric 
68730b57cec5SDimitry Andric     // <substitution> ::= Sa # ::std::allocator
68740b57cec5SDimitry Andric     if (TD->getIdentifier()->isStr("allocator")) {
68750b57cec5SDimitry Andric       Out << "Sa";
68760b57cec5SDimitry Andric       return true;
68770b57cec5SDimitry Andric     }
68780b57cec5SDimitry Andric 
68790b57cec5SDimitry Andric     // <<substitution> ::= Sb # ::std::basic_string
68800b57cec5SDimitry Andric     if (TD->getIdentifier()->isStr("basic_string")) {
68810b57cec5SDimitry Andric       Out << "Sb";
68820b57cec5SDimitry Andric       return true;
68830b57cec5SDimitry Andric     }
68842a66634dSDimitry Andric     return false;
68850b57cec5SDimitry Andric   }
68860b57cec5SDimitry Andric 
68870b57cec5SDimitry Andric   if (const ClassTemplateSpecializationDecl *SD =
68880b57cec5SDimitry Andric         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
68892a66634dSDimitry Andric     if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
68900b57cec5SDimitry Andric       return false;
68910b57cec5SDimitry Andric 
689281ad6265SDimitry Andric     if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
689381ad6265SDimitry Andric       return false;
689481ad6265SDimitry Andric 
68950b57cec5SDimitry Andric     //    <substitution> ::= Ss # ::std::basic_string<char,
68960b57cec5SDimitry Andric     //                            ::std::char_traits<char>,
68970b57cec5SDimitry Andric     //                            ::std::allocator<char> >
68982a66634dSDimitry Andric     if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {
68990b57cec5SDimitry Andric       Out << "Ss";
69000b57cec5SDimitry Andric       return true;
69010b57cec5SDimitry Andric     }
69020b57cec5SDimitry Andric 
69030b57cec5SDimitry Andric     //    <substitution> ::= Si # ::std::basic_istream<char,
69040b57cec5SDimitry Andric     //                            ::std::char_traits<char> >
69052a66634dSDimitry Andric     if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {
69060b57cec5SDimitry Andric       Out << "Si";
69070b57cec5SDimitry Andric       return true;
69080b57cec5SDimitry Andric     }
69090b57cec5SDimitry Andric 
69100b57cec5SDimitry Andric     //    <substitution> ::= So # ::std::basic_ostream<char,
69110b57cec5SDimitry Andric     //                            ::std::char_traits<char> >
69122a66634dSDimitry Andric     if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {
69130b57cec5SDimitry Andric       Out << "So";
69140b57cec5SDimitry Andric       return true;
69150b57cec5SDimitry Andric     }
69160b57cec5SDimitry Andric 
69170b57cec5SDimitry Andric     //    <substitution> ::= Sd # ::std::basic_iostream<char,
69180b57cec5SDimitry Andric     //                            ::std::char_traits<char> >
69192a66634dSDimitry Andric     if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {
69200b57cec5SDimitry Andric       Out << "Sd";
69210b57cec5SDimitry Andric       return true;
69220b57cec5SDimitry Andric     }
69232a66634dSDimitry Andric     return false;
69240b57cec5SDimitry Andric   }
69252a66634dSDimitry Andric 
69260b57cec5SDimitry Andric   return false;
69270b57cec5SDimitry Andric }
69280b57cec5SDimitry Andric 
addSubstitution(QualType T)69290b57cec5SDimitry Andric void CXXNameMangler::addSubstitution(QualType T) {
69300b57cec5SDimitry Andric   if (!hasMangledSubstitutionQualifiers(T)) {
69310b57cec5SDimitry Andric     if (const RecordType *RT = T->getAs<RecordType>()) {
69320b57cec5SDimitry Andric       addSubstitution(RT->getDecl());
69330b57cec5SDimitry Andric       return;
69340b57cec5SDimitry Andric     }
69350b57cec5SDimitry Andric   }
69360b57cec5SDimitry Andric 
69370b57cec5SDimitry Andric   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
69380b57cec5SDimitry Andric   addSubstitution(TypePtr);
69390b57cec5SDimitry Andric }
69400b57cec5SDimitry Andric 
addSubstitution(TemplateName Template)69410b57cec5SDimitry Andric void CXXNameMangler::addSubstitution(TemplateName Template) {
69420b57cec5SDimitry Andric   if (TemplateDecl *TD = Template.getAsTemplateDecl())
69430b57cec5SDimitry Andric     return addSubstitution(TD);
69440b57cec5SDimitry Andric 
69450b57cec5SDimitry Andric   Template = Context.getASTContext().getCanonicalTemplateName(Template);
69460b57cec5SDimitry Andric   addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
69470b57cec5SDimitry Andric }
69480b57cec5SDimitry Andric 
addSubstitution(uintptr_t Ptr)69490b57cec5SDimitry Andric void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
69500b57cec5SDimitry Andric   assert(!Substitutions.count(Ptr) && "Substitution already exists!");
69510b57cec5SDimitry Andric   Substitutions[Ptr] = SeqID++;
69520b57cec5SDimitry Andric }
69530b57cec5SDimitry Andric 
extendSubstitutions(CXXNameMangler * Other)69540b57cec5SDimitry Andric void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
69550b57cec5SDimitry Andric   assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
69560b57cec5SDimitry Andric   if (Other->SeqID > SeqID) {
69570b57cec5SDimitry Andric     Substitutions.swap(Other->Substitutions);
69580b57cec5SDimitry Andric     SeqID = Other->SeqID;
69590b57cec5SDimitry Andric   }
69600b57cec5SDimitry Andric }
69610b57cec5SDimitry Andric 
69620b57cec5SDimitry Andric CXXNameMangler::AbiTagList
makeFunctionReturnTypeTags(const FunctionDecl * FD)69630b57cec5SDimitry Andric CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
69640b57cec5SDimitry Andric   // When derived abi tags are disabled there is no need to make any list.
69650b57cec5SDimitry Andric   if (DisableDerivedAbiTags)
69660b57cec5SDimitry Andric     return AbiTagList();
69670b57cec5SDimitry Andric 
69680b57cec5SDimitry Andric   llvm::raw_null_ostream NullOutStream;
69690b57cec5SDimitry Andric   CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
69700b57cec5SDimitry Andric   TrackReturnTypeTags.disableDerivedAbiTags();
69710b57cec5SDimitry Andric 
69720b57cec5SDimitry Andric   const FunctionProtoType *Proto =
69730b57cec5SDimitry Andric       cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
69740b57cec5SDimitry Andric   FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
69750b57cec5SDimitry Andric   TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
69760b57cec5SDimitry Andric   TrackReturnTypeTags.mangleType(Proto->getReturnType());
69770b57cec5SDimitry Andric   TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
69780b57cec5SDimitry Andric   TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
69790b57cec5SDimitry Andric 
69800b57cec5SDimitry Andric   return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
69810b57cec5SDimitry Andric }
69820b57cec5SDimitry Andric 
69830b57cec5SDimitry Andric CXXNameMangler::AbiTagList
makeVariableTypeTags(const VarDecl * VD)69840b57cec5SDimitry Andric CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
69850b57cec5SDimitry Andric   // When derived abi tags are disabled there is no need to make any list.
69860b57cec5SDimitry Andric   if (DisableDerivedAbiTags)
69870b57cec5SDimitry Andric     return AbiTagList();
69880b57cec5SDimitry Andric 
69890b57cec5SDimitry Andric   llvm::raw_null_ostream NullOutStream;
69900b57cec5SDimitry Andric   CXXNameMangler TrackVariableType(*this, NullOutStream);
69910b57cec5SDimitry Andric   TrackVariableType.disableDerivedAbiTags();
69920b57cec5SDimitry Andric 
69930b57cec5SDimitry Andric   TrackVariableType.mangleType(VD->getType());
69940b57cec5SDimitry Andric 
69950b57cec5SDimitry Andric   return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
69960b57cec5SDimitry Andric }
69970b57cec5SDimitry Andric 
shouldHaveAbiTags(ItaniumMangleContextImpl & C,const VarDecl * VD)69980b57cec5SDimitry Andric bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
69990b57cec5SDimitry Andric                                        const VarDecl *VD) {
70000b57cec5SDimitry Andric   llvm::raw_null_ostream NullOutStream;
70010b57cec5SDimitry Andric   CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
70020b57cec5SDimitry Andric   TrackAbiTags.mangle(VD);
70030b57cec5SDimitry Andric   return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
70040b57cec5SDimitry Andric }
70050b57cec5SDimitry Andric 
70060b57cec5SDimitry Andric //
70070b57cec5SDimitry Andric 
70080b57cec5SDimitry Andric /// Mangles the name of the declaration D and emits that name to the given
70090b57cec5SDimitry Andric /// output stream.
70100b57cec5SDimitry Andric ///
70110b57cec5SDimitry Andric /// If the declaration D requires a mangled name, this routine will emit that
70120b57cec5SDimitry Andric /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
70130b57cec5SDimitry Andric /// and this routine will return false. In this case, the caller should just
70140b57cec5SDimitry Andric /// emit the identifier of the declaration (\c D->getIdentifier()) as its
70150b57cec5SDimitry Andric /// name.
mangleCXXName(GlobalDecl GD,raw_ostream & Out)70165ffd83dbSDimitry Andric void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
70170b57cec5SDimitry Andric                                              raw_ostream &Out) {
70185ffd83dbSDimitry Andric   const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
7019e8d8bef9SDimitry Andric   assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&
70200b57cec5SDimitry Andric          "Invalid mangleName() call, argument is not a variable or function!");
70210b57cec5SDimitry Andric 
70220b57cec5SDimitry Andric   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
70230b57cec5SDimitry Andric                                  getASTContext().getSourceManager(),
70240b57cec5SDimitry Andric                                  "Mangling declaration");
70250b57cec5SDimitry Andric 
70265ffd83dbSDimitry Andric   if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
70275ffd83dbSDimitry Andric     auto Type = GD.getCtorType();
70285ffd83dbSDimitry Andric     CXXNameMangler Mangler(*this, Out, CD, Type);
70295ffd83dbSDimitry Andric     return Mangler.mangle(GlobalDecl(CD, Type));
70305ffd83dbSDimitry Andric   }
70315ffd83dbSDimitry Andric 
70325ffd83dbSDimitry Andric   if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
70335ffd83dbSDimitry Andric     auto Type = GD.getDtorType();
70345ffd83dbSDimitry Andric     CXXNameMangler Mangler(*this, Out, DD, Type);
70355ffd83dbSDimitry Andric     return Mangler.mangle(GlobalDecl(DD, Type));
70365ffd83dbSDimitry Andric   }
70375ffd83dbSDimitry Andric 
70380b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out, D);
70395ffd83dbSDimitry Andric   Mangler.mangle(GD);
70400b57cec5SDimitry Andric }
70410b57cec5SDimitry Andric 
mangleCXXCtorComdat(const CXXConstructorDecl * D,raw_ostream & Out)70420b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
70430b57cec5SDimitry Andric                                                    raw_ostream &Out) {
70440b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
70455ffd83dbSDimitry Andric   Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
70460b57cec5SDimitry Andric }
70470b57cec5SDimitry Andric 
mangleCXXDtorComdat(const CXXDestructorDecl * D,raw_ostream & Out)70480b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
70490b57cec5SDimitry Andric                                                    raw_ostream &Out) {
70500b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
70515ffd83dbSDimitry Andric   Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
70520b57cec5SDimitry Andric }
70530b57cec5SDimitry Andric 
70540fca6ea1SDimitry Andric /// Mangles the pointer authentication override attribute for classes
70550fca6ea1SDimitry Andric /// that have explicit overrides for the vtable authentication schema.
70560fca6ea1SDimitry Andric ///
70570fca6ea1SDimitry Andric /// The override is mangled as a parameterized vendor extension as follows
70580fca6ea1SDimitry Andric ///
70590fca6ea1SDimitry Andric ///   <type> ::= U "__vtptrauth" I
70600fca6ea1SDimitry Andric ///                 <key>
70610fca6ea1SDimitry Andric ///                 <addressDiscriminated>
70620fca6ea1SDimitry Andric ///                 <extraDiscriminator>
70630fca6ea1SDimitry Andric ///              E
70640fca6ea1SDimitry Andric ///
70650fca6ea1SDimitry Andric /// The extra discriminator encodes the explicit value derived from the
70660fca6ea1SDimitry Andric /// override schema, e.g. if the override has specified type based
70670fca6ea1SDimitry Andric /// discrimination the encoded value will be the discriminator derived from the
70680fca6ea1SDimitry Andric /// type name.
mangleOverrideDiscrimination(CXXNameMangler & Mangler,ASTContext & Context,const ThunkInfo & Thunk)70690fca6ea1SDimitry Andric static void mangleOverrideDiscrimination(CXXNameMangler &Mangler,
70700fca6ea1SDimitry Andric                                          ASTContext &Context,
70710fca6ea1SDimitry Andric                                          const ThunkInfo &Thunk) {
70720fca6ea1SDimitry Andric   auto &LangOpts = Context.getLangOpts();
70730fca6ea1SDimitry Andric   const CXXRecordDecl *ThisRD = Thunk.ThisType->getPointeeCXXRecordDecl();
70740fca6ea1SDimitry Andric   const CXXRecordDecl *PtrauthClassRD =
70750fca6ea1SDimitry Andric       Context.baseForVTableAuthentication(ThisRD);
70760fca6ea1SDimitry Andric   unsigned TypedDiscriminator =
70770fca6ea1SDimitry Andric       Context.getPointerAuthVTablePointerDiscriminator(ThisRD);
70780fca6ea1SDimitry Andric   Mangler.mangleVendorQualifier("__vtptrauth");
70790fca6ea1SDimitry Andric   auto &ManglerStream = Mangler.getStream();
70800fca6ea1SDimitry Andric   ManglerStream << "I";
70810fca6ea1SDimitry Andric   if (const auto *ExplicitAuth =
70820fca6ea1SDimitry Andric           PtrauthClassRD->getAttr<VTablePointerAuthenticationAttr>()) {
70830fca6ea1SDimitry Andric     ManglerStream << "Lj" << ExplicitAuth->getKey();
70840fca6ea1SDimitry Andric 
70850fca6ea1SDimitry Andric     if (ExplicitAuth->getAddressDiscrimination() ==
70860fca6ea1SDimitry Andric         VTablePointerAuthenticationAttr::DefaultAddressDiscrimination)
70870fca6ea1SDimitry Andric       ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;
70880fca6ea1SDimitry Andric     else
70890fca6ea1SDimitry Andric       ManglerStream << "Lb"
70900fca6ea1SDimitry Andric                     << (ExplicitAuth->getAddressDiscrimination() ==
70910fca6ea1SDimitry Andric                         VTablePointerAuthenticationAttr::AddressDiscrimination);
70920fca6ea1SDimitry Andric 
70930fca6ea1SDimitry Andric     switch (ExplicitAuth->getExtraDiscrimination()) {
70940fca6ea1SDimitry Andric     case VTablePointerAuthenticationAttr::DefaultExtraDiscrimination: {
70950fca6ea1SDimitry Andric       if (LangOpts.PointerAuthVTPtrTypeDiscrimination)
70960fca6ea1SDimitry Andric         ManglerStream << "Lj" << TypedDiscriminator;
70970fca6ea1SDimitry Andric       else
70980fca6ea1SDimitry Andric         ManglerStream << "Lj" << 0;
70990fca6ea1SDimitry Andric       break;
71000fca6ea1SDimitry Andric     }
71010fca6ea1SDimitry Andric     case VTablePointerAuthenticationAttr::TypeDiscrimination:
71020fca6ea1SDimitry Andric       ManglerStream << "Lj" << TypedDiscriminator;
71030fca6ea1SDimitry Andric       break;
71040fca6ea1SDimitry Andric     case VTablePointerAuthenticationAttr::CustomDiscrimination:
71050fca6ea1SDimitry Andric       ManglerStream << "Lj" << ExplicitAuth->getCustomDiscriminationValue();
71060fca6ea1SDimitry Andric       break;
71070fca6ea1SDimitry Andric     case VTablePointerAuthenticationAttr::NoExtraDiscrimination:
71080fca6ea1SDimitry Andric       ManglerStream << "Lj" << 0;
71090fca6ea1SDimitry Andric       break;
71100fca6ea1SDimitry Andric     }
71110fca6ea1SDimitry Andric   } else {
71120fca6ea1SDimitry Andric     ManglerStream << "Lj"
71130fca6ea1SDimitry Andric                   << (unsigned)VTablePointerAuthenticationAttr::DefaultKey;
71140fca6ea1SDimitry Andric     ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;
71150fca6ea1SDimitry Andric     if (LangOpts.PointerAuthVTPtrTypeDiscrimination)
71160fca6ea1SDimitry Andric       ManglerStream << "Lj" << TypedDiscriminator;
71170fca6ea1SDimitry Andric     else
71180fca6ea1SDimitry Andric       ManglerStream << "Lj" << 0;
71190fca6ea1SDimitry Andric   }
71200fca6ea1SDimitry Andric   ManglerStream << "E";
71210fca6ea1SDimitry Andric }
71220fca6ea1SDimitry Andric 
mangleThunk(const CXXMethodDecl * MD,const ThunkInfo & Thunk,bool ElideOverrideInfo,raw_ostream & Out)71230b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
71240b57cec5SDimitry Andric                                            const ThunkInfo &Thunk,
71250fca6ea1SDimitry Andric                                            bool ElideOverrideInfo,
71260b57cec5SDimitry Andric                                            raw_ostream &Out) {
71270b57cec5SDimitry Andric   //  <special-name> ::= T <call-offset> <base encoding>
71280b57cec5SDimitry Andric   //                      # base is the nominal target function of thunk
71290b57cec5SDimitry Andric   //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
71300b57cec5SDimitry Andric   //                      # base is the nominal target function of thunk
71310b57cec5SDimitry Andric   //                      # first call-offset is 'this' adjustment
71320b57cec5SDimitry Andric   //                      # second call-offset is result adjustment
71330b57cec5SDimitry Andric 
71340b57cec5SDimitry Andric   assert(!isa<CXXDestructorDecl>(MD) &&
71350b57cec5SDimitry Andric          "Use mangleCXXDtor for destructor decls!");
71360b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
71370b57cec5SDimitry Andric   Mangler.getStream() << "_ZT";
71380b57cec5SDimitry Andric   if (!Thunk.Return.isEmpty())
71390b57cec5SDimitry Andric     Mangler.getStream() << 'c';
71400b57cec5SDimitry Andric 
71410b57cec5SDimitry Andric   // Mangle the 'this' pointer adjustment.
71420b57cec5SDimitry Andric   Mangler.mangleCallOffset(Thunk.This.NonVirtual,
71430b57cec5SDimitry Andric                            Thunk.This.Virtual.Itanium.VCallOffsetOffset);
71440b57cec5SDimitry Andric 
71450b57cec5SDimitry Andric   // Mangle the return pointer adjustment if there is one.
71460b57cec5SDimitry Andric   if (!Thunk.Return.isEmpty())
71470b57cec5SDimitry Andric     Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
71480b57cec5SDimitry Andric                              Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
71490b57cec5SDimitry Andric 
71500b57cec5SDimitry Andric   Mangler.mangleFunctionEncoding(MD);
71510fca6ea1SDimitry Andric   if (!ElideOverrideInfo)
71520fca6ea1SDimitry Andric     mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);
71530b57cec5SDimitry Andric }
71540b57cec5SDimitry Andric 
mangleCXXDtorThunk(const CXXDestructorDecl * DD,CXXDtorType Type,const ThunkInfo & Thunk,bool ElideOverrideInfo,raw_ostream & Out)71550fca6ea1SDimitry Andric void ItaniumMangleContextImpl::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
71560fca6ea1SDimitry Andric                                                   CXXDtorType Type,
71570fca6ea1SDimitry Andric                                                   const ThunkInfo &Thunk,
71580fca6ea1SDimitry Andric                                                   bool ElideOverrideInfo,
71590fca6ea1SDimitry Andric                                                   raw_ostream &Out) {
71600b57cec5SDimitry Andric   //  <special-name> ::= T <call-offset> <base encoding>
71610b57cec5SDimitry Andric   //                      # base is the nominal target function of thunk
71620b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out, DD, Type);
71630b57cec5SDimitry Andric   Mangler.getStream() << "_ZT";
71640b57cec5SDimitry Andric 
71650fca6ea1SDimitry Andric   auto &ThisAdjustment = Thunk.This;
71660b57cec5SDimitry Andric   // Mangle the 'this' pointer adjustment.
71670b57cec5SDimitry Andric   Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
71680b57cec5SDimitry Andric                            ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
71690b57cec5SDimitry Andric 
71705ffd83dbSDimitry Andric   Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
71710fca6ea1SDimitry Andric   if (!ElideOverrideInfo)
71720fca6ea1SDimitry Andric     mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);
71730b57cec5SDimitry Andric }
71740b57cec5SDimitry Andric 
71750b57cec5SDimitry Andric /// Returns the mangled name for a guard variable for the passed in VarDecl.
mangleStaticGuardVariable(const VarDecl * D,raw_ostream & Out)71760b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
71770b57cec5SDimitry Andric                                                          raw_ostream &Out) {
71780b57cec5SDimitry Andric   //  <special-name> ::= GV <object name>       # Guard variable for one-time
71790b57cec5SDimitry Andric   //                                            # initialization
71800b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
71810b57cec5SDimitry Andric   // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
71820b57cec5SDimitry Andric   // be a bug that is fixed in trunk.
71830b57cec5SDimitry Andric   Mangler.getStream() << "_ZGV";
71840b57cec5SDimitry Andric   Mangler.mangleName(D);
71850b57cec5SDimitry Andric }
71860b57cec5SDimitry Andric 
mangleDynamicInitializer(const VarDecl * MD,raw_ostream & Out)71870b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
71880b57cec5SDimitry Andric                                                         raw_ostream &Out) {
71890b57cec5SDimitry Andric   // These symbols are internal in the Itanium ABI, so the names don't matter.
71900b57cec5SDimitry Andric   // Clang has traditionally used this symbol and allowed LLVM to adjust it to
71910b57cec5SDimitry Andric   // avoid duplicate symbols.
71920b57cec5SDimitry Andric   Out << "__cxx_global_var_init";
71930b57cec5SDimitry Andric }
71940b57cec5SDimitry Andric 
mangleDynamicAtExitDestructor(const VarDecl * D,raw_ostream & Out)71950b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
71960b57cec5SDimitry Andric                                                              raw_ostream &Out) {
71970b57cec5SDimitry Andric   // Prefix the mangling of D with __dtor_.
71980b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
71990b57cec5SDimitry Andric   Mangler.getStream() << "__dtor_";
72000b57cec5SDimitry Andric   if (shouldMangleDeclName(D))
72010b57cec5SDimitry Andric     Mangler.mangle(D);
72020b57cec5SDimitry Andric   else
72030b57cec5SDimitry Andric     Mangler.getStream() << D->getName();
72040b57cec5SDimitry Andric }
72050b57cec5SDimitry Andric 
mangleDynamicStermFinalizer(const VarDecl * D,raw_ostream & Out)72065ffd83dbSDimitry Andric void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
72075ffd83dbSDimitry Andric                                                            raw_ostream &Out) {
72085ffd83dbSDimitry Andric   // Clang generates these internal-linkage functions as part of its
72095ffd83dbSDimitry Andric   // implementation of the XL ABI.
72105ffd83dbSDimitry Andric   CXXNameMangler Mangler(*this, Out);
72115ffd83dbSDimitry Andric   Mangler.getStream() << "__finalize_";
72125ffd83dbSDimitry Andric   if (shouldMangleDeclName(D))
72135ffd83dbSDimitry Andric     Mangler.mangle(D);
72145ffd83dbSDimitry Andric   else
72155ffd83dbSDimitry Andric     Mangler.getStream() << D->getName();
72165ffd83dbSDimitry Andric }
72175ffd83dbSDimitry Andric 
mangleSEHFilterExpression(GlobalDecl EnclosingDecl,raw_ostream & Out)72180b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleSEHFilterExpression(
7219bdd1243dSDimitry Andric     GlobalDecl EnclosingDecl, raw_ostream &Out) {
72200b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
72210b57cec5SDimitry Andric   Mangler.getStream() << "__filt_";
7222bdd1243dSDimitry Andric   auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7223bdd1243dSDimitry Andric   if (shouldMangleDeclName(EnclosingFD))
72240b57cec5SDimitry Andric     Mangler.mangle(EnclosingDecl);
72250b57cec5SDimitry Andric   else
7226bdd1243dSDimitry Andric     Mangler.getStream() << EnclosingFD->getName();
72270b57cec5SDimitry Andric }
72280b57cec5SDimitry Andric 
mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,raw_ostream & Out)72290b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
7230bdd1243dSDimitry Andric     GlobalDecl EnclosingDecl, raw_ostream &Out) {
72310b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
72320b57cec5SDimitry Andric   Mangler.getStream() << "__fin_";
7233bdd1243dSDimitry Andric   auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7234bdd1243dSDimitry Andric   if (shouldMangleDeclName(EnclosingFD))
72350b57cec5SDimitry Andric     Mangler.mangle(EnclosingDecl);
72360b57cec5SDimitry Andric   else
7237bdd1243dSDimitry Andric     Mangler.getStream() << EnclosingFD->getName();
72380b57cec5SDimitry Andric }
72390b57cec5SDimitry Andric 
mangleItaniumThreadLocalInit(const VarDecl * D,raw_ostream & Out)72400b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
72410b57cec5SDimitry Andric                                                             raw_ostream &Out) {
72420b57cec5SDimitry Andric   //  <special-name> ::= TH <object name>
72430b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
72440b57cec5SDimitry Andric   Mangler.getStream() << "_ZTH";
72450b57cec5SDimitry Andric   Mangler.mangleName(D);
72460b57cec5SDimitry Andric }
72470b57cec5SDimitry Andric 
72480b57cec5SDimitry Andric void
mangleItaniumThreadLocalWrapper(const VarDecl * D,raw_ostream & Out)72490b57cec5SDimitry Andric ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
72500b57cec5SDimitry Andric                                                           raw_ostream &Out) {
72510b57cec5SDimitry Andric   //  <special-name> ::= TW <object name>
72520b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
72530b57cec5SDimitry Andric   Mangler.getStream() << "_ZTW";
72540b57cec5SDimitry Andric   Mangler.mangleName(D);
72550b57cec5SDimitry Andric }
72560b57cec5SDimitry Andric 
mangleReferenceTemporary(const VarDecl * D,unsigned ManglingNumber,raw_ostream & Out)72570b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
72580b57cec5SDimitry Andric                                                         unsigned ManglingNumber,
72590b57cec5SDimitry Andric                                                         raw_ostream &Out) {
72600b57cec5SDimitry Andric   // We match the GCC mangling here.
72610b57cec5SDimitry Andric   //  <special-name> ::= GR <object name>
72620b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
72630b57cec5SDimitry Andric   Mangler.getStream() << "_ZGR";
72640b57cec5SDimitry Andric   Mangler.mangleName(D);
72650b57cec5SDimitry Andric   assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
72660b57cec5SDimitry Andric   Mangler.mangleSeqID(ManglingNumber - 1);
72670b57cec5SDimitry Andric }
72680b57cec5SDimitry Andric 
mangleCXXVTable(const CXXRecordDecl * RD,raw_ostream & Out)72690b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
72700b57cec5SDimitry Andric                                                raw_ostream &Out) {
72710b57cec5SDimitry Andric   // <special-name> ::= TV <type>  # virtual table
72720b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
72730b57cec5SDimitry Andric   Mangler.getStream() << "_ZTV";
72740b57cec5SDimitry Andric   Mangler.mangleNameOrStandardSubstitution(RD);
72750b57cec5SDimitry Andric }
72760b57cec5SDimitry Andric 
mangleCXXVTT(const CXXRecordDecl * RD,raw_ostream & Out)72770b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
72780b57cec5SDimitry Andric                                             raw_ostream &Out) {
72790b57cec5SDimitry Andric   // <special-name> ::= TT <type>  # VTT structure
72800b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
72810b57cec5SDimitry Andric   Mangler.getStream() << "_ZTT";
72820b57cec5SDimitry Andric   Mangler.mangleNameOrStandardSubstitution(RD);
72830b57cec5SDimitry Andric }
72840b57cec5SDimitry Andric 
mangleCXXCtorVTable(const CXXRecordDecl * RD,int64_t Offset,const CXXRecordDecl * Type,raw_ostream & Out)72850b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
72860b57cec5SDimitry Andric                                                    int64_t Offset,
72870b57cec5SDimitry Andric                                                    const CXXRecordDecl *Type,
72880b57cec5SDimitry Andric                                                    raw_ostream &Out) {
72890b57cec5SDimitry Andric   // <special-name> ::= TC <type> <offset number> _ <base type>
72900b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
72910b57cec5SDimitry Andric   Mangler.getStream() << "_ZTC";
72920b57cec5SDimitry Andric   Mangler.mangleNameOrStandardSubstitution(RD);
72930b57cec5SDimitry Andric   Mangler.getStream() << Offset;
72940b57cec5SDimitry Andric   Mangler.getStream() << '_';
72950b57cec5SDimitry Andric   Mangler.mangleNameOrStandardSubstitution(Type);
72960b57cec5SDimitry Andric }
72970b57cec5SDimitry Andric 
mangleCXXRTTI(QualType Ty,raw_ostream & Out)72980b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
72990b57cec5SDimitry Andric   // <special-name> ::= TI <type>  # typeinfo structure
73000b57cec5SDimitry Andric   assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
73010b57cec5SDimitry Andric   CXXNameMangler Mangler(*this, Out);
73020b57cec5SDimitry Andric   Mangler.getStream() << "_ZTI";
73030b57cec5SDimitry Andric   Mangler.mangleType(Ty);
73040b57cec5SDimitry Andric }
73050b57cec5SDimitry Andric 
mangleCXXRTTIName(QualType Ty,raw_ostream & Out,bool NormalizeIntegers=false)730606c3fb27SDimitry Andric void ItaniumMangleContextImpl::mangleCXXRTTIName(
730706c3fb27SDimitry Andric     QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
73080b57cec5SDimitry Andric   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
730906c3fb27SDimitry Andric   CXXNameMangler Mangler(*this, Out, NormalizeIntegers);
73100b57cec5SDimitry Andric   Mangler.getStream() << "_ZTS";
73110b57cec5SDimitry Andric   Mangler.mangleType(Ty);
73120b57cec5SDimitry Andric }
73130b57cec5SDimitry Andric 
mangleCanonicalTypeName(QualType Ty,raw_ostream & Out,bool NormalizeIntegers=false)73145f757f3fSDimitry Andric void ItaniumMangleContextImpl::mangleCanonicalTypeName(
73155f757f3fSDimitry Andric     QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
731606c3fb27SDimitry Andric   mangleCXXRTTIName(Ty, Out, NormalizeIntegers);
73170b57cec5SDimitry Andric }
73180b57cec5SDimitry Andric 
mangleStringLiteral(const StringLiteral *,raw_ostream &)73190b57cec5SDimitry Andric void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
73200b57cec5SDimitry Andric   llvm_unreachable("Can't mangle string literals");
73210b57cec5SDimitry Andric }
73220b57cec5SDimitry Andric 
mangleLambdaSig(const CXXRecordDecl * Lambda,raw_ostream & Out)7323a7dea167SDimitry Andric void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
7324a7dea167SDimitry Andric                                                raw_ostream &Out) {
7325a7dea167SDimitry Andric   CXXNameMangler Mangler(*this, Out);
7326a7dea167SDimitry Andric   Mangler.mangleLambdaSig(Lambda);
7327a7dea167SDimitry Andric }
7328a7dea167SDimitry Andric 
mangleModuleInitializer(const Module * M,raw_ostream & Out)732981ad6265SDimitry Andric void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
733081ad6265SDimitry Andric                                                        raw_ostream &Out) {
733181ad6265SDimitry Andric   // <special-name> ::= GI <module-name>  # module initializer function
733281ad6265SDimitry Andric   CXXNameMangler Mangler(*this, Out);
733381ad6265SDimitry Andric   Mangler.getStream() << "_ZGI";
733481ad6265SDimitry Andric   Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
733581ad6265SDimitry Andric   if (M->isModulePartition()) {
733681ad6265SDimitry Andric     // The partition needs including, as partitions can have them too.
733781ad6265SDimitry Andric     auto Partition = M->Name.find(':');
733881ad6265SDimitry Andric     Mangler.mangleModuleNamePrefix(
733981ad6265SDimitry Andric         StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
734081ad6265SDimitry Andric         /*IsPartition*/ true);
734181ad6265SDimitry Andric   }
734281ad6265SDimitry Andric }
734381ad6265SDimitry Andric 
create(ASTContext & Context,DiagnosticsEngine & Diags,bool IsAux)7344fe6060f1SDimitry Andric ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
734581ad6265SDimitry Andric                                                    DiagnosticsEngine &Diags,
734681ad6265SDimitry Andric                                                    bool IsAux) {
7347fe6060f1SDimitry Andric   return new ItaniumMangleContextImpl(
7348fe6060f1SDimitry Andric       Context, Diags,
7349bdd1243dSDimitry Andric       [](ASTContext &, const NamedDecl *) -> std::optional<unsigned> {
7350bdd1243dSDimitry Andric         return std::nullopt;
735181ad6265SDimitry Andric       },
735281ad6265SDimitry Andric       IsAux);
7353fe6060f1SDimitry Andric }
7354fe6060f1SDimitry Andric 
7355e8d8bef9SDimitry Andric ItaniumMangleContext *
create(ASTContext & Context,DiagnosticsEngine & Diags,DiscriminatorOverrideTy DiscriminatorOverride,bool IsAux)7356fe6060f1SDimitry Andric ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,
735781ad6265SDimitry Andric                              DiscriminatorOverrideTy DiscriminatorOverride,
735881ad6265SDimitry Andric                              bool IsAux) {
735981ad6265SDimitry Andric   return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,
736081ad6265SDimitry Andric                                       IsAux);
73610b57cec5SDimitry Andric }
7362