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