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