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