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