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