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