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