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