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