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