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