1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implements C++ name mangling according to the Itanium C++ ABI,
11 // which is used in GCC 3.2 and newer (and many compilers that are
12 // ABI-compatible with GCC):
13 //
14 //   http://mentorembedded.github.io/cxx-abi/abi.html#mangling
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/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/ABI.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 
36 #define MANGLE_CHECKER 0
37 
38 #if MANGLE_CHECKER
39 #include <cxxabi.h>
40 #endif
41 
42 using namespace clang;
43 
44 namespace {
45 
46 /// Retrieve the declaration context that should be used when mangling the given
47 /// declaration.
48 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
49   // The ABI assumes that lambda closure types that occur within
50   // default arguments live in the context of the function. However, due to
51   // the way in which Clang parses and creates function declarations, this is
52   // not the case: the lambda closure type ends up living in the context
53   // where the function itself resides, because the function declaration itself
54   // had not yet been created. Fix the context here.
55   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56     if (RD->isLambda())
57       if (ParmVarDecl *ContextParam
58             = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59         return ContextParam->getDeclContext();
60   }
61 
62   // Perform the same check for block literals.
63   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64     if (ParmVarDecl *ContextParam
65           = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
66       return ContextParam->getDeclContext();
67   }
68 
69   const DeclContext *DC = D->getDeclContext();
70   if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71     return getEffectiveDeclContext(cast<Decl>(DC));
72   }
73 
74   if (const auto *VD = dyn_cast<VarDecl>(D))
75     if (VD->isExternC())
76       return VD->getASTContext().getTranslationUnitDecl();
77 
78   if (const auto *FD = dyn_cast<FunctionDecl>(D))
79     if (FD->isExternC())
80       return FD->getASTContext().getTranslationUnitDecl();
81 
82   return DC->getRedeclContext();
83 }
84 
85 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86   return getEffectiveDeclContext(cast<Decl>(DC));
87 }
88 
89 static bool isLocalContainerContext(const DeclContext *DC) {
90   return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91 }
92 
93 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
94   const DeclContext *DC = getEffectiveDeclContext(D);
95   while (!DC->isNamespace() && !DC->isTranslationUnit()) {
96     if (isLocalContainerContext(DC))
97       return dyn_cast<RecordDecl>(D);
98     D = cast<Decl>(DC);
99     DC = getEffectiveDeclContext(D);
100   }
101   return nullptr;
102 }
103 
104 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106     return ftd->getTemplatedDecl();
107 
108   return fn;
109 }
110 
111 static const NamedDecl *getStructor(const NamedDecl *decl) {
112   const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113   return (fn ? getStructor(fn) : decl);
114 }
115 
116 static bool isLambda(const NamedDecl *ND) {
117   const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
118   if (!Record)
119     return false;
120 
121   return Record->isLambda();
122 }
123 
124 static const unsigned UnknownArity = ~0U;
125 
126 class ItaniumMangleContextImpl : public ItaniumMangleContext {
127   typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
128   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
129   llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
130 
131 public:
132   explicit ItaniumMangleContextImpl(ASTContext &Context,
133                                     DiagnosticsEngine &Diags)
134       : ItaniumMangleContext(Context, Diags) {}
135 
136   /// @name Mangler Entry Points
137   /// @{
138 
139   bool shouldMangleCXXName(const NamedDecl *D) override;
140   bool shouldMangleStringLiteral(const StringLiteral *) override {
141     return false;
142   }
143   void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
144   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
145                    raw_ostream &) override;
146   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
147                           const ThisAdjustment &ThisAdjustment,
148                           raw_ostream &) override;
149   void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
150                                 raw_ostream &) override;
151   void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
152   void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
153   void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
154                            const CXXRecordDecl *Type, raw_ostream &) override;
155   void mangleCXXRTTI(QualType T, raw_ostream &) override;
156   void mangleCXXRTTIName(QualType T, raw_ostream &) override;
157   void mangleTypeName(QualType T, raw_ostream &) override;
158   void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
159                      raw_ostream &) override;
160   void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
161                      raw_ostream &) override;
162 
163   void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
164   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
165   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
166   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
167   void mangleDynamicAtExitDestructor(const VarDecl *D,
168                                      raw_ostream &Out) override;
169   void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
170                                  raw_ostream &Out) override;
171   void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
172                              raw_ostream &Out) override;
173   void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
174   void mangleItaniumThreadLocalWrapper(const VarDecl *D,
175                                        raw_ostream &) override;
176 
177   void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
178 
179   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
180     // Lambda closure types are already numbered.
181     if (isLambda(ND))
182       return false;
183 
184     // Anonymous tags are already numbered.
185     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186       if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187         return false;
188     }
189 
190     // Use the canonical number for externally visible decls.
191     if (ND->isExternallyVisible()) {
192       unsigned discriminator = getASTContext().getManglingNumber(ND);
193       if (discriminator == 1)
194         return false;
195       disc = discriminator - 2;
196       return true;
197     }
198 
199     // Make up a reasonable number for internal decls.
200     unsigned &discriminator = Uniquifier[ND];
201     if (!discriminator) {
202       const DeclContext *DC = getEffectiveDeclContext(ND);
203       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
204     }
205     if (discriminator == 1)
206       return false;
207     disc = discriminator-2;
208     return true;
209   }
210   /// @}
211 };
212 
213 /// Manage the mangling of a single name.
214 class CXXNameMangler {
215   ItaniumMangleContextImpl &Context;
216   raw_ostream &Out;
217 
218   /// The "structor" is the top-level declaration being mangled, if
219   /// that's not a template specialization; otherwise it's the pattern
220   /// for that specialization.
221   const NamedDecl *Structor;
222   unsigned StructorType;
223 
224   /// The next substitution sequence number.
225   unsigned SeqID;
226 
227   class FunctionTypeDepthState {
228     unsigned Bits;
229 
230     enum { InResultTypeMask = 1 };
231 
232   public:
233     FunctionTypeDepthState() : Bits(0) {}
234 
235     /// The number of function types we're inside.
236     unsigned getDepth() const {
237       return Bits >> 1;
238     }
239 
240     /// True if we're in the return type of the innermost function type.
241     bool isInResultType() const {
242       return Bits & InResultTypeMask;
243     }
244 
245     FunctionTypeDepthState push() {
246       FunctionTypeDepthState tmp = *this;
247       Bits = (Bits & ~InResultTypeMask) + 2;
248       return tmp;
249     }
250 
251     void enterResultType() {
252       Bits |= InResultTypeMask;
253     }
254 
255     void leaveResultType() {
256       Bits &= ~InResultTypeMask;
257     }
258 
259     void pop(FunctionTypeDepthState saved) {
260       assert(getDepth() == saved.getDepth() + 1);
261       Bits = saved.Bits;
262     }
263 
264   } FunctionTypeDepth;
265 
266   llvm::DenseMap<uintptr_t, unsigned> Substitutions;
267 
268   ASTContext &getASTContext() const { return Context.getASTContext(); }
269 
270 public:
271   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
272                  const NamedDecl *D = nullptr)
273     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
274       SeqID(0) {
275     // These can't be mangled without a ctor type or dtor type.
276     assert(!D || (!isa<CXXDestructorDecl>(D) &&
277                   !isa<CXXConstructorDecl>(D)));
278   }
279   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
280                  const CXXConstructorDecl *D, CXXCtorType Type)
281     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
282       SeqID(0) { }
283   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
284                  const CXXDestructorDecl *D, CXXDtorType Type)
285     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
286       SeqID(0) { }
287 
288 #if MANGLE_CHECKER
289   ~CXXNameMangler() {
290     if (Out.str()[0] == '\01')
291       return;
292 
293     int status = 0;
294     char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
295     assert(status == 0 && "Could not demangle mangled name!");
296     free(result);
297   }
298 #endif
299   raw_ostream &getStream() { return Out; }
300 
301   void mangle(const NamedDecl *D);
302   void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
303   void mangleNumber(const llvm::APSInt &I);
304   void mangleNumber(int64_t Number);
305   void mangleFloat(const llvm::APFloat &F);
306   void mangleFunctionEncoding(const FunctionDecl *FD);
307   void mangleSeqID(unsigned SeqID);
308   void mangleName(const NamedDecl *ND);
309   void mangleType(QualType T);
310   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
311 
312 private:
313 
314   bool mangleSubstitution(const NamedDecl *ND);
315   bool mangleSubstitution(QualType T);
316   bool mangleSubstitution(TemplateName Template);
317   bool mangleSubstitution(uintptr_t Ptr);
318 
319   void mangleExistingSubstitution(QualType type);
320   void mangleExistingSubstitution(TemplateName name);
321 
322   bool mangleStandardSubstitution(const NamedDecl *ND);
323 
324   void addSubstitution(const NamedDecl *ND) {
325     ND = cast<NamedDecl>(ND->getCanonicalDecl());
326 
327     addSubstitution(reinterpret_cast<uintptr_t>(ND));
328   }
329   void addSubstitution(QualType T);
330   void addSubstitution(TemplateName Template);
331   void addSubstitution(uintptr_t Ptr);
332 
333   void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
334                               bool recursive = false);
335   void mangleUnresolvedName(NestedNameSpecifier *qualifier,
336                             DeclarationName name,
337                             unsigned KnownArity = UnknownArity);
338 
339   void mangleName(const TemplateDecl *TD,
340                   const TemplateArgument *TemplateArgs,
341                   unsigned NumTemplateArgs);
342   void mangleUnqualifiedName(const NamedDecl *ND) {
343     mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
344   }
345   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
346                              unsigned KnownArity);
347   void mangleUnscopedName(const NamedDecl *ND);
348   void mangleUnscopedTemplateName(const TemplateDecl *ND);
349   void mangleUnscopedTemplateName(TemplateName);
350   void mangleSourceName(const IdentifierInfo *II);
351   void mangleLocalName(const Decl *D);
352   void mangleBlockForPrefix(const BlockDecl *Block);
353   void mangleUnqualifiedBlock(const BlockDecl *Block);
354   void mangleLambda(const CXXRecordDecl *Lambda);
355   void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
356                         bool NoFunction=false);
357   void mangleNestedName(const TemplateDecl *TD,
358                         const TemplateArgument *TemplateArgs,
359                         unsigned NumTemplateArgs);
360   void manglePrefix(NestedNameSpecifier *qualifier);
361   void manglePrefix(const DeclContext *DC, bool NoFunction=false);
362   void manglePrefix(QualType type);
363   void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
364   void mangleTemplatePrefix(TemplateName Template);
365   bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
366                                       StringRef Prefix = "");
367   void mangleOperatorName(DeclarationName Name, unsigned Arity);
368   void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
369   void mangleVendorQualifier(StringRef qualifier);
370   void mangleQualifiers(Qualifiers Quals);
371   void mangleRefQualifier(RefQualifierKind RefQualifier);
372 
373   void mangleObjCMethodName(const ObjCMethodDecl *MD);
374 
375   // Declare manglers for every type class.
376 #define ABSTRACT_TYPE(CLASS, PARENT)
377 #define NON_CANONICAL_TYPE(CLASS, PARENT)
378 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
379 #include "clang/AST/TypeNodes.def"
380 
381   void mangleType(const TagType*);
382   void mangleType(TemplateName);
383   static StringRef getCallingConvQualifierName(CallingConv CC);
384   void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
385   void mangleExtFunctionInfo(const FunctionType *T);
386   void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
387                               const FunctionDecl *FD = nullptr);
388   void mangleNeonVectorType(const VectorType *T);
389   void mangleAArch64NeonVectorType(const VectorType *T);
390 
391   void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
392   void mangleMemberExprBase(const Expr *base, bool isArrow);
393   void mangleMemberExpr(const Expr *base, bool isArrow,
394                         NestedNameSpecifier *qualifier,
395                         NamedDecl *firstQualifierLookup,
396                         DeclarationName name,
397                         unsigned knownArity);
398   void mangleCastExpression(const Expr *E, StringRef CastEncoding);
399   void mangleInitListElements(const InitListExpr *InitList);
400   void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
401   void mangleCXXCtorType(CXXCtorType T);
402   void mangleCXXDtorType(CXXDtorType T);
403 
404   void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
405                           unsigned NumTemplateArgs);
406   void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
407                           unsigned NumTemplateArgs);
408   void mangleTemplateArgs(const TemplateArgumentList &AL);
409   void mangleTemplateArg(TemplateArgument A);
410 
411   void mangleTemplateParameter(unsigned Index);
412 
413   void mangleFunctionParam(const ParmVarDecl *parm);
414 };
415 
416 }
417 
418 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
419   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
420   if (FD) {
421     LanguageLinkage L = FD->getLanguageLinkage();
422     // Overloadable functions need mangling.
423     if (FD->hasAttr<OverloadableAttr>())
424       return true;
425 
426     // "main" is not mangled.
427     if (FD->isMain())
428       return false;
429 
430     // C++ functions and those whose names are not a simple identifier need
431     // mangling.
432     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
433       return true;
434 
435     // C functions are not mangled.
436     if (L == CLanguageLinkage)
437       return false;
438   }
439 
440   // Otherwise, no mangling is done outside C++ mode.
441   if (!getASTContext().getLangOpts().CPlusPlus)
442     return false;
443 
444   const VarDecl *VD = dyn_cast<VarDecl>(D);
445   if (VD) {
446     // C variables are not mangled.
447     if (VD->isExternC())
448       return false;
449 
450     // Variables at global scope with non-internal linkage are not mangled
451     const DeclContext *DC = getEffectiveDeclContext(D);
452     // Check for extern variable declared locally.
453     if (DC->isFunctionOrMethod() && D->hasLinkage())
454       while (!DC->isNamespace() && !DC->isTranslationUnit())
455         DC = getEffectiveParentContext(DC);
456     if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
457         !isa<VarTemplateSpecializationDecl>(D))
458       return false;
459   }
460 
461   return true;
462 }
463 
464 void CXXNameMangler::mangle(const NamedDecl *D) {
465   // <mangled-name> ::= _Z <encoding>
466   //            ::= <data name>
467   //            ::= <special-name>
468   Out << "_Z";
469   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
470     mangleFunctionEncoding(FD);
471   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
472     mangleName(VD);
473   else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
474     mangleName(IFD->getAnonField());
475   else
476     mangleName(cast<FieldDecl>(D));
477 }
478 
479 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
480   // <encoding> ::= <function name> <bare-function-type>
481   mangleName(FD);
482 
483   // Don't mangle in the type if this isn't a decl we should typically mangle.
484   if (!Context.shouldMangleDeclName(FD))
485     return;
486 
487   if (FD->hasAttr<EnableIfAttr>()) {
488     FunctionTypeDepthState Saved = FunctionTypeDepth.push();
489     Out << "Ua9enable_ifI";
490     // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
491     // it here.
492     for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
493                                          E = FD->getAttrs().rend();
494          I != E; ++I) {
495       EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
496       if (!EIA)
497         continue;
498       Out << 'X';
499       mangleExpression(EIA->getCond());
500       Out << 'E';
501     }
502     Out << 'E';
503     FunctionTypeDepth.pop(Saved);
504   }
505 
506   // Whether the mangling of a function type includes the return type depends on
507   // the context and the nature of the function. The rules for deciding whether
508   // the return type is included are:
509   //
510   //   1. Template functions (names or types) have return types encoded, with
511   //   the exceptions listed below.
512   //   2. Function types not appearing as part of a function name mangling,
513   //   e.g. parameters, pointer types, etc., have return type encoded, with the
514   //   exceptions listed below.
515   //   3. Non-template function names do not have return types encoded.
516   //
517   // The exceptions mentioned in (1) and (2) above, for which the return type is
518   // never included, are
519   //   1. Constructors.
520   //   2. Destructors.
521   //   3. Conversion operator functions, e.g. operator int.
522   bool MangleReturnType = false;
523   if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
524     if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
525           isa<CXXConversionDecl>(FD)))
526       MangleReturnType = true;
527 
528     // Mangle the type of the primary template.
529     FD = PrimaryTemplate->getTemplatedDecl();
530   }
531 
532   mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
533                          MangleReturnType, FD);
534 }
535 
536 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
537   while (isa<LinkageSpecDecl>(DC)) {
538     DC = getEffectiveParentContext(DC);
539   }
540 
541   return DC;
542 }
543 
544 /// Return whether a given namespace is the 'std' namespace.
545 static bool isStd(const NamespaceDecl *NS) {
546   if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
547                                 ->isTranslationUnit())
548     return false;
549 
550   const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
551   return II && II->isStr("std");
552 }
553 
554 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
555 // namespace.
556 static bool isStdNamespace(const DeclContext *DC) {
557   if (!DC->isNamespace())
558     return false;
559 
560   return isStd(cast<NamespaceDecl>(DC));
561 }
562 
563 static const TemplateDecl *
564 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
565   // Check if we have a function template.
566   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
567     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
568       TemplateArgs = FD->getTemplateSpecializationArgs();
569       return TD;
570     }
571   }
572 
573   // Check if we have a class template.
574   if (const ClassTemplateSpecializationDecl *Spec =
575         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
576     TemplateArgs = &Spec->getTemplateArgs();
577     return Spec->getSpecializedTemplate();
578   }
579 
580   // Check if we have a variable template.
581   if (const VarTemplateSpecializationDecl *Spec =
582           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
583     TemplateArgs = &Spec->getTemplateArgs();
584     return Spec->getSpecializedTemplate();
585   }
586 
587   return nullptr;
588 }
589 
590 void CXXNameMangler::mangleName(const NamedDecl *ND) {
591   //  <name> ::= <nested-name>
592   //         ::= <unscoped-name>
593   //         ::= <unscoped-template-name> <template-args>
594   //         ::= <local-name>
595   //
596   const DeclContext *DC = getEffectiveDeclContext(ND);
597 
598   // If this is an extern variable declared locally, the relevant DeclContext
599   // is that of the containing namespace, or the translation unit.
600   // FIXME: This is a hack; extern variables declared locally should have
601   // a proper semantic declaration context!
602   if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
603     while (!DC->isNamespace() && !DC->isTranslationUnit())
604       DC = getEffectiveParentContext(DC);
605   else if (GetLocalClassDecl(ND)) {
606     mangleLocalName(ND);
607     return;
608   }
609 
610   DC = IgnoreLinkageSpecDecls(DC);
611 
612   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
613     // Check if we have a template.
614     const TemplateArgumentList *TemplateArgs = nullptr;
615     if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
616       mangleUnscopedTemplateName(TD);
617       mangleTemplateArgs(*TemplateArgs);
618       return;
619     }
620 
621     mangleUnscopedName(ND);
622     return;
623   }
624 
625   if (isLocalContainerContext(DC)) {
626     mangleLocalName(ND);
627     return;
628   }
629 
630   mangleNestedName(ND, DC);
631 }
632 void CXXNameMangler::mangleName(const TemplateDecl *TD,
633                                 const TemplateArgument *TemplateArgs,
634                                 unsigned NumTemplateArgs) {
635   const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
636 
637   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
638     mangleUnscopedTemplateName(TD);
639     mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
640   } else {
641     mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
642   }
643 }
644 
645 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
646   //  <unscoped-name> ::= <unqualified-name>
647   //                  ::= St <unqualified-name>   # ::std::
648 
649   if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
650     Out << "St";
651 
652   mangleUnqualifiedName(ND);
653 }
654 
655 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
656   //     <unscoped-template-name> ::= <unscoped-name>
657   //                              ::= <substitution>
658   if (mangleSubstitution(ND))
659     return;
660 
661   // <template-template-param> ::= <template-param>
662   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
663     mangleTemplateParameter(TTP->getIndex());
664   else
665     mangleUnscopedName(ND->getTemplatedDecl());
666 
667   addSubstitution(ND);
668 }
669 
670 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
671   //     <unscoped-template-name> ::= <unscoped-name>
672   //                              ::= <substitution>
673   if (TemplateDecl *TD = Template.getAsTemplateDecl())
674     return mangleUnscopedTemplateName(TD);
675 
676   if (mangleSubstitution(Template))
677     return;
678 
679   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
680   assert(Dependent && "Not a dependent template name?");
681   if (const IdentifierInfo *Id = Dependent->getIdentifier())
682     mangleSourceName(Id);
683   else
684     mangleOperatorName(Dependent->getOperator(), UnknownArity);
685 
686   addSubstitution(Template);
687 }
688 
689 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
690   // ABI:
691   //   Floating-point literals are encoded using a fixed-length
692   //   lowercase hexadecimal string corresponding to the internal
693   //   representation (IEEE on Itanium), high-order bytes first,
694   //   without leading zeroes. For example: "Lf bf800000 E" is -1.0f
695   //   on Itanium.
696   // The 'without leading zeroes' thing seems to be an editorial
697   // mistake; see the discussion on cxx-abi-dev beginning on
698   // 2012-01-16.
699 
700   // Our requirements here are just barely weird enough to justify
701   // using a custom algorithm instead of post-processing APInt::toString().
702 
703   llvm::APInt valueBits = f.bitcastToAPInt();
704   unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
705   assert(numCharacters != 0);
706 
707   // Allocate a buffer of the right number of characters.
708   SmallVector<char, 20> buffer(numCharacters);
709 
710   // Fill the buffer left-to-right.
711   for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
712     // The bit-index of the next hex digit.
713     unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
714 
715     // Project out 4 bits starting at 'digitIndex'.
716     llvm::integerPart hexDigit
717       = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
718     hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
719     hexDigit &= 0xF;
720 
721     // Map that over to a lowercase hex digit.
722     static const char charForHex[16] = {
723       '0', '1', '2', '3', '4', '5', '6', '7',
724       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
725     };
726     buffer[stringIndex] = charForHex[hexDigit];
727   }
728 
729   Out.write(buffer.data(), numCharacters);
730 }
731 
732 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
733   if (Value.isSigned() && Value.isNegative()) {
734     Out << 'n';
735     Value.abs().print(Out, /*signed*/ false);
736   } else {
737     Value.print(Out, /*signed*/ false);
738   }
739 }
740 
741 void CXXNameMangler::mangleNumber(int64_t Number) {
742   //  <number> ::= [n] <non-negative decimal integer>
743   if (Number < 0) {
744     Out << 'n';
745     Number = -Number;
746   }
747 
748   Out << Number;
749 }
750 
751 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
752   //  <call-offset>  ::= h <nv-offset> _
753   //                 ::= v <v-offset> _
754   //  <nv-offset>    ::= <offset number>        # non-virtual base override
755   //  <v-offset>     ::= <offset number> _ <virtual offset number>
756   //                      # virtual base override, with vcall offset
757   if (!Virtual) {
758     Out << 'h';
759     mangleNumber(NonVirtual);
760     Out << '_';
761     return;
762   }
763 
764   Out << 'v';
765   mangleNumber(NonVirtual);
766   Out << '_';
767   mangleNumber(Virtual);
768   Out << '_';
769 }
770 
771 void CXXNameMangler::manglePrefix(QualType type) {
772   if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
773     if (!mangleSubstitution(QualType(TST, 0))) {
774       mangleTemplatePrefix(TST->getTemplateName());
775 
776       // FIXME: GCC does not appear to mangle the template arguments when
777       // the template in question is a dependent template name. Should we
778       // emulate that badness?
779       mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
780       addSubstitution(QualType(TST, 0));
781     }
782   } else if (const auto *DTST =
783                  type->getAs<DependentTemplateSpecializationType>()) {
784     if (!mangleSubstitution(QualType(DTST, 0))) {
785       TemplateName Template = getASTContext().getDependentTemplateName(
786           DTST->getQualifier(), DTST->getIdentifier());
787       mangleTemplatePrefix(Template);
788 
789       // FIXME: GCC does not appear to mangle the template arguments when
790       // the template in question is a dependent template name. Should we
791       // emulate that badness?
792       mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
793       addSubstitution(QualType(DTST, 0));
794     }
795   } else {
796     // We use the QualType mangle type variant here because it handles
797     // substitutions.
798     mangleType(type);
799   }
800 }
801 
802 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
803 ///
804 /// \param recursive - true if this is being called recursively,
805 ///   i.e. if there is more prefix "to the right".
806 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
807                                             bool recursive) {
808 
809   // x, ::x
810   // <unresolved-name> ::= [gs] <base-unresolved-name>
811 
812   // T::x / decltype(p)::x
813   // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
814 
815   // T::N::x /decltype(p)::N::x
816   // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
817   //                       <base-unresolved-name>
818 
819   // A::x, N::y, A<T>::z; "gs" means leading "::"
820   // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
821   //                       <base-unresolved-name>
822 
823   switch (qualifier->getKind()) {
824   case NestedNameSpecifier::Global:
825     Out << "gs";
826 
827     // We want an 'sr' unless this is the entire NNS.
828     if (recursive)
829       Out << "sr";
830 
831     // We never want an 'E' here.
832     return;
833 
834   case NestedNameSpecifier::Super:
835     llvm_unreachable("Can't mangle __super specifier");
836 
837   case NestedNameSpecifier::Namespace:
838     if (qualifier->getPrefix())
839       mangleUnresolvedPrefix(qualifier->getPrefix(),
840                              /*recursive*/ true);
841     else
842       Out << "sr";
843     mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
844     break;
845   case NestedNameSpecifier::NamespaceAlias:
846     if (qualifier->getPrefix())
847       mangleUnresolvedPrefix(qualifier->getPrefix(),
848                              /*recursive*/ true);
849     else
850       Out << "sr";
851     mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
852     break;
853 
854   case NestedNameSpecifier::TypeSpec:
855   case NestedNameSpecifier::TypeSpecWithTemplate: {
856     const Type *type = qualifier->getAsType();
857 
858     // We only want to use an unresolved-type encoding if this is one of:
859     //   - a decltype
860     //   - a template type parameter
861     //   - a template template parameter with arguments
862     // In all of these cases, we should have no prefix.
863     if (qualifier->getPrefix()) {
864       mangleUnresolvedPrefix(qualifier->getPrefix(),
865                              /*recursive*/ true);
866     } else {
867       // Otherwise, all the cases want this.
868       Out << "sr";
869     }
870 
871     if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
872       return;
873 
874     break;
875   }
876 
877   case NestedNameSpecifier::Identifier:
878     // Member expressions can have these without prefixes.
879     if (qualifier->getPrefix())
880       mangleUnresolvedPrefix(qualifier->getPrefix(),
881                              /*recursive*/ true);
882     else
883       Out << "sr";
884 
885     mangleSourceName(qualifier->getAsIdentifier());
886     break;
887   }
888 
889   // If this was the innermost part of the NNS, and we fell out to
890   // here, append an 'E'.
891   if (!recursive)
892     Out << 'E';
893 }
894 
895 /// Mangle an unresolved-name, which is generally used for names which
896 /// weren't resolved to specific entities.
897 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
898                                           DeclarationName name,
899                                           unsigned knownArity) {
900   if (qualifier) mangleUnresolvedPrefix(qualifier);
901   switch (name.getNameKind()) {
902     // <base-unresolved-name> ::= <simple-id>
903     case DeclarationName::Identifier:
904       mangleSourceName(name.getAsIdentifierInfo());
905       break;
906     // <base-unresolved-name> ::= dn <destructor-name>
907     case DeclarationName::CXXDestructorName:
908       Out << "dn";
909       mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
910       break;
911     // <base-unresolved-name> ::= on <operator-name>
912     case DeclarationName::CXXConversionFunctionName:
913     case DeclarationName::CXXLiteralOperatorName:
914     case DeclarationName::CXXOperatorName:
915       Out << "on";
916       mangleOperatorName(name, knownArity);
917       break;
918     case DeclarationName::CXXConstructorName:
919       llvm_unreachable("Can't mangle a constructor name!");
920     case DeclarationName::CXXUsingDirective:
921       llvm_unreachable("Can't mangle a using directive name!");
922     case DeclarationName::ObjCMultiArgSelector:
923     case DeclarationName::ObjCOneArgSelector:
924     case DeclarationName::ObjCZeroArgSelector:
925       llvm_unreachable("Can't mangle Objective-C selector names here!");
926   }
927 }
928 
929 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
930                                            DeclarationName Name,
931                                            unsigned KnownArity) {
932   unsigned Arity = KnownArity;
933   //  <unqualified-name> ::= <operator-name>
934   //                     ::= <ctor-dtor-name>
935   //                     ::= <source-name>
936   switch (Name.getNameKind()) {
937   case DeclarationName::Identifier: {
938     if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
939       // We must avoid conflicts between internally- and externally-
940       // linked variable and function declaration names in the same TU:
941       //   void test() { extern void foo(); }
942       //   static void foo();
943       // This naming convention is the same as that followed by GCC,
944       // though it shouldn't actually matter.
945       if (ND && ND->getFormalLinkage() == InternalLinkage &&
946           getEffectiveDeclContext(ND)->isFileContext())
947         Out << 'L';
948 
949       mangleSourceName(II);
950       break;
951     }
952 
953     // Otherwise, an anonymous entity.  We must have a declaration.
954     assert(ND && "mangling empty name without declaration");
955 
956     if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
957       if (NS->isAnonymousNamespace()) {
958         // This is how gcc mangles these names.
959         Out << "12_GLOBAL__N_1";
960         break;
961       }
962     }
963 
964     if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
965       // We must have an anonymous union or struct declaration.
966       const RecordDecl *RD =
967         cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
968 
969       // Itanium C++ ABI 5.1.2:
970       //
971       //   For the purposes of mangling, the name of an anonymous union is
972       //   considered to be the name of the first named data member found by a
973       //   pre-order, depth-first, declaration-order walk of the data members of
974       //   the anonymous union. If there is no such data member (i.e., if all of
975       //   the data members in the union are unnamed), then there is no way for
976       //   a program to refer to the anonymous union, and there is therefore no
977       //   need to mangle its name.
978       assert(RD->isAnonymousStructOrUnion()
979              && "Expected anonymous struct or union!");
980       const FieldDecl *FD = RD->findFirstNamedDataMember();
981 
982       // It's actually possible for various reasons for us to get here
983       // with an empty anonymous struct / union.  Fortunately, it
984       // doesn't really matter what name we generate.
985       if (!FD) break;
986       assert(FD->getIdentifier() && "Data member name isn't an identifier!");
987 
988       mangleSourceName(FD->getIdentifier());
989       break;
990     }
991 
992     // Class extensions have no name as a category, and it's possible
993     // for them to be the semantic parent of certain declarations
994     // (primarily, tag decls defined within declarations).  Such
995     // declarations will always have internal linkage, so the name
996     // doesn't really matter, but we shouldn't crash on them.  For
997     // safety, just handle all ObjC containers here.
998     if (isa<ObjCContainerDecl>(ND))
999       break;
1000 
1001     // We must have an anonymous struct.
1002     const TagDecl *TD = cast<TagDecl>(ND);
1003     if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1004       assert(TD->getDeclContext() == D->getDeclContext() &&
1005              "Typedef should not be in another decl context!");
1006       assert(D->getDeclName().getAsIdentifierInfo() &&
1007              "Typedef was not named!");
1008       mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1009       break;
1010     }
1011 
1012     // <unnamed-type-name> ::= <closure-type-name>
1013     //
1014     // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1015     // <lambda-sig> ::= <parameter-type>+   # Parameter types or 'v' for 'void'.
1016     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1017       if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1018         mangleLambda(Record);
1019         break;
1020       }
1021     }
1022 
1023     if (TD->isExternallyVisible()) {
1024       unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1025       Out << "Ut";
1026       if (UnnamedMangle > 1)
1027         Out << UnnamedMangle - 2;
1028       Out << '_';
1029       break;
1030     }
1031 
1032     // Get a unique id for the anonymous struct.
1033     unsigned AnonStructId = Context.getAnonymousStructId(TD);
1034 
1035     // Mangle it as a source name in the form
1036     // [n] $_<id>
1037     // where n is the length of the string.
1038     SmallString<8> Str;
1039     Str += "$_";
1040     Str += llvm::utostr(AnonStructId);
1041 
1042     Out << Str.size();
1043     Out << Str;
1044     break;
1045   }
1046 
1047   case DeclarationName::ObjCZeroArgSelector:
1048   case DeclarationName::ObjCOneArgSelector:
1049   case DeclarationName::ObjCMultiArgSelector:
1050     llvm_unreachable("Can't mangle Objective-C selector names here!");
1051 
1052   case DeclarationName::CXXConstructorName:
1053     if (ND == Structor)
1054       // If the named decl is the C++ constructor we're mangling, use the type
1055       // we were given.
1056       mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1057     else
1058       // Otherwise, use the complete constructor name. This is relevant if a
1059       // class with a constructor is declared within a constructor.
1060       mangleCXXCtorType(Ctor_Complete);
1061     break;
1062 
1063   case DeclarationName::CXXDestructorName:
1064     if (ND == Structor)
1065       // If the named decl is the C++ destructor we're mangling, use the type we
1066       // were given.
1067       mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1068     else
1069       // Otherwise, use the complete destructor name. This is relevant if a
1070       // class with a destructor is declared within a destructor.
1071       mangleCXXDtorType(Dtor_Complete);
1072     break;
1073 
1074   case DeclarationName::CXXOperatorName:
1075     if (ND && Arity == UnknownArity) {
1076       Arity = cast<FunctionDecl>(ND)->getNumParams();
1077 
1078       // If we have a member function, we need to include the 'this' pointer.
1079       if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1080         if (!MD->isStatic())
1081           Arity++;
1082     }
1083   // FALLTHROUGH
1084   case DeclarationName::CXXConversionFunctionName:
1085   case DeclarationName::CXXLiteralOperatorName:
1086     mangleOperatorName(Name, Arity);
1087     break;
1088 
1089   case DeclarationName::CXXUsingDirective:
1090     llvm_unreachable("Can't mangle a using directive name!");
1091   }
1092 }
1093 
1094 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1095   // <source-name> ::= <positive length number> <identifier>
1096   // <number> ::= [n] <non-negative decimal integer>
1097   // <identifier> ::= <unqualified source code identifier>
1098   Out << II->getLength() << II->getName();
1099 }
1100 
1101 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1102                                       const DeclContext *DC,
1103                                       bool NoFunction) {
1104   // <nested-name>
1105   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1106   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1107   //       <template-args> E
1108 
1109   Out << 'N';
1110   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1111     Qualifiers MethodQuals =
1112         Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1113     // We do not consider restrict a distinguishing attribute for overloading
1114     // purposes so we must not mangle it.
1115     MethodQuals.removeRestrict();
1116     mangleQualifiers(MethodQuals);
1117     mangleRefQualifier(Method->getRefQualifier());
1118   }
1119 
1120   // Check if we have a template.
1121   const TemplateArgumentList *TemplateArgs = nullptr;
1122   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1123     mangleTemplatePrefix(TD, NoFunction);
1124     mangleTemplateArgs(*TemplateArgs);
1125   }
1126   else {
1127     manglePrefix(DC, NoFunction);
1128     mangleUnqualifiedName(ND);
1129   }
1130 
1131   Out << 'E';
1132 }
1133 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1134                                       const TemplateArgument *TemplateArgs,
1135                                       unsigned NumTemplateArgs) {
1136   // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1137 
1138   Out << 'N';
1139 
1140   mangleTemplatePrefix(TD);
1141   mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1142 
1143   Out << 'E';
1144 }
1145 
1146 void CXXNameMangler::mangleLocalName(const Decl *D) {
1147   // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1148   //              := Z <function encoding> E s [<discriminator>]
1149   // <local-name> := Z <function encoding> E d [ <parameter number> ]
1150   //                 _ <entity name>
1151   // <discriminator> := _ <non-negative number>
1152   assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1153   const RecordDecl *RD = GetLocalClassDecl(D);
1154   const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1155 
1156   Out << 'Z';
1157 
1158   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1159     mangleObjCMethodName(MD);
1160   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1161     mangleBlockForPrefix(BD);
1162   else
1163     mangleFunctionEncoding(cast<FunctionDecl>(DC));
1164 
1165   Out << 'E';
1166 
1167   if (RD) {
1168     // The parameter number is omitted for the last parameter, 0 for the
1169     // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1170     // <entity name> will of course contain a <closure-type-name>: Its
1171     // numbering will be local to the particular argument in which it appears
1172     // -- other default arguments do not affect its encoding.
1173     const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1174     if (CXXRD->isLambda()) {
1175       if (const ParmVarDecl *Parm
1176               = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1177         if (const FunctionDecl *Func
1178               = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1179           Out << 'd';
1180           unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1181           if (Num > 1)
1182             mangleNumber(Num - 2);
1183           Out << '_';
1184         }
1185       }
1186     }
1187 
1188     // Mangle the name relative to the closest enclosing function.
1189     // equality ok because RD derived from ND above
1190     if (D == RD)  {
1191       mangleUnqualifiedName(RD);
1192     } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1193       manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1194       mangleUnqualifiedBlock(BD);
1195     } else {
1196       const NamedDecl *ND = cast<NamedDecl>(D);
1197       mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
1198     }
1199   } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1200     // Mangle a block in a default parameter; see above explanation for
1201     // lambdas.
1202     if (const ParmVarDecl *Parm
1203             = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1204       if (const FunctionDecl *Func
1205             = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1206         Out << 'd';
1207         unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1208         if (Num > 1)
1209           mangleNumber(Num - 2);
1210         Out << '_';
1211       }
1212     }
1213 
1214     mangleUnqualifiedBlock(BD);
1215   } else {
1216     mangleUnqualifiedName(cast<NamedDecl>(D));
1217   }
1218 
1219   if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1220     unsigned disc;
1221     if (Context.getNextDiscriminator(ND, disc)) {
1222       if (disc < 10)
1223         Out << '_' << disc;
1224       else
1225         Out << "__" << disc << '_';
1226     }
1227   }
1228 }
1229 
1230 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1231   if (GetLocalClassDecl(Block)) {
1232     mangleLocalName(Block);
1233     return;
1234   }
1235   const DeclContext *DC = getEffectiveDeclContext(Block);
1236   if (isLocalContainerContext(DC)) {
1237     mangleLocalName(Block);
1238     return;
1239   }
1240   manglePrefix(getEffectiveDeclContext(Block));
1241   mangleUnqualifiedBlock(Block);
1242 }
1243 
1244 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1245   if (Decl *Context = Block->getBlockManglingContextDecl()) {
1246     if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1247         Context->getDeclContext()->isRecord()) {
1248       if (const IdentifierInfo *Name
1249             = cast<NamedDecl>(Context)->getIdentifier()) {
1250         mangleSourceName(Name);
1251         Out << 'M';
1252       }
1253     }
1254   }
1255 
1256   // If we have a block mangling number, use it.
1257   unsigned Number = Block->getBlockManglingNumber();
1258   // Otherwise, just make up a number. It doesn't matter what it is because
1259   // the symbol in question isn't externally visible.
1260   if (!Number)
1261     Number = Context.getBlockId(Block, false);
1262   Out << "Ub";
1263   if (Number > 0)
1264     Out << Number - 1;
1265   Out << '_';
1266 }
1267 
1268 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1269   // If the context of a closure type is an initializer for a class member
1270   // (static or nonstatic), it is encoded in a qualified name with a final
1271   // <prefix> of the form:
1272   //
1273   //   <data-member-prefix> := <member source-name> M
1274   //
1275   // Technically, the data-member-prefix is part of the <prefix>. However,
1276   // since a closure type will always be mangled with a prefix, it's easier
1277   // to emit that last part of the prefix here.
1278   if (Decl *Context = Lambda->getLambdaContextDecl()) {
1279     if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1280         Context->getDeclContext()->isRecord()) {
1281       if (const IdentifierInfo *Name
1282             = cast<NamedDecl>(Context)->getIdentifier()) {
1283         mangleSourceName(Name);
1284         Out << 'M';
1285       }
1286     }
1287   }
1288 
1289   Out << "Ul";
1290   const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1291                                    getAs<FunctionProtoType>();
1292   mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1293                          Lambda->getLambdaStaticInvoker());
1294   Out << "E";
1295 
1296   // The number is omitted for the first closure type with a given
1297   // <lambda-sig> in a given context; it is n-2 for the nth closure type
1298   // (in lexical order) with that same <lambda-sig> and context.
1299   //
1300   // The AST keeps track of the number for us.
1301   unsigned Number = Lambda->getLambdaManglingNumber();
1302   assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1303   if (Number > 1)
1304     mangleNumber(Number - 2);
1305   Out << '_';
1306 }
1307 
1308 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1309   switch (qualifier->getKind()) {
1310   case NestedNameSpecifier::Global:
1311     // nothing
1312     return;
1313 
1314   case NestedNameSpecifier::Super:
1315     llvm_unreachable("Can't mangle __super specifier");
1316 
1317   case NestedNameSpecifier::Namespace:
1318     mangleName(qualifier->getAsNamespace());
1319     return;
1320 
1321   case NestedNameSpecifier::NamespaceAlias:
1322     mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1323     return;
1324 
1325   case NestedNameSpecifier::TypeSpec:
1326   case NestedNameSpecifier::TypeSpecWithTemplate:
1327     manglePrefix(QualType(qualifier->getAsType(), 0));
1328     return;
1329 
1330   case NestedNameSpecifier::Identifier:
1331     // Member expressions can have these without prefixes, but that
1332     // should end up in mangleUnresolvedPrefix instead.
1333     assert(qualifier->getPrefix());
1334     manglePrefix(qualifier->getPrefix());
1335 
1336     mangleSourceName(qualifier->getAsIdentifier());
1337     return;
1338   }
1339 
1340   llvm_unreachable("unexpected nested name specifier");
1341 }
1342 
1343 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1344   //  <prefix> ::= <prefix> <unqualified-name>
1345   //           ::= <template-prefix> <template-args>
1346   //           ::= <template-param>
1347   //           ::= # empty
1348   //           ::= <substitution>
1349 
1350   DC = IgnoreLinkageSpecDecls(DC);
1351 
1352   if (DC->isTranslationUnit())
1353     return;
1354 
1355   if (NoFunction && isLocalContainerContext(DC))
1356     return;
1357 
1358   assert(!isLocalContainerContext(DC));
1359 
1360   const NamedDecl *ND = cast<NamedDecl>(DC);
1361   if (mangleSubstitution(ND))
1362     return;
1363 
1364   // Check if we have a template.
1365   const TemplateArgumentList *TemplateArgs = nullptr;
1366   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1367     mangleTemplatePrefix(TD);
1368     mangleTemplateArgs(*TemplateArgs);
1369   } else {
1370     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1371     mangleUnqualifiedName(ND);
1372   }
1373 
1374   addSubstitution(ND);
1375 }
1376 
1377 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1378   // <template-prefix> ::= <prefix> <template unqualified-name>
1379   //                   ::= <template-param>
1380   //                   ::= <substitution>
1381   if (TemplateDecl *TD = Template.getAsTemplateDecl())
1382     return mangleTemplatePrefix(TD);
1383 
1384   if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1385     manglePrefix(Qualified->getQualifier());
1386 
1387   if (OverloadedTemplateStorage *Overloaded
1388                                       = Template.getAsOverloadedTemplate()) {
1389     mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1390                           UnknownArity);
1391     return;
1392   }
1393 
1394   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1395   assert(Dependent && "Unknown template name kind?");
1396   if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1397     manglePrefix(Qualifier);
1398   mangleUnscopedTemplateName(Template);
1399 }
1400 
1401 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1402                                           bool NoFunction) {
1403   // <template-prefix> ::= <prefix> <template unqualified-name>
1404   //                   ::= <template-param>
1405   //                   ::= <substitution>
1406   // <template-template-param> ::= <template-param>
1407   //                               <substitution>
1408 
1409   if (mangleSubstitution(ND))
1410     return;
1411 
1412   // <template-template-param> ::= <template-param>
1413   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1414     mangleTemplateParameter(TTP->getIndex());
1415   } else {
1416     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1417     mangleUnqualifiedName(ND->getTemplatedDecl());
1418   }
1419 
1420   addSubstitution(ND);
1421 }
1422 
1423 /// Mangles a template name under the production <type>.  Required for
1424 /// template template arguments.
1425 ///   <type> ::= <class-enum-type>
1426 ///          ::= <template-param>
1427 ///          ::= <substitution>
1428 void CXXNameMangler::mangleType(TemplateName TN) {
1429   if (mangleSubstitution(TN))
1430     return;
1431 
1432   TemplateDecl *TD = nullptr;
1433 
1434   switch (TN.getKind()) {
1435   case TemplateName::QualifiedTemplate:
1436     TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1437     goto HaveDecl;
1438 
1439   case TemplateName::Template:
1440     TD = TN.getAsTemplateDecl();
1441     goto HaveDecl;
1442 
1443   HaveDecl:
1444     if (isa<TemplateTemplateParmDecl>(TD))
1445       mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1446     else
1447       mangleName(TD);
1448     break;
1449 
1450   case TemplateName::OverloadedTemplate:
1451     llvm_unreachable("can't mangle an overloaded template name as a <type>");
1452 
1453   case TemplateName::DependentTemplate: {
1454     const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1455     assert(Dependent->isIdentifier());
1456 
1457     // <class-enum-type> ::= <name>
1458     // <name> ::= <nested-name>
1459     mangleUnresolvedPrefix(Dependent->getQualifier());
1460     mangleSourceName(Dependent->getIdentifier());
1461     break;
1462   }
1463 
1464   case TemplateName::SubstTemplateTemplateParm: {
1465     // Substituted template parameters are mangled as the substituted
1466     // template.  This will check for the substitution twice, which is
1467     // fine, but we have to return early so that we don't try to *add*
1468     // the substitution twice.
1469     SubstTemplateTemplateParmStorage *subst
1470       = TN.getAsSubstTemplateTemplateParm();
1471     mangleType(subst->getReplacement());
1472     return;
1473   }
1474 
1475   case TemplateName::SubstTemplateTemplateParmPack: {
1476     // FIXME: not clear how to mangle this!
1477     // template <template <class> class T...> class A {
1478     //   template <template <class> class U...> void foo(B<T,U> x...);
1479     // };
1480     Out << "_SUBSTPACK_";
1481     break;
1482   }
1483   }
1484 
1485   addSubstitution(TN);
1486 }
1487 
1488 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1489                                                     StringRef Prefix) {
1490   // Only certain other types are valid as prefixes;  enumerate them.
1491   switch (Ty->getTypeClass()) {
1492   case Type::Builtin:
1493   case Type::Complex:
1494   case Type::Adjusted:
1495   case Type::Decayed:
1496   case Type::Pointer:
1497   case Type::BlockPointer:
1498   case Type::LValueReference:
1499   case Type::RValueReference:
1500   case Type::MemberPointer:
1501   case Type::ConstantArray:
1502   case Type::IncompleteArray:
1503   case Type::VariableArray:
1504   case Type::DependentSizedArray:
1505   case Type::DependentSizedExtVector:
1506   case Type::Vector:
1507   case Type::ExtVector:
1508   case Type::FunctionProto:
1509   case Type::FunctionNoProto:
1510   case Type::Paren:
1511   case Type::Attributed:
1512   case Type::Auto:
1513   case Type::PackExpansion:
1514   case Type::ObjCObject:
1515   case Type::ObjCInterface:
1516   case Type::ObjCObjectPointer:
1517   case Type::Atomic:
1518   case Type::Pipe:
1519     llvm_unreachable("type is illegal as a nested name specifier");
1520 
1521   case Type::SubstTemplateTypeParmPack:
1522     // FIXME: not clear how to mangle this!
1523     // template <class T...> class A {
1524     //   template <class U...> void foo(decltype(T::foo(U())) x...);
1525     // };
1526     Out << "_SUBSTPACK_";
1527     break;
1528 
1529   // <unresolved-type> ::= <template-param>
1530   //                   ::= <decltype>
1531   //                   ::= <template-template-param> <template-args>
1532   // (this last is not official yet)
1533   case Type::TypeOfExpr:
1534   case Type::TypeOf:
1535   case Type::Decltype:
1536   case Type::TemplateTypeParm:
1537   case Type::UnaryTransform:
1538   case Type::SubstTemplateTypeParm:
1539   unresolvedType:
1540     // Some callers want a prefix before the mangled type.
1541     Out << Prefix;
1542 
1543     // This seems to do everything we want.  It's not really
1544     // sanctioned for a substituted template parameter, though.
1545     mangleType(Ty);
1546 
1547     // We never want to print 'E' directly after an unresolved-type,
1548     // so we return directly.
1549     return true;
1550 
1551   case Type::Typedef:
1552     mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1553     break;
1554 
1555   case Type::UnresolvedUsing:
1556     mangleSourceName(
1557         cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1558     break;
1559 
1560   case Type::Enum:
1561   case Type::Record:
1562     mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1563     break;
1564 
1565   case Type::TemplateSpecialization: {
1566     const TemplateSpecializationType *TST =
1567         cast<TemplateSpecializationType>(Ty);
1568     TemplateName TN = TST->getTemplateName();
1569     switch (TN.getKind()) {
1570     case TemplateName::Template:
1571     case TemplateName::QualifiedTemplate: {
1572       TemplateDecl *TD = TN.getAsTemplateDecl();
1573 
1574       // If the base is a template template parameter, this is an
1575       // unresolved type.
1576       assert(TD && "no template for template specialization type");
1577       if (isa<TemplateTemplateParmDecl>(TD))
1578         goto unresolvedType;
1579 
1580       mangleSourceName(TD->getIdentifier());
1581       break;
1582     }
1583 
1584     case TemplateName::OverloadedTemplate:
1585     case TemplateName::DependentTemplate:
1586       llvm_unreachable("invalid base for a template specialization type");
1587 
1588     case TemplateName::SubstTemplateTemplateParm: {
1589       SubstTemplateTemplateParmStorage *subst =
1590           TN.getAsSubstTemplateTemplateParm();
1591       mangleExistingSubstitution(subst->getReplacement());
1592       break;
1593     }
1594 
1595     case TemplateName::SubstTemplateTemplateParmPack: {
1596       // FIXME: not clear how to mangle this!
1597       // template <template <class U> class T...> class A {
1598       //   template <class U...> void foo(decltype(T<U>::foo) x...);
1599       // };
1600       Out << "_SUBSTPACK_";
1601       break;
1602     }
1603     }
1604 
1605     mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1606     break;
1607   }
1608 
1609   case Type::InjectedClassName:
1610     mangleSourceName(
1611         cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1612     break;
1613 
1614   case Type::DependentName:
1615     mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1616     break;
1617 
1618   case Type::DependentTemplateSpecialization: {
1619     const DependentTemplateSpecializationType *DTST =
1620         cast<DependentTemplateSpecializationType>(Ty);
1621     mangleSourceName(DTST->getIdentifier());
1622     mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1623     break;
1624   }
1625 
1626   case Type::Elaborated:
1627     return mangleUnresolvedTypeOrSimpleId(
1628         cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1629   }
1630 
1631   return false;
1632 }
1633 
1634 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1635   switch (Name.getNameKind()) {
1636   case DeclarationName::CXXConstructorName:
1637   case DeclarationName::CXXDestructorName:
1638   case DeclarationName::CXXUsingDirective:
1639   case DeclarationName::Identifier:
1640   case DeclarationName::ObjCMultiArgSelector:
1641   case DeclarationName::ObjCOneArgSelector:
1642   case DeclarationName::ObjCZeroArgSelector:
1643     llvm_unreachable("Not an operator name");
1644 
1645   case DeclarationName::CXXConversionFunctionName:
1646     // <operator-name> ::= cv <type>    # (cast)
1647     Out << "cv";
1648     mangleType(Name.getCXXNameType());
1649     break;
1650 
1651   case DeclarationName::CXXLiteralOperatorName:
1652     Out << "li";
1653     mangleSourceName(Name.getCXXLiteralIdentifier());
1654     return;
1655 
1656   case DeclarationName::CXXOperatorName:
1657     mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1658     break;
1659   }
1660 }
1661 
1662 
1663 
1664 void
1665 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1666   switch (OO) {
1667   // <operator-name> ::= nw     # new
1668   case OO_New: Out << "nw"; break;
1669   //              ::= na        # new[]
1670   case OO_Array_New: Out << "na"; break;
1671   //              ::= dl        # delete
1672   case OO_Delete: Out << "dl"; break;
1673   //              ::= da        # delete[]
1674   case OO_Array_Delete: Out << "da"; break;
1675   //              ::= ps        # + (unary)
1676   //              ::= pl        # + (binary or unknown)
1677   case OO_Plus:
1678     Out << (Arity == 1? "ps" : "pl"); break;
1679   //              ::= ng        # - (unary)
1680   //              ::= mi        # - (binary or unknown)
1681   case OO_Minus:
1682     Out << (Arity == 1? "ng" : "mi"); break;
1683   //              ::= ad        # & (unary)
1684   //              ::= an        # & (binary or unknown)
1685   case OO_Amp:
1686     Out << (Arity == 1? "ad" : "an"); break;
1687   //              ::= de        # * (unary)
1688   //              ::= ml        # * (binary or unknown)
1689   case OO_Star:
1690     // Use binary when unknown.
1691     Out << (Arity == 1? "de" : "ml"); break;
1692   //              ::= co        # ~
1693   case OO_Tilde: Out << "co"; break;
1694   //              ::= dv        # /
1695   case OO_Slash: Out << "dv"; break;
1696   //              ::= rm        # %
1697   case OO_Percent: Out << "rm"; break;
1698   //              ::= or        # |
1699   case OO_Pipe: Out << "or"; break;
1700   //              ::= eo        # ^
1701   case OO_Caret: Out << "eo"; break;
1702   //              ::= aS        # =
1703   case OO_Equal: Out << "aS"; break;
1704   //              ::= pL        # +=
1705   case OO_PlusEqual: Out << "pL"; break;
1706   //              ::= mI        # -=
1707   case OO_MinusEqual: Out << "mI"; break;
1708   //              ::= mL        # *=
1709   case OO_StarEqual: Out << "mL"; break;
1710   //              ::= dV        # /=
1711   case OO_SlashEqual: Out << "dV"; break;
1712   //              ::= rM        # %=
1713   case OO_PercentEqual: Out << "rM"; break;
1714   //              ::= aN        # &=
1715   case OO_AmpEqual: Out << "aN"; break;
1716   //              ::= oR        # |=
1717   case OO_PipeEqual: Out << "oR"; break;
1718   //              ::= eO        # ^=
1719   case OO_CaretEqual: Out << "eO"; break;
1720   //              ::= ls        # <<
1721   case OO_LessLess: Out << "ls"; break;
1722   //              ::= rs        # >>
1723   case OO_GreaterGreater: Out << "rs"; break;
1724   //              ::= lS        # <<=
1725   case OO_LessLessEqual: Out << "lS"; break;
1726   //              ::= rS        # >>=
1727   case OO_GreaterGreaterEqual: Out << "rS"; break;
1728   //              ::= eq        # ==
1729   case OO_EqualEqual: Out << "eq"; break;
1730   //              ::= ne        # !=
1731   case OO_ExclaimEqual: Out << "ne"; break;
1732   //              ::= lt        # <
1733   case OO_Less: Out << "lt"; break;
1734   //              ::= gt        # >
1735   case OO_Greater: Out << "gt"; break;
1736   //              ::= le        # <=
1737   case OO_LessEqual: Out << "le"; break;
1738   //              ::= ge        # >=
1739   case OO_GreaterEqual: Out << "ge"; break;
1740   //              ::= nt        # !
1741   case OO_Exclaim: Out << "nt"; break;
1742   //              ::= aa        # &&
1743   case OO_AmpAmp: Out << "aa"; break;
1744   //              ::= oo        # ||
1745   case OO_PipePipe: Out << "oo"; break;
1746   //              ::= pp        # ++
1747   case OO_PlusPlus: Out << "pp"; break;
1748   //              ::= mm        # --
1749   case OO_MinusMinus: Out << "mm"; break;
1750   //              ::= cm        # ,
1751   case OO_Comma: Out << "cm"; break;
1752   //              ::= pm        # ->*
1753   case OO_ArrowStar: Out << "pm"; break;
1754   //              ::= pt        # ->
1755   case OO_Arrow: Out << "pt"; break;
1756   //              ::= cl        # ()
1757   case OO_Call: Out << "cl"; break;
1758   //              ::= ix        # []
1759   case OO_Subscript: Out << "ix"; break;
1760 
1761   //              ::= qu        # ?
1762   // The conditional operator can't be overloaded, but we still handle it when
1763   // mangling expressions.
1764   case OO_Conditional: Out << "qu"; break;
1765   // Proposal on cxx-abi-dev, 2015-10-21.
1766   //              ::= aw        # co_await
1767   case OO_Coawait: Out << "aw"; break;
1768 
1769   case OO_None:
1770   case NUM_OVERLOADED_OPERATORS:
1771     llvm_unreachable("Not an overloaded operator");
1772   }
1773 }
1774 
1775 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1776   // Vendor qualifiers come first.
1777 
1778   // Address space qualifiers start with an ordinary letter.
1779   if (Quals.hasAddressSpace()) {
1780     // Address space extension:
1781     //
1782     //   <type> ::= U <target-addrspace>
1783     //   <type> ::= U <OpenCL-addrspace>
1784     //   <type> ::= U <CUDA-addrspace>
1785 
1786     SmallString<64> ASString;
1787     unsigned AS = Quals.getAddressSpace();
1788 
1789     if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1790       //  <target-addrspace> ::= "AS" <address-space-number>
1791       unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1792       ASString = "AS" + llvm::utostr(TargetAS);
1793     } else {
1794       switch (AS) {
1795       default: llvm_unreachable("Not a language specific address space");
1796       //  <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1797       case LangAS::opencl_global:   ASString = "CLglobal";   break;
1798       case LangAS::opencl_local:    ASString = "CLlocal";    break;
1799       case LangAS::opencl_constant: ASString = "CLconstant"; break;
1800       //  <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1801       case LangAS::cuda_device:     ASString = "CUdevice";   break;
1802       case LangAS::cuda_constant:   ASString = "CUconstant"; break;
1803       case LangAS::cuda_shared:     ASString = "CUshared";   break;
1804       }
1805     }
1806     mangleVendorQualifier(ASString);
1807   }
1808 
1809   // The ARC ownership qualifiers start with underscores.
1810   switch (Quals.getObjCLifetime()) {
1811   // Objective-C ARC Extension:
1812   //
1813   //   <type> ::= U "__strong"
1814   //   <type> ::= U "__weak"
1815   //   <type> ::= U "__autoreleasing"
1816   case Qualifiers::OCL_None:
1817     break;
1818 
1819   case Qualifiers::OCL_Weak:
1820     mangleVendorQualifier("__weak");
1821     break;
1822 
1823   case Qualifiers::OCL_Strong:
1824     mangleVendorQualifier("__strong");
1825     break;
1826 
1827   case Qualifiers::OCL_Autoreleasing:
1828     mangleVendorQualifier("__autoreleasing");
1829     break;
1830 
1831   case Qualifiers::OCL_ExplicitNone:
1832     // The __unsafe_unretained qualifier is *not* mangled, so that
1833     // __unsafe_unretained types in ARC produce the same manglings as the
1834     // equivalent (but, naturally, unqualified) types in non-ARC, providing
1835     // better ABI compatibility.
1836     //
1837     // It's safe to do this because unqualified 'id' won't show up
1838     // in any type signatures that need to be mangled.
1839     break;
1840   }
1841 
1842   // <CV-qualifiers> ::= [r] [V] [K]    # restrict (C99), volatile, const
1843   if (Quals.hasRestrict())
1844     Out << 'r';
1845   if (Quals.hasVolatile())
1846     Out << 'V';
1847   if (Quals.hasConst())
1848     Out << 'K';
1849 }
1850 
1851 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
1852   Out << 'U' << name.size() << name;
1853 }
1854 
1855 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1856   // <ref-qualifier> ::= R                # lvalue reference
1857   //                 ::= O                # rvalue-reference
1858   switch (RefQualifier) {
1859   case RQ_None:
1860     break;
1861 
1862   case RQ_LValue:
1863     Out << 'R';
1864     break;
1865 
1866   case RQ_RValue:
1867     Out << 'O';
1868     break;
1869   }
1870 }
1871 
1872 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1873   Context.mangleObjCMethodName(MD, Out);
1874 }
1875 
1876 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1877   if (Quals)
1878     return true;
1879   if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1880     return true;
1881   if (Ty->isOpenCLSpecificType())
1882     return true;
1883   if (Ty->isBuiltinType())
1884     return false;
1885 
1886   return true;
1887 }
1888 
1889 void CXXNameMangler::mangleType(QualType T) {
1890   // If our type is instantiation-dependent but not dependent, we mangle
1891   // it as it was written in the source, removing any top-level sugar.
1892   // Otherwise, use the canonical type.
1893   //
1894   // FIXME: This is an approximation of the instantiation-dependent name
1895   // mangling rules, since we should really be using the type as written and
1896   // augmented via semantic analysis (i.e., with implicit conversions and
1897   // default template arguments) for any instantiation-dependent type.
1898   // Unfortunately, that requires several changes to our AST:
1899   //   - Instantiation-dependent TemplateSpecializationTypes will need to be
1900   //     uniqued, so that we can handle substitutions properly
1901   //   - Default template arguments will need to be represented in the
1902   //     TemplateSpecializationType, since they need to be mangled even though
1903   //     they aren't written.
1904   //   - Conversions on non-type template arguments need to be expressed, since
1905   //     they can affect the mangling of sizeof/alignof.
1906   if (!T->isInstantiationDependentType() || T->isDependentType())
1907     T = T.getCanonicalType();
1908   else {
1909     // Desugar any types that are purely sugar.
1910     do {
1911       // Don't desugar through template specialization types that aren't
1912       // type aliases. We need to mangle the template arguments as written.
1913       if (const TemplateSpecializationType *TST
1914                                       = dyn_cast<TemplateSpecializationType>(T))
1915         if (!TST->isTypeAlias())
1916           break;
1917 
1918       QualType Desugared
1919         = T.getSingleStepDesugaredType(Context.getASTContext());
1920       if (Desugared == T)
1921         break;
1922 
1923       T = Desugared;
1924     } while (true);
1925   }
1926   SplitQualType split = T.split();
1927   Qualifiers quals = split.Quals;
1928   const Type *ty = split.Ty;
1929 
1930   bool isSubstitutable = isTypeSubstitutable(quals, ty);
1931   if (isSubstitutable && mangleSubstitution(T))
1932     return;
1933 
1934   // If we're mangling a qualified array type, push the qualifiers to
1935   // the element type.
1936   if (quals && isa<ArrayType>(T)) {
1937     ty = Context.getASTContext().getAsArrayType(T);
1938     quals = Qualifiers();
1939 
1940     // Note that we don't update T: we want to add the
1941     // substitution at the original type.
1942   }
1943 
1944   if (quals) {
1945     mangleQualifiers(quals);
1946     // Recurse:  even if the qualified type isn't yet substitutable,
1947     // the unqualified type might be.
1948     mangleType(QualType(ty, 0));
1949   } else {
1950     switch (ty->getTypeClass()) {
1951 #define ABSTRACT_TYPE(CLASS, PARENT)
1952 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1953     case Type::CLASS: \
1954       llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1955       return;
1956 #define TYPE(CLASS, PARENT) \
1957     case Type::CLASS: \
1958       mangleType(static_cast<const CLASS##Type*>(ty)); \
1959       break;
1960 #include "clang/AST/TypeNodes.def"
1961     }
1962   }
1963 
1964   // Add the substitution.
1965   if (isSubstitutable)
1966     addSubstitution(T);
1967 }
1968 
1969 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1970   if (!mangleStandardSubstitution(ND))
1971     mangleName(ND);
1972 }
1973 
1974 void CXXNameMangler::mangleType(const BuiltinType *T) {
1975   //  <type>         ::= <builtin-type>
1976   //  <builtin-type> ::= v  # void
1977   //                 ::= w  # wchar_t
1978   //                 ::= b  # bool
1979   //                 ::= c  # char
1980   //                 ::= a  # signed char
1981   //                 ::= h  # unsigned char
1982   //                 ::= s  # short
1983   //                 ::= t  # unsigned short
1984   //                 ::= i  # int
1985   //                 ::= j  # unsigned int
1986   //                 ::= l  # long
1987   //                 ::= m  # unsigned long
1988   //                 ::= x  # long long, __int64
1989   //                 ::= y  # unsigned long long, __int64
1990   //                 ::= n  # __int128
1991   //                 ::= o  # unsigned __int128
1992   //                 ::= f  # float
1993   //                 ::= d  # double
1994   //                 ::= e  # long double, __float80
1995   //                 ::= g  # __float128
1996   // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)
1997   // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)
1998   // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)
1999   //                 ::= Dh # IEEE 754r half-precision floating point (16 bits)
2000   //                 ::= Di # char32_t
2001   //                 ::= Ds # char16_t
2002   //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2003   //                 ::= u <source-name>    # vendor extended type
2004   std::string type_name;
2005   switch (T->getKind()) {
2006   case BuiltinType::Void:
2007     Out << 'v';
2008     break;
2009   case BuiltinType::Bool:
2010     Out << 'b';
2011     break;
2012   case BuiltinType::Char_U:
2013   case BuiltinType::Char_S:
2014     Out << 'c';
2015     break;
2016   case BuiltinType::UChar:
2017     Out << 'h';
2018     break;
2019   case BuiltinType::UShort:
2020     Out << 't';
2021     break;
2022   case BuiltinType::UInt:
2023     Out << 'j';
2024     break;
2025   case BuiltinType::ULong:
2026     Out << 'm';
2027     break;
2028   case BuiltinType::ULongLong:
2029     Out << 'y';
2030     break;
2031   case BuiltinType::UInt128:
2032     Out << 'o';
2033     break;
2034   case BuiltinType::SChar:
2035     Out << 'a';
2036     break;
2037   case BuiltinType::WChar_S:
2038   case BuiltinType::WChar_U:
2039     Out << 'w';
2040     break;
2041   case BuiltinType::Char16:
2042     Out << "Ds";
2043     break;
2044   case BuiltinType::Char32:
2045     Out << "Di";
2046     break;
2047   case BuiltinType::Short:
2048     Out << 's';
2049     break;
2050   case BuiltinType::Int:
2051     Out << 'i';
2052     break;
2053   case BuiltinType::Long:
2054     Out << 'l';
2055     break;
2056   case BuiltinType::LongLong:
2057     Out << 'x';
2058     break;
2059   case BuiltinType::Int128:
2060     Out << 'n';
2061     break;
2062   case BuiltinType::Half:
2063     Out << "Dh";
2064     break;
2065   case BuiltinType::Float:
2066     Out << 'f';
2067     break;
2068   case BuiltinType::Double:
2069     Out << 'd';
2070     break;
2071   case BuiltinType::LongDouble:
2072     Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2073                 ? 'g'
2074                 : 'e');
2075     break;
2076   case BuiltinType::Float128:
2077     if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2078       Out << "U10__float128"; // Match the GCC mangling
2079     else
2080       Out << 'g';
2081     break;
2082   case BuiltinType::NullPtr:
2083     Out << "Dn";
2084     break;
2085 
2086 #define BUILTIN_TYPE(Id, SingletonId)
2087 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2088   case BuiltinType::Id:
2089 #include "clang/AST/BuiltinTypes.def"
2090   case BuiltinType::Dependent:
2091     llvm_unreachable("mangling a placeholder type");
2092   case BuiltinType::ObjCId:
2093     Out << "11objc_object";
2094     break;
2095   case BuiltinType::ObjCClass:
2096     Out << "10objc_class";
2097     break;
2098   case BuiltinType::ObjCSel:
2099     Out << "13objc_selector";
2100     break;
2101 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2102   case BuiltinType::Id: \
2103     type_name = "ocl_" #ImgType "_" #Suffix; \
2104     Out << type_name.size() << type_name; \
2105     break;
2106 #include "clang/Basic/OpenCLImageTypes.def"
2107   case BuiltinType::OCLSampler:
2108     Out << "11ocl_sampler";
2109     break;
2110   case BuiltinType::OCLEvent:
2111     Out << "9ocl_event";
2112     break;
2113   case BuiltinType::OCLClkEvent:
2114     Out << "12ocl_clkevent";
2115     break;
2116   case BuiltinType::OCLQueue:
2117     Out << "9ocl_queue";
2118     break;
2119   case BuiltinType::OCLNDRange:
2120     Out << "11ocl_ndrange";
2121     break;
2122   case BuiltinType::OCLReserveID:
2123     Out << "13ocl_reserveid";
2124     break;
2125   }
2126 }
2127 
2128 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2129   switch (CC) {
2130   case CC_C:
2131     return "";
2132 
2133   case CC_X86StdCall:
2134   case CC_X86FastCall:
2135   case CC_X86ThisCall:
2136   case CC_X86VectorCall:
2137   case CC_X86Pascal:
2138   case CC_X86_64Win64:
2139   case CC_X86_64SysV:
2140   case CC_AAPCS:
2141   case CC_AAPCS_VFP:
2142   case CC_IntelOclBicc:
2143   case CC_SpirFunction:
2144   case CC_SpirKernel:
2145   case CC_PreserveMost:
2146   case CC_PreserveAll:
2147     // FIXME: we should be mangling all of the above.
2148     return "";
2149 
2150   case CC_Swift:
2151     return "swiftcall";
2152   }
2153   llvm_unreachable("bad calling convention");
2154 }
2155 
2156 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2157   // Fast path.
2158   if (T->getExtInfo() == FunctionType::ExtInfo())
2159     return;
2160 
2161   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2162   // This will get more complicated in the future if we mangle other
2163   // things here; but for now, since we mangle ns_returns_retained as
2164   // a qualifier on the result type, we can get away with this:
2165   StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2166   if (!CCQualifier.empty())
2167     mangleVendorQualifier(CCQualifier);
2168 
2169   // FIXME: regparm
2170   // FIXME: noreturn
2171 }
2172 
2173 void
2174 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2175   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2176 
2177   // Note that these are *not* substitution candidates.  Demanglers might
2178   // have trouble with this if the parameter type is fully substituted.
2179 
2180   switch (PI.getABI()) {
2181   case ParameterABI::Ordinary:
2182     break;
2183 
2184   // All of these start with "swift", so they come before "ns_consumed".
2185   case ParameterABI::SwiftContext:
2186   case ParameterABI::SwiftErrorResult:
2187   case ParameterABI::SwiftIndirectResult:
2188     mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2189     break;
2190   }
2191 
2192   if (PI.isConsumed())
2193     mangleVendorQualifier("ns_consumed");
2194 }
2195 
2196 // <type>          ::= <function-type>
2197 // <function-type> ::= [<CV-qualifiers>] F [Y]
2198 //                      <bare-function-type> [<ref-qualifier>] E
2199 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2200   mangleExtFunctionInfo(T);
2201 
2202   // Mangle CV-qualifiers, if present.  These are 'this' qualifiers,
2203   // e.g. "const" in "int (A::*)() const".
2204   mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2205 
2206   Out << 'F';
2207 
2208   // FIXME: We don't have enough information in the AST to produce the 'Y'
2209   // encoding for extern "C" function types.
2210   mangleBareFunctionType(T, /*MangleReturnType=*/true);
2211 
2212   // Mangle the ref-qualifier, if present.
2213   mangleRefQualifier(T->getRefQualifier());
2214 
2215   Out << 'E';
2216 }
2217 
2218 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2219   // Function types without prototypes can arise when mangling a function type
2220   // within an overloadable function in C. We mangle these as the absence of any
2221   // parameter types (not even an empty parameter list).
2222   Out << 'F';
2223 
2224   FunctionTypeDepthState saved = FunctionTypeDepth.push();
2225 
2226   FunctionTypeDepth.enterResultType();
2227   mangleType(T->getReturnType());
2228   FunctionTypeDepth.leaveResultType();
2229 
2230   FunctionTypeDepth.pop(saved);
2231   Out << 'E';
2232 }
2233 
2234 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2235                                             bool MangleReturnType,
2236                                             const FunctionDecl *FD) {
2237   // Record that we're in a function type.  See mangleFunctionParam
2238   // for details on what we're trying to achieve here.
2239   FunctionTypeDepthState saved = FunctionTypeDepth.push();
2240 
2241   // <bare-function-type> ::= <signature type>+
2242   if (MangleReturnType) {
2243     FunctionTypeDepth.enterResultType();
2244 
2245     // Mangle ns_returns_retained as an order-sensitive qualifier here.
2246     if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2247       mangleVendorQualifier("ns_returns_retained");
2248 
2249     // Mangle the return type without any direct ARC ownership qualifiers.
2250     QualType ReturnTy = Proto->getReturnType();
2251     if (ReturnTy.getObjCLifetime()) {
2252       auto SplitReturnTy = ReturnTy.split();
2253       SplitReturnTy.Quals.removeObjCLifetime();
2254       ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2255     }
2256     mangleType(ReturnTy);
2257 
2258     FunctionTypeDepth.leaveResultType();
2259   }
2260 
2261   if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2262     //   <builtin-type> ::= v   # void
2263     Out << 'v';
2264 
2265     FunctionTypeDepth.pop(saved);
2266     return;
2267   }
2268 
2269   assert(!FD || FD->getNumParams() == Proto->getNumParams());
2270   for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2271     // Mangle extended parameter info as order-sensitive qualifiers here.
2272     if (Proto->hasExtParameterInfos() && FD == nullptr) {
2273       mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2274     }
2275 
2276     // Mangle the type.
2277     QualType ParamTy = Proto->getParamType(I);
2278     mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2279 
2280     if (FD) {
2281       if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2282         // Attr can only take 1 character, so we can hardcode the length below.
2283         assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2284         Out << "U17pass_object_size" << Attr->getType();
2285       }
2286     }
2287   }
2288 
2289   FunctionTypeDepth.pop(saved);
2290 
2291   // <builtin-type>      ::= z  # ellipsis
2292   if (Proto->isVariadic())
2293     Out << 'z';
2294 }
2295 
2296 // <type>            ::= <class-enum-type>
2297 // <class-enum-type> ::= <name>
2298 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2299   mangleName(T->getDecl());
2300 }
2301 
2302 // <type>            ::= <class-enum-type>
2303 // <class-enum-type> ::= <name>
2304 void CXXNameMangler::mangleType(const EnumType *T) {
2305   mangleType(static_cast<const TagType*>(T));
2306 }
2307 void CXXNameMangler::mangleType(const RecordType *T) {
2308   mangleType(static_cast<const TagType*>(T));
2309 }
2310 void CXXNameMangler::mangleType(const TagType *T) {
2311   mangleName(T->getDecl());
2312 }
2313 
2314 // <type>       ::= <array-type>
2315 // <array-type> ::= A <positive dimension number> _ <element type>
2316 //              ::= A [<dimension expression>] _ <element type>
2317 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2318   Out << 'A' << T->getSize() << '_';
2319   mangleType(T->getElementType());
2320 }
2321 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2322   Out << 'A';
2323   // decayed vla types (size 0) will just be skipped.
2324   if (T->getSizeExpr())
2325     mangleExpression(T->getSizeExpr());
2326   Out << '_';
2327   mangleType(T->getElementType());
2328 }
2329 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2330   Out << 'A';
2331   mangleExpression(T->getSizeExpr());
2332   Out << '_';
2333   mangleType(T->getElementType());
2334 }
2335 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2336   Out << "A_";
2337   mangleType(T->getElementType());
2338 }
2339 
2340 // <type>                   ::= <pointer-to-member-type>
2341 // <pointer-to-member-type> ::= M <class type> <member type>
2342 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2343   Out << 'M';
2344   mangleType(QualType(T->getClass(), 0));
2345   QualType PointeeType = T->getPointeeType();
2346   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2347     mangleType(FPT);
2348 
2349     // Itanium C++ ABI 5.1.8:
2350     //
2351     //   The type of a non-static member function is considered to be different,
2352     //   for the purposes of substitution, from the type of a namespace-scope or
2353     //   static member function whose type appears similar. The types of two
2354     //   non-static member functions are considered to be different, for the
2355     //   purposes of substitution, if the functions are members of different
2356     //   classes. In other words, for the purposes of substitution, the class of
2357     //   which the function is a member is considered part of the type of
2358     //   function.
2359 
2360     // Given that we already substitute member function pointers as a
2361     // whole, the net effect of this rule is just to unconditionally
2362     // suppress substitution on the function type in a member pointer.
2363     // We increment the SeqID here to emulate adding an entry to the
2364     // substitution table.
2365     ++SeqID;
2366   } else
2367     mangleType(PointeeType);
2368 }
2369 
2370 // <type>           ::= <template-param>
2371 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2372   mangleTemplateParameter(T->getIndex());
2373 }
2374 
2375 // <type>           ::= <template-param>
2376 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2377   // FIXME: not clear how to mangle this!
2378   // template <class T...> class A {
2379   //   template <class U...> void foo(T(*)(U) x...);
2380   // };
2381   Out << "_SUBSTPACK_";
2382 }
2383 
2384 // <type> ::= P <type>   # pointer-to
2385 void CXXNameMangler::mangleType(const PointerType *T) {
2386   Out << 'P';
2387   mangleType(T->getPointeeType());
2388 }
2389 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2390   Out << 'P';
2391   mangleType(T->getPointeeType());
2392 }
2393 
2394 // <type> ::= R <type>   # reference-to
2395 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2396   Out << 'R';
2397   mangleType(T->getPointeeType());
2398 }
2399 
2400 // <type> ::= O <type>   # rvalue reference-to (C++0x)
2401 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2402   Out << 'O';
2403   mangleType(T->getPointeeType());
2404 }
2405 
2406 // <type> ::= C <type>   # complex pair (C 2000)
2407 void CXXNameMangler::mangleType(const ComplexType *T) {
2408   Out << 'C';
2409   mangleType(T->getElementType());
2410 }
2411 
2412 // ARM's ABI for Neon vector types specifies that they should be mangled as
2413 // if they are structs (to match ARM's initial implementation).  The
2414 // vector type must be one of the special types predefined by ARM.
2415 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2416   QualType EltType = T->getElementType();
2417   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2418   const char *EltName = nullptr;
2419   if (T->getVectorKind() == VectorType::NeonPolyVector) {
2420     switch (cast<BuiltinType>(EltType)->getKind()) {
2421     case BuiltinType::SChar:
2422     case BuiltinType::UChar:
2423       EltName = "poly8_t";
2424       break;
2425     case BuiltinType::Short:
2426     case BuiltinType::UShort:
2427       EltName = "poly16_t";
2428       break;
2429     case BuiltinType::ULongLong:
2430       EltName = "poly64_t";
2431       break;
2432     default: llvm_unreachable("unexpected Neon polynomial vector element type");
2433     }
2434   } else {
2435     switch (cast<BuiltinType>(EltType)->getKind()) {
2436     case BuiltinType::SChar:     EltName = "int8_t"; break;
2437     case BuiltinType::UChar:     EltName = "uint8_t"; break;
2438     case BuiltinType::Short:     EltName = "int16_t"; break;
2439     case BuiltinType::UShort:    EltName = "uint16_t"; break;
2440     case BuiltinType::Int:       EltName = "int32_t"; break;
2441     case BuiltinType::UInt:      EltName = "uint32_t"; break;
2442     case BuiltinType::LongLong:  EltName = "int64_t"; break;
2443     case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2444     case BuiltinType::Double:    EltName = "float64_t"; break;
2445     case BuiltinType::Float:     EltName = "float32_t"; break;
2446     case BuiltinType::Half:      EltName = "float16_t";break;
2447     default:
2448       llvm_unreachable("unexpected Neon vector element type");
2449     }
2450   }
2451   const char *BaseName = nullptr;
2452   unsigned BitSize = (T->getNumElements() *
2453                       getASTContext().getTypeSize(EltType));
2454   if (BitSize == 64)
2455     BaseName = "__simd64_";
2456   else {
2457     assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2458     BaseName = "__simd128_";
2459   }
2460   Out << strlen(BaseName) + strlen(EltName);
2461   Out << BaseName << EltName;
2462 }
2463 
2464 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2465   switch (EltType->getKind()) {
2466   case BuiltinType::SChar:
2467     return "Int8";
2468   case BuiltinType::Short:
2469     return "Int16";
2470   case BuiltinType::Int:
2471     return "Int32";
2472   case BuiltinType::Long:
2473   case BuiltinType::LongLong:
2474     return "Int64";
2475   case BuiltinType::UChar:
2476     return "Uint8";
2477   case BuiltinType::UShort:
2478     return "Uint16";
2479   case BuiltinType::UInt:
2480     return "Uint32";
2481   case BuiltinType::ULong:
2482   case BuiltinType::ULongLong:
2483     return "Uint64";
2484   case BuiltinType::Half:
2485     return "Float16";
2486   case BuiltinType::Float:
2487     return "Float32";
2488   case BuiltinType::Double:
2489     return "Float64";
2490   default:
2491     llvm_unreachable("Unexpected vector element base type");
2492   }
2493 }
2494 
2495 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2496 // the equivalent internal name. The vector type must be one of the special
2497 // types predefined by ARM.
2498 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2499   QualType EltType = T->getElementType();
2500   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2501   unsigned BitSize =
2502       (T->getNumElements() * getASTContext().getTypeSize(EltType));
2503   (void)BitSize; // Silence warning.
2504 
2505   assert((BitSize == 64 || BitSize == 128) &&
2506          "Neon vector type not 64 or 128 bits");
2507 
2508   StringRef EltName;
2509   if (T->getVectorKind() == VectorType::NeonPolyVector) {
2510     switch (cast<BuiltinType>(EltType)->getKind()) {
2511     case BuiltinType::UChar:
2512       EltName = "Poly8";
2513       break;
2514     case BuiltinType::UShort:
2515       EltName = "Poly16";
2516       break;
2517     case BuiltinType::ULong:
2518     case BuiltinType::ULongLong:
2519       EltName = "Poly64";
2520       break;
2521     default:
2522       llvm_unreachable("unexpected Neon polynomial vector element type");
2523     }
2524   } else
2525     EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2526 
2527   std::string TypeName =
2528       ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
2529   Out << TypeName.length() << TypeName;
2530 }
2531 
2532 // GNU extension: vector types
2533 // <type>                  ::= <vector-type>
2534 // <vector-type>           ::= Dv <positive dimension number> _
2535 //                                    <extended element type>
2536 //                         ::= Dv [<dimension expression>] _ <element type>
2537 // <extended element type> ::= <element type>
2538 //                         ::= p # AltiVec vector pixel
2539 //                         ::= b # Altivec vector bool
2540 void CXXNameMangler::mangleType(const VectorType *T) {
2541   if ((T->getVectorKind() == VectorType::NeonVector ||
2542        T->getVectorKind() == VectorType::NeonPolyVector)) {
2543     llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
2544     llvm::Triple::ArchType Arch =
2545         getASTContext().getTargetInfo().getTriple().getArch();
2546     if ((Arch == llvm::Triple::aarch64 ||
2547          Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
2548       mangleAArch64NeonVectorType(T);
2549     else
2550       mangleNeonVectorType(T);
2551     return;
2552   }
2553   Out << "Dv" << T->getNumElements() << '_';
2554   if (T->getVectorKind() == VectorType::AltiVecPixel)
2555     Out << 'p';
2556   else if (T->getVectorKind() == VectorType::AltiVecBool)
2557     Out << 'b';
2558   else
2559     mangleType(T->getElementType());
2560 }
2561 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2562   mangleType(static_cast<const VectorType*>(T));
2563 }
2564 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2565   Out << "Dv";
2566   mangleExpression(T->getSizeExpr());
2567   Out << '_';
2568   mangleType(T->getElementType());
2569 }
2570 
2571 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2572   // <type>  ::= Dp <type>          # pack expansion (C++0x)
2573   Out << "Dp";
2574   mangleType(T->getPattern());
2575 }
2576 
2577 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2578   mangleSourceName(T->getDecl()->getIdentifier());
2579 }
2580 
2581 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2582   // Treat __kindof as a vendor extended type qualifier.
2583   if (T->isKindOfType())
2584     Out << "U8__kindof";
2585 
2586   if (!T->qual_empty()) {
2587     // Mangle protocol qualifiers.
2588     SmallString<64> QualStr;
2589     llvm::raw_svector_ostream QualOS(QualStr);
2590     QualOS << "objcproto";
2591     for (const auto *I : T->quals()) {
2592       StringRef name = I->getName();
2593       QualOS << name.size() << name;
2594     }
2595     Out << 'U' << QualStr.size() << QualStr;
2596   }
2597 
2598   mangleType(T->getBaseType());
2599 
2600   if (T->isSpecialized()) {
2601     // Mangle type arguments as I <type>+ E
2602     Out << 'I';
2603     for (auto typeArg : T->getTypeArgs())
2604       mangleType(typeArg);
2605     Out << 'E';
2606   }
2607 }
2608 
2609 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2610   Out << "U13block_pointer";
2611   mangleType(T->getPointeeType());
2612 }
2613 
2614 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2615   // Mangle injected class name types as if the user had written the
2616   // specialization out fully.  It may not actually be possible to see
2617   // this mangling, though.
2618   mangleType(T->getInjectedSpecializationType());
2619 }
2620 
2621 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2622   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2623     mangleName(TD, T->getArgs(), T->getNumArgs());
2624   } else {
2625     if (mangleSubstitution(QualType(T, 0)))
2626       return;
2627 
2628     mangleTemplatePrefix(T->getTemplateName());
2629 
2630     // FIXME: GCC does not appear to mangle the template arguments when
2631     // the template in question is a dependent template name. Should we
2632     // emulate that badness?
2633     mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2634     addSubstitution(QualType(T, 0));
2635   }
2636 }
2637 
2638 void CXXNameMangler::mangleType(const DependentNameType *T) {
2639   // Proposal by cxx-abi-dev, 2014-03-26
2640   // <class-enum-type> ::= <name>    # non-dependent or dependent type name or
2641   //                                 # dependent elaborated type specifier using
2642   //                                 # 'typename'
2643   //                   ::= Ts <name> # dependent elaborated type specifier using
2644   //                                 # 'struct' or 'class'
2645   //                   ::= Tu <name> # dependent elaborated type specifier using
2646   //                                 # 'union'
2647   //                   ::= Te <name> # dependent elaborated type specifier using
2648   //                                 # 'enum'
2649   switch (T->getKeyword()) {
2650     case ETK_Typename:
2651       break;
2652     case ETK_Struct:
2653     case ETK_Class:
2654     case ETK_Interface:
2655       Out << "Ts";
2656       break;
2657     case ETK_Union:
2658       Out << "Tu";
2659       break;
2660     case ETK_Enum:
2661       Out << "Te";
2662       break;
2663     default:
2664       llvm_unreachable("unexpected keyword for dependent type name");
2665   }
2666   // Typename types are always nested
2667   Out << 'N';
2668   manglePrefix(T->getQualifier());
2669   mangleSourceName(T->getIdentifier());
2670   Out << 'E';
2671 }
2672 
2673 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2674   // Dependently-scoped template types are nested if they have a prefix.
2675   Out << 'N';
2676 
2677   // TODO: avoid making this TemplateName.
2678   TemplateName Prefix =
2679     getASTContext().getDependentTemplateName(T->getQualifier(),
2680                                              T->getIdentifier());
2681   mangleTemplatePrefix(Prefix);
2682 
2683   // FIXME: GCC does not appear to mangle the template arguments when
2684   // the template in question is a dependent template name. Should we
2685   // emulate that badness?
2686   mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2687   Out << 'E';
2688 }
2689 
2690 void CXXNameMangler::mangleType(const TypeOfType *T) {
2691   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2692   // "extension with parameters" mangling.
2693   Out << "u6typeof";
2694 }
2695 
2696 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2697   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2698   // "extension with parameters" mangling.
2699   Out << "u6typeof";
2700 }
2701 
2702 void CXXNameMangler::mangleType(const DecltypeType *T) {
2703   Expr *E = T->getUnderlyingExpr();
2704 
2705   // type ::= Dt <expression> E  # decltype of an id-expression
2706   //                             #   or class member access
2707   //      ::= DT <expression> E  # decltype of an expression
2708 
2709   // This purports to be an exhaustive list of id-expressions and
2710   // class member accesses.  Note that we do not ignore parentheses;
2711   // parentheses change the semantics of decltype for these
2712   // expressions (and cause the mangler to use the other form).
2713   if (isa<DeclRefExpr>(E) ||
2714       isa<MemberExpr>(E) ||
2715       isa<UnresolvedLookupExpr>(E) ||
2716       isa<DependentScopeDeclRefExpr>(E) ||
2717       isa<CXXDependentScopeMemberExpr>(E) ||
2718       isa<UnresolvedMemberExpr>(E))
2719     Out << "Dt";
2720   else
2721     Out << "DT";
2722   mangleExpression(E);
2723   Out << 'E';
2724 }
2725 
2726 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2727   // If this is dependent, we need to record that. If not, we simply
2728   // mangle it as the underlying type since they are equivalent.
2729   if (T->isDependentType()) {
2730     Out << 'U';
2731 
2732     switch (T->getUTTKind()) {
2733       case UnaryTransformType::EnumUnderlyingType:
2734         Out << "3eut";
2735         break;
2736     }
2737   }
2738 
2739   mangleType(T->getUnderlyingType());
2740 }
2741 
2742 void CXXNameMangler::mangleType(const AutoType *T) {
2743   QualType D = T->getDeducedType();
2744   // <builtin-type> ::= Da  # dependent auto
2745   if (D.isNull()) {
2746     assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2747            "shouldn't need to mangle __auto_type!");
2748     Out << (T->isDecltypeAuto() ? "Dc" : "Da");
2749   } else
2750     mangleType(D);
2751 }
2752 
2753 void CXXNameMangler::mangleType(const AtomicType *T) {
2754   // <type> ::= U <source-name> <type>  # vendor extended type qualifier
2755   // (Until there's a standardized mangling...)
2756   Out << "U7_Atomic";
2757   mangleType(T->getValueType());
2758 }
2759 
2760 void CXXNameMangler::mangleType(const PipeType *T) {
2761   // Pipe type mangling rules are described in SPIR 2.0 specification
2762   // A.1 Data types and A.3 Summary of changes
2763   // <type> ::= 8ocl_pipe
2764   Out << "8ocl_pipe";
2765 }
2766 
2767 void CXXNameMangler::mangleIntegerLiteral(QualType T,
2768                                           const llvm::APSInt &Value) {
2769   //  <expr-primary> ::= L <type> <value number> E # integer literal
2770   Out << 'L';
2771 
2772   mangleType(T);
2773   if (T->isBooleanType()) {
2774     // Boolean values are encoded as 0/1.
2775     Out << (Value.getBoolValue() ? '1' : '0');
2776   } else {
2777     mangleNumber(Value);
2778   }
2779   Out << 'E';
2780 
2781 }
2782 
2783 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2784   // Ignore member expressions involving anonymous unions.
2785   while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2786     if (!RT->getDecl()->isAnonymousStructOrUnion())
2787       break;
2788     const auto *ME = dyn_cast<MemberExpr>(Base);
2789     if (!ME)
2790       break;
2791     Base = ME->getBase();
2792     IsArrow = ME->isArrow();
2793   }
2794 
2795   if (Base->isImplicitCXXThis()) {
2796     // Note: GCC mangles member expressions to the implicit 'this' as
2797     // *this., whereas we represent them as this->. The Itanium C++ ABI
2798     // does not specify anything here, so we follow GCC.
2799     Out << "dtdefpT";
2800   } else {
2801     Out << (IsArrow ? "pt" : "dt");
2802     mangleExpression(Base);
2803   }
2804 }
2805 
2806 /// Mangles a member expression.
2807 void CXXNameMangler::mangleMemberExpr(const Expr *base,
2808                                       bool isArrow,
2809                                       NestedNameSpecifier *qualifier,
2810                                       NamedDecl *firstQualifierLookup,
2811                                       DeclarationName member,
2812                                       unsigned arity) {
2813   // <expression> ::= dt <expression> <unresolved-name>
2814   //              ::= pt <expression> <unresolved-name>
2815   if (base)
2816     mangleMemberExprBase(base, isArrow);
2817   mangleUnresolvedName(qualifier, member, arity);
2818 }
2819 
2820 /// Look at the callee of the given call expression and determine if
2821 /// it's a parenthesized id-expression which would have triggered ADL
2822 /// otherwise.
2823 static bool isParenthesizedADLCallee(const CallExpr *call) {
2824   const Expr *callee = call->getCallee();
2825   const Expr *fn = callee->IgnoreParens();
2826 
2827   // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,
2828   // too, but for those to appear in the callee, it would have to be
2829   // parenthesized.
2830   if (callee == fn) return false;
2831 
2832   // Must be an unresolved lookup.
2833   const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2834   if (!lookup) return false;
2835 
2836   assert(!lookup->requiresADL());
2837 
2838   // Must be an unqualified lookup.
2839   if (lookup->getQualifier()) return false;
2840 
2841   // Must not have found a class member.  Note that if one is a class
2842   // member, they're all class members.
2843   if (lookup->getNumDecls() > 0 &&
2844       (*lookup->decls_begin())->isCXXClassMember())
2845     return false;
2846 
2847   // Otherwise, ADL would have been triggered.
2848   return true;
2849 }
2850 
2851 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2852   const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2853   Out << CastEncoding;
2854   mangleType(ECE->getType());
2855   mangleExpression(ECE->getSubExpr());
2856 }
2857 
2858 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2859   if (auto *Syntactic = InitList->getSyntacticForm())
2860     InitList = Syntactic;
2861   for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2862     mangleExpression(InitList->getInit(i));
2863 }
2864 
2865 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2866   // <expression> ::= <unary operator-name> <expression>
2867   //              ::= <binary operator-name> <expression> <expression>
2868   //              ::= <trinary operator-name> <expression> <expression> <expression>
2869   //              ::= cv <type> expression           # conversion with one argument
2870   //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2871   //              ::= dc <type> <expression>         # dynamic_cast<type> (expression)
2872   //              ::= sc <type> <expression>         # static_cast<type> (expression)
2873   //              ::= cc <type> <expression>         # const_cast<type> (expression)
2874   //              ::= rc <type> <expression>         # reinterpret_cast<type> (expression)
2875   //              ::= st <type>                      # sizeof (a type)
2876   //              ::= at <type>                      # alignof (a type)
2877   //              ::= <template-param>
2878   //              ::= <function-param>
2879   //              ::= sr <type> <unqualified-name>                   # dependent name
2880   //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
2881   //              ::= ds <expression> <expression>                   # expr.*expr
2882   //              ::= sZ <template-param>                            # size of a parameter pack
2883   //              ::= sZ <function-param>    # size of a function parameter pack
2884   //              ::= <expr-primary>
2885   // <expr-primary> ::= L <type> <value number> E    # integer literal
2886   //                ::= L <type <value float> E      # floating literal
2887   //                ::= L <mangled-name> E           # external name
2888   //                ::= fpT                          # 'this' expression
2889   QualType ImplicitlyConvertedToType;
2890 
2891 recurse:
2892   switch (E->getStmtClass()) {
2893   case Expr::NoStmtClass:
2894 #define ABSTRACT_STMT(Type)
2895 #define EXPR(Type, Base)
2896 #define STMT(Type, Base) \
2897   case Expr::Type##Class:
2898 #include "clang/AST/StmtNodes.inc"
2899     // fallthrough
2900 
2901   // These all can only appear in local or variable-initialization
2902   // contexts and so should never appear in a mangling.
2903   case Expr::AddrLabelExprClass:
2904   case Expr::DesignatedInitUpdateExprClass:
2905   case Expr::ImplicitValueInitExprClass:
2906   case Expr::NoInitExprClass:
2907   case Expr::ParenListExprClass:
2908   case Expr::LambdaExprClass:
2909   case Expr::MSPropertyRefExprClass:
2910   case Expr::MSPropertySubscriptExprClass:
2911   case Expr::TypoExprClass:  // This should no longer exist in the AST by now.
2912   case Expr::OMPArraySectionExprClass:
2913     llvm_unreachable("unexpected statement kind");
2914 
2915   // FIXME: invent manglings for all these.
2916   case Expr::BlockExprClass:
2917   case Expr::ChooseExprClass:
2918   case Expr::CompoundLiteralExprClass:
2919   case Expr::DesignatedInitExprClass:
2920   case Expr::ExtVectorElementExprClass:
2921   case Expr::GenericSelectionExprClass:
2922   case Expr::ObjCEncodeExprClass:
2923   case Expr::ObjCIsaExprClass:
2924   case Expr::ObjCIvarRefExprClass:
2925   case Expr::ObjCMessageExprClass:
2926   case Expr::ObjCPropertyRefExprClass:
2927   case Expr::ObjCProtocolExprClass:
2928   case Expr::ObjCSelectorExprClass:
2929   case Expr::ObjCStringLiteralClass:
2930   case Expr::ObjCBoxedExprClass:
2931   case Expr::ObjCArrayLiteralClass:
2932   case Expr::ObjCDictionaryLiteralClass:
2933   case Expr::ObjCSubscriptRefExprClass:
2934   case Expr::ObjCIndirectCopyRestoreExprClass:
2935   case Expr::OffsetOfExprClass:
2936   case Expr::PredefinedExprClass:
2937   case Expr::ShuffleVectorExprClass:
2938   case Expr::ConvertVectorExprClass:
2939   case Expr::StmtExprClass:
2940   case Expr::TypeTraitExprClass:
2941   case Expr::ArrayTypeTraitExprClass:
2942   case Expr::ExpressionTraitExprClass:
2943   case Expr::VAArgExprClass:
2944   case Expr::CUDAKernelCallExprClass:
2945   case Expr::AsTypeExprClass:
2946   case Expr::PseudoObjectExprClass:
2947   case Expr::AtomicExprClass:
2948   {
2949     // As bad as this diagnostic is, it's better than crashing.
2950     DiagnosticsEngine &Diags = Context.getDiags();
2951     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2952                                      "cannot yet mangle expression type %0");
2953     Diags.Report(E->getExprLoc(), DiagID)
2954       << E->getStmtClassName() << E->getSourceRange();
2955     break;
2956   }
2957 
2958   case Expr::CXXUuidofExprClass: {
2959     const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2960     if (UE->isTypeOperand()) {
2961       QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2962       Out << "u8__uuidoft";
2963       mangleType(UuidT);
2964     } else {
2965       Expr *UuidExp = UE->getExprOperand();
2966       Out << "u8__uuidofz";
2967       mangleExpression(UuidExp, Arity);
2968     }
2969     break;
2970   }
2971 
2972   // Even gcc-4.5 doesn't mangle this.
2973   case Expr::BinaryConditionalOperatorClass: {
2974     DiagnosticsEngine &Diags = Context.getDiags();
2975     unsigned DiagID =
2976       Diags.getCustomDiagID(DiagnosticsEngine::Error,
2977                 "?: operator with omitted middle operand cannot be mangled");
2978     Diags.Report(E->getExprLoc(), DiagID)
2979       << E->getStmtClassName() << E->getSourceRange();
2980     break;
2981   }
2982 
2983   // These are used for internal purposes and cannot be meaningfully mangled.
2984   case Expr::OpaqueValueExprClass:
2985     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2986 
2987   case Expr::InitListExprClass: {
2988     Out << "il";
2989     mangleInitListElements(cast<InitListExpr>(E));
2990     Out << "E";
2991     break;
2992   }
2993 
2994   case Expr::CXXDefaultArgExprClass:
2995     mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2996     break;
2997 
2998   case Expr::CXXDefaultInitExprClass:
2999     mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3000     break;
3001 
3002   case Expr::CXXStdInitializerListExprClass:
3003     mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3004     break;
3005 
3006   case Expr::SubstNonTypeTemplateParmExprClass:
3007     mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3008                      Arity);
3009     break;
3010 
3011   case Expr::UserDefinedLiteralClass:
3012     // We follow g++'s approach of mangling a UDL as a call to the literal
3013     // operator.
3014   case Expr::CXXMemberCallExprClass: // fallthrough
3015   case Expr::CallExprClass: {
3016     const CallExpr *CE = cast<CallExpr>(E);
3017 
3018     // <expression> ::= cp <simple-id> <expression>* E
3019     // We use this mangling only when the call would use ADL except
3020     // for being parenthesized.  Per discussion with David
3021     // Vandervoorde, 2011.04.25.
3022     if (isParenthesizedADLCallee(CE)) {
3023       Out << "cp";
3024       // The callee here is a parenthesized UnresolvedLookupExpr with
3025       // no qualifier and should always get mangled as a <simple-id>
3026       // anyway.
3027 
3028     // <expression> ::= cl <expression>* E
3029     } else {
3030       Out << "cl";
3031     }
3032 
3033     unsigned CallArity = CE->getNumArgs();
3034     for (const Expr *Arg : CE->arguments())
3035       if (isa<PackExpansionExpr>(Arg))
3036         CallArity = UnknownArity;
3037 
3038     mangleExpression(CE->getCallee(), CallArity);
3039     for (const Expr *Arg : CE->arguments())
3040       mangleExpression(Arg);
3041     Out << 'E';
3042     break;
3043   }
3044 
3045   case Expr::CXXNewExprClass: {
3046     const CXXNewExpr *New = cast<CXXNewExpr>(E);
3047     if (New->isGlobalNew()) Out << "gs";
3048     Out << (New->isArray() ? "na" : "nw");
3049     for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3050            E = New->placement_arg_end(); I != E; ++I)
3051       mangleExpression(*I);
3052     Out << '_';
3053     mangleType(New->getAllocatedType());
3054     if (New->hasInitializer()) {
3055       if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3056         Out << "il";
3057       else
3058         Out << "pi";
3059       const Expr *Init = New->getInitializer();
3060       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3061         // Directly inline the initializers.
3062         for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3063                                                   E = CCE->arg_end();
3064              I != E; ++I)
3065           mangleExpression(*I);
3066       } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3067         for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3068           mangleExpression(PLE->getExpr(i));
3069       } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3070                  isa<InitListExpr>(Init)) {
3071         // Only take InitListExprs apart for list-initialization.
3072         mangleInitListElements(cast<InitListExpr>(Init));
3073       } else
3074         mangleExpression(Init);
3075     }
3076     Out << 'E';
3077     break;
3078   }
3079 
3080   case Expr::CXXPseudoDestructorExprClass: {
3081     const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3082     if (const Expr *Base = PDE->getBase())
3083       mangleMemberExprBase(Base, PDE->isArrow());
3084     NestedNameSpecifier *Qualifier = PDE->getQualifier();
3085     QualType ScopeType;
3086     if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3087       if (Qualifier) {
3088         mangleUnresolvedPrefix(Qualifier,
3089                                /*Recursive=*/true);
3090         mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3091         Out << 'E';
3092       } else {
3093         Out << "sr";
3094         if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3095           Out << 'E';
3096       }
3097     } else if (Qualifier) {
3098       mangleUnresolvedPrefix(Qualifier);
3099     }
3100     // <base-unresolved-name> ::= dn <destructor-name>
3101     Out << "dn";
3102     QualType DestroyedType = PDE->getDestroyedType();
3103     mangleUnresolvedTypeOrSimpleId(DestroyedType);
3104     break;
3105   }
3106 
3107   case Expr::MemberExprClass: {
3108     const MemberExpr *ME = cast<MemberExpr>(E);
3109     mangleMemberExpr(ME->getBase(), ME->isArrow(),
3110                      ME->getQualifier(), nullptr,
3111                      ME->getMemberDecl()->getDeclName(), Arity);
3112     break;
3113   }
3114 
3115   case Expr::UnresolvedMemberExprClass: {
3116     const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3117     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3118                      ME->isArrow(), ME->getQualifier(), nullptr,
3119                      ME->getMemberName(), Arity);
3120     if (ME->hasExplicitTemplateArgs())
3121       mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3122     break;
3123   }
3124 
3125   case Expr::CXXDependentScopeMemberExprClass: {
3126     const CXXDependentScopeMemberExpr *ME
3127       = cast<CXXDependentScopeMemberExpr>(E);
3128     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3129                      ME->isArrow(), ME->getQualifier(),
3130                      ME->getFirstQualifierFoundInScope(),
3131                      ME->getMember(), Arity);
3132     if (ME->hasExplicitTemplateArgs())
3133       mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3134     break;
3135   }
3136 
3137   case Expr::UnresolvedLookupExprClass: {
3138     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3139     mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
3140 
3141     // All the <unresolved-name> productions end in a
3142     // base-unresolved-name, where <template-args> are just tacked
3143     // onto the end.
3144     if (ULE->hasExplicitTemplateArgs())
3145       mangleTemplateArgs(ULE->getTemplateArgs(), ULE->getNumTemplateArgs());
3146     break;
3147   }
3148 
3149   case Expr::CXXUnresolvedConstructExprClass: {
3150     const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3151     unsigned N = CE->arg_size();
3152 
3153     Out << "cv";
3154     mangleType(CE->getType());
3155     if (N != 1) Out << '_';
3156     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3157     if (N != 1) Out << 'E';
3158     break;
3159   }
3160 
3161   case Expr::CXXConstructExprClass: {
3162     const auto *CE = cast<CXXConstructExpr>(E);
3163     if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3164       assert(
3165           CE->getNumArgs() >= 1 &&
3166           (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3167           "implicit CXXConstructExpr must have one argument");
3168       return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3169     }
3170     Out << "il";
3171     for (auto *E : CE->arguments())
3172       mangleExpression(E);
3173     Out << "E";
3174     break;
3175   }
3176 
3177   case Expr::CXXTemporaryObjectExprClass: {
3178     const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3179     unsigned N = CE->getNumArgs();
3180     bool List = CE->isListInitialization();
3181 
3182     if (List)
3183       Out << "tl";
3184     else
3185       Out << "cv";
3186     mangleType(CE->getType());
3187     if (!List && N != 1)
3188       Out << '_';
3189     if (CE->isStdInitListInitialization()) {
3190       // We implicitly created a std::initializer_list<T> for the first argument
3191       // of a constructor of type U in an expression of the form U{a, b, c}.
3192       // Strip all the semantic gunk off the initializer list.
3193       auto *SILE =
3194           cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3195       auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3196       mangleInitListElements(ILE);
3197     } else {
3198       for (auto *E : CE->arguments())
3199         mangleExpression(E);
3200     }
3201     if (List || N != 1)
3202       Out << 'E';
3203     break;
3204   }
3205 
3206   case Expr::CXXScalarValueInitExprClass:
3207     Out << "cv";
3208     mangleType(E->getType());
3209     Out << "_E";
3210     break;
3211 
3212   case Expr::CXXNoexceptExprClass:
3213     Out << "nx";
3214     mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3215     break;
3216 
3217   case Expr::UnaryExprOrTypeTraitExprClass: {
3218     const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3219 
3220     if (!SAE->isInstantiationDependent()) {
3221       // Itanium C++ ABI:
3222       //   If the operand of a sizeof or alignof operator is not
3223       //   instantiation-dependent it is encoded as an integer literal
3224       //   reflecting the result of the operator.
3225       //
3226       //   If the result of the operator is implicitly converted to a known
3227       //   integer type, that type is used for the literal; otherwise, the type
3228       //   of std::size_t or std::ptrdiff_t is used.
3229       QualType T = (ImplicitlyConvertedToType.isNull() ||
3230                     !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3231                                                     : ImplicitlyConvertedToType;
3232       llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3233       mangleIntegerLiteral(T, V);
3234       break;
3235     }
3236 
3237     switch(SAE->getKind()) {
3238     case UETT_SizeOf:
3239       Out << 's';
3240       break;
3241     case UETT_AlignOf:
3242       Out << 'a';
3243       break;
3244     case UETT_VecStep: {
3245       DiagnosticsEngine &Diags = Context.getDiags();
3246       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3247                                      "cannot yet mangle vec_step expression");
3248       Diags.Report(DiagID);
3249       return;
3250     }
3251     case UETT_OpenMPRequiredSimdAlign:
3252       DiagnosticsEngine &Diags = Context.getDiags();
3253       unsigned DiagID = Diags.getCustomDiagID(
3254           DiagnosticsEngine::Error,
3255           "cannot yet mangle __builtin_omp_required_simd_align expression");
3256       Diags.Report(DiagID);
3257       return;
3258     }
3259     if (SAE->isArgumentType()) {
3260       Out << 't';
3261       mangleType(SAE->getArgumentType());
3262     } else {
3263       Out << 'z';
3264       mangleExpression(SAE->getArgumentExpr());
3265     }
3266     break;
3267   }
3268 
3269   case Expr::CXXThrowExprClass: {
3270     const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3271     //  <expression> ::= tw <expression>  # throw expression
3272     //               ::= tr               # rethrow
3273     if (TE->getSubExpr()) {
3274       Out << "tw";
3275       mangleExpression(TE->getSubExpr());
3276     } else {
3277       Out << "tr";
3278     }
3279     break;
3280   }
3281 
3282   case Expr::CXXTypeidExprClass: {
3283     const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3284     //  <expression> ::= ti <type>        # typeid (type)
3285     //               ::= te <expression>  # typeid (expression)
3286     if (TIE->isTypeOperand()) {
3287       Out << "ti";
3288       mangleType(TIE->getTypeOperand(Context.getASTContext()));
3289     } else {
3290       Out << "te";
3291       mangleExpression(TIE->getExprOperand());
3292     }
3293     break;
3294   }
3295 
3296   case Expr::CXXDeleteExprClass: {
3297     const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3298     //  <expression> ::= [gs] dl <expression>  # [::] delete expr
3299     //               ::= [gs] da <expression>  # [::] delete [] expr
3300     if (DE->isGlobalDelete()) Out << "gs";
3301     Out << (DE->isArrayForm() ? "da" : "dl");
3302     mangleExpression(DE->getArgument());
3303     break;
3304   }
3305 
3306   case Expr::UnaryOperatorClass: {
3307     const UnaryOperator *UO = cast<UnaryOperator>(E);
3308     mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3309                        /*Arity=*/1);
3310     mangleExpression(UO->getSubExpr());
3311     break;
3312   }
3313 
3314   case Expr::ArraySubscriptExprClass: {
3315     const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3316 
3317     // Array subscript is treated as a syntactically weird form of
3318     // binary operator.
3319     Out << "ix";
3320     mangleExpression(AE->getLHS());
3321     mangleExpression(AE->getRHS());
3322     break;
3323   }
3324 
3325   case Expr::CompoundAssignOperatorClass: // fallthrough
3326   case Expr::BinaryOperatorClass: {
3327     const BinaryOperator *BO = cast<BinaryOperator>(E);
3328     if (BO->getOpcode() == BO_PtrMemD)
3329       Out << "ds";
3330     else
3331       mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3332                          /*Arity=*/2);
3333     mangleExpression(BO->getLHS());
3334     mangleExpression(BO->getRHS());
3335     break;
3336   }
3337 
3338   case Expr::ConditionalOperatorClass: {
3339     const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3340     mangleOperatorName(OO_Conditional, /*Arity=*/3);
3341     mangleExpression(CO->getCond());
3342     mangleExpression(CO->getLHS(), Arity);
3343     mangleExpression(CO->getRHS(), Arity);
3344     break;
3345   }
3346 
3347   case Expr::ImplicitCastExprClass: {
3348     ImplicitlyConvertedToType = E->getType();
3349     E = cast<ImplicitCastExpr>(E)->getSubExpr();
3350     goto recurse;
3351   }
3352 
3353   case Expr::ObjCBridgedCastExprClass: {
3354     // Mangle ownership casts as a vendor extended operator __bridge,
3355     // __bridge_transfer, or __bridge_retain.
3356     StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3357     Out << "v1U" << Kind.size() << Kind;
3358   }
3359   // Fall through to mangle the cast itself.
3360 
3361   case Expr::CStyleCastExprClass:
3362     mangleCastExpression(E, "cv");
3363     break;
3364 
3365   case Expr::CXXFunctionalCastExprClass: {
3366     auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3367     // FIXME: Add isImplicit to CXXConstructExpr.
3368     if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3369       if (CCE->getParenOrBraceRange().isInvalid())
3370         Sub = CCE->getArg(0)->IgnoreImplicit();
3371     if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3372       Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3373     if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3374       Out << "tl";
3375       mangleType(E->getType());
3376       mangleInitListElements(IL);
3377       Out << "E";
3378     } else {
3379       mangleCastExpression(E, "cv");
3380     }
3381     break;
3382   }
3383 
3384   case Expr::CXXStaticCastExprClass:
3385     mangleCastExpression(E, "sc");
3386     break;
3387   case Expr::CXXDynamicCastExprClass:
3388     mangleCastExpression(E, "dc");
3389     break;
3390   case Expr::CXXReinterpretCastExprClass:
3391     mangleCastExpression(E, "rc");
3392     break;
3393   case Expr::CXXConstCastExprClass:
3394     mangleCastExpression(E, "cc");
3395     break;
3396 
3397   case Expr::CXXOperatorCallExprClass: {
3398     const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3399     unsigned NumArgs = CE->getNumArgs();
3400     mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3401     // Mangle the arguments.
3402     for (unsigned i = 0; i != NumArgs; ++i)
3403       mangleExpression(CE->getArg(i));
3404     break;
3405   }
3406 
3407   case Expr::ParenExprClass:
3408     mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3409     break;
3410 
3411   case Expr::DeclRefExprClass: {
3412     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3413 
3414     switch (D->getKind()) {
3415     default:
3416       //  <expr-primary> ::= L <mangled-name> E # external name
3417       Out << 'L';
3418       mangle(D);
3419       Out << 'E';
3420       break;
3421 
3422     case Decl::ParmVar:
3423       mangleFunctionParam(cast<ParmVarDecl>(D));
3424       break;
3425 
3426     case Decl::EnumConstant: {
3427       const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3428       mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3429       break;
3430     }
3431 
3432     case Decl::NonTypeTemplateParm: {
3433       const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3434       mangleTemplateParameter(PD->getIndex());
3435       break;
3436     }
3437 
3438     }
3439 
3440     break;
3441   }
3442 
3443   case Expr::SubstNonTypeTemplateParmPackExprClass:
3444     // FIXME: not clear how to mangle this!
3445     // template <unsigned N...> class A {
3446     //   template <class U...> void foo(U (&x)[N]...);
3447     // };
3448     Out << "_SUBSTPACK_";
3449     break;
3450 
3451   case Expr::FunctionParmPackExprClass: {
3452     // FIXME: not clear how to mangle this!
3453     const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3454     Out << "v110_SUBSTPACK";
3455     mangleFunctionParam(FPPE->getParameterPack());
3456     break;
3457   }
3458 
3459   case Expr::DependentScopeDeclRefExprClass: {
3460     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3461     mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
3462 
3463     // All the <unresolved-name> productions end in a
3464     // base-unresolved-name, where <template-args> are just tacked
3465     // onto the end.
3466     if (DRE->hasExplicitTemplateArgs())
3467       mangleTemplateArgs(DRE->getTemplateArgs(), DRE->getNumTemplateArgs());
3468     break;
3469   }
3470 
3471   case Expr::CXXBindTemporaryExprClass:
3472     mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3473     break;
3474 
3475   case Expr::ExprWithCleanupsClass:
3476     mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3477     break;
3478 
3479   case Expr::FloatingLiteralClass: {
3480     const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3481     Out << 'L';
3482     mangleType(FL->getType());
3483     mangleFloat(FL->getValue());
3484     Out << 'E';
3485     break;
3486   }
3487 
3488   case Expr::CharacterLiteralClass:
3489     Out << 'L';
3490     mangleType(E->getType());
3491     Out << cast<CharacterLiteral>(E)->getValue();
3492     Out << 'E';
3493     break;
3494 
3495   // FIXME. __objc_yes/__objc_no are mangled same as true/false
3496   case Expr::ObjCBoolLiteralExprClass:
3497     Out << "Lb";
3498     Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3499     Out << 'E';
3500     break;
3501 
3502   case Expr::CXXBoolLiteralExprClass:
3503     Out << "Lb";
3504     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3505     Out << 'E';
3506     break;
3507 
3508   case Expr::IntegerLiteralClass: {
3509     llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3510     if (E->getType()->isSignedIntegerType())
3511       Value.setIsSigned(true);
3512     mangleIntegerLiteral(E->getType(), Value);
3513     break;
3514   }
3515 
3516   case Expr::ImaginaryLiteralClass: {
3517     const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3518     // Mangle as if a complex literal.
3519     // Proposal from David Vandevoorde, 2010.06.30.
3520     Out << 'L';
3521     mangleType(E->getType());
3522     if (const FloatingLiteral *Imag =
3523           dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3524       // Mangle a floating-point zero of the appropriate type.
3525       mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3526       Out << '_';
3527       mangleFloat(Imag->getValue());
3528     } else {
3529       Out << "0_";
3530       llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3531       if (IE->getSubExpr()->getType()->isSignedIntegerType())
3532         Value.setIsSigned(true);
3533       mangleNumber(Value);
3534     }
3535     Out << 'E';
3536     break;
3537   }
3538 
3539   case Expr::StringLiteralClass: {
3540     // Revised proposal from David Vandervoorde, 2010.07.15.
3541     Out << 'L';
3542     assert(isa<ConstantArrayType>(E->getType()));
3543     mangleType(E->getType());
3544     Out << 'E';
3545     break;
3546   }
3547 
3548   case Expr::GNUNullExprClass:
3549     // FIXME: should this really be mangled the same as nullptr?
3550     // fallthrough
3551 
3552   case Expr::CXXNullPtrLiteralExprClass: {
3553     Out << "LDnE";
3554     break;
3555   }
3556 
3557   case Expr::PackExpansionExprClass:
3558     Out << "sp";
3559     mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3560     break;
3561 
3562   case Expr::SizeOfPackExprClass: {
3563     auto *SPE = cast<SizeOfPackExpr>(E);
3564     if (SPE->isPartiallySubstituted()) {
3565       Out << "sP";
3566       for (const auto &A : SPE->getPartialArguments())
3567         mangleTemplateArg(A);
3568       Out << "E";
3569       break;
3570     }
3571 
3572     Out << "sZ";
3573     const NamedDecl *Pack = SPE->getPack();
3574     if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3575       mangleTemplateParameter(TTP->getIndex());
3576     else if (const NonTypeTemplateParmDecl *NTTP
3577                 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3578       mangleTemplateParameter(NTTP->getIndex());
3579     else if (const TemplateTemplateParmDecl *TempTP
3580                                     = dyn_cast<TemplateTemplateParmDecl>(Pack))
3581       mangleTemplateParameter(TempTP->getIndex());
3582     else
3583       mangleFunctionParam(cast<ParmVarDecl>(Pack));
3584     break;
3585   }
3586 
3587   case Expr::MaterializeTemporaryExprClass: {
3588     mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3589     break;
3590   }
3591 
3592   case Expr::CXXFoldExprClass: {
3593     auto *FE = cast<CXXFoldExpr>(E);
3594     if (FE->isLeftFold())
3595       Out << (FE->getInit() ? "fL" : "fl");
3596     else
3597       Out << (FE->getInit() ? "fR" : "fr");
3598 
3599     if (FE->getOperator() == BO_PtrMemD)
3600       Out << "ds";
3601     else
3602       mangleOperatorName(
3603           BinaryOperator::getOverloadedOperator(FE->getOperator()),
3604           /*Arity=*/2);
3605 
3606     if (FE->getLHS())
3607       mangleExpression(FE->getLHS());
3608     if (FE->getRHS())
3609       mangleExpression(FE->getRHS());
3610     break;
3611   }
3612 
3613   case Expr::CXXThisExprClass:
3614     Out << "fpT";
3615     break;
3616 
3617   case Expr::CoawaitExprClass:
3618     // FIXME: Propose a non-vendor mangling.
3619     Out << "v18co_await";
3620     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3621     break;
3622 
3623   case Expr::CoyieldExprClass:
3624     // FIXME: Propose a non-vendor mangling.
3625     Out << "v18co_yield";
3626     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3627     break;
3628   }
3629 }
3630 
3631 /// Mangle an expression which refers to a parameter variable.
3632 ///
3633 /// <expression>     ::= <function-param>
3634 /// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 0
3635 /// <function-param> ::= fp <top-level CV-qualifiers>
3636 ///                      <parameter-2 non-negative number> _ # L == 0, I > 0
3637 /// <function-param> ::= fL <L-1 non-negative number>
3638 ///                      p <top-level CV-qualifiers> _       # L > 0, I == 0
3639 /// <function-param> ::= fL <L-1 non-negative number>
3640 ///                      p <top-level CV-qualifiers>
3641 ///                      <I-1 non-negative number> _         # L > 0, I > 0
3642 ///
3643 /// L is the nesting depth of the parameter, defined as 1 if the
3644 /// parameter comes from the innermost function prototype scope
3645 /// enclosing the current context, 2 if from the next enclosing
3646 /// function prototype scope, and so on, with one special case: if
3647 /// we've processed the full parameter clause for the innermost
3648 /// function type, then L is one less.  This definition conveniently
3649 /// makes it irrelevant whether a function's result type was written
3650 /// trailing or leading, but is otherwise overly complicated; the
3651 /// numbering was first designed without considering references to
3652 /// parameter in locations other than return types, and then the
3653 /// mangling had to be generalized without changing the existing
3654 /// manglings.
3655 ///
3656 /// I is the zero-based index of the parameter within its parameter
3657 /// declaration clause.  Note that the original ABI document describes
3658 /// this using 1-based ordinals.
3659 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3660   unsigned parmDepth = parm->getFunctionScopeDepth();
3661   unsigned parmIndex = parm->getFunctionScopeIndex();
3662 
3663   // Compute 'L'.
3664   // parmDepth does not include the declaring function prototype.
3665   // FunctionTypeDepth does account for that.
3666   assert(parmDepth < FunctionTypeDepth.getDepth());
3667   unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3668   if (FunctionTypeDepth.isInResultType())
3669     nestingDepth--;
3670 
3671   if (nestingDepth == 0) {
3672     Out << "fp";
3673   } else {
3674     Out << "fL" << (nestingDepth - 1) << 'p';
3675   }
3676 
3677   // Top-level qualifiers.  We don't have to worry about arrays here,
3678   // because parameters declared as arrays should already have been
3679   // transformed to have pointer type. FIXME: apparently these don't
3680   // get mangled if used as an rvalue of a known non-class type?
3681   assert(!parm->getType()->isArrayType()
3682          && "parameter's type is still an array type?");
3683   mangleQualifiers(parm->getType().getQualifiers());
3684 
3685   // Parameter index.
3686   if (parmIndex != 0) {
3687     Out << (parmIndex - 1);
3688   }
3689   Out << '_';
3690 }
3691 
3692 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3693   // <ctor-dtor-name> ::= C1  # complete object constructor
3694   //                  ::= C2  # base object constructor
3695   //
3696   // In addition, C5 is a comdat name with C1 and C2 in it.
3697   switch (T) {
3698   case Ctor_Complete:
3699     Out << "C1";
3700     break;
3701   case Ctor_Base:
3702     Out << "C2";
3703     break;
3704   case Ctor_Comdat:
3705     Out << "C5";
3706     break;
3707   case Ctor_DefaultClosure:
3708   case Ctor_CopyingClosure:
3709     llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
3710   }
3711 }
3712 
3713 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3714   // <ctor-dtor-name> ::= D0  # deleting destructor
3715   //                  ::= D1  # complete object destructor
3716   //                  ::= D2  # base object destructor
3717   //
3718   // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
3719   switch (T) {
3720   case Dtor_Deleting:
3721     Out << "D0";
3722     break;
3723   case Dtor_Complete:
3724     Out << "D1";
3725     break;
3726   case Dtor_Base:
3727     Out << "D2";
3728     break;
3729   case Dtor_Comdat:
3730     Out << "D5";
3731     break;
3732   }
3733 }
3734 
3735 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
3736                                         unsigned NumTemplateArgs) {
3737   // <template-args> ::= I <template-arg>+ E
3738   Out << 'I';
3739   for (unsigned i = 0; i != NumTemplateArgs; ++i)
3740     mangleTemplateArg(TemplateArgs[i].getArgument());
3741   Out << 'E';
3742 }
3743 
3744 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3745   // <template-args> ::= I <template-arg>+ E
3746   Out << 'I';
3747   for (unsigned i = 0, e = AL.size(); i != e; ++i)
3748     mangleTemplateArg(AL[i]);
3749   Out << 'E';
3750 }
3751 
3752 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3753                                         unsigned NumTemplateArgs) {
3754   // <template-args> ::= I <template-arg>+ E
3755   Out << 'I';
3756   for (unsigned i = 0; i != NumTemplateArgs; ++i)
3757     mangleTemplateArg(TemplateArgs[i]);
3758   Out << 'E';
3759 }
3760 
3761 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3762   // <template-arg> ::= <type>              # type or template
3763   //                ::= X <expression> E    # expression
3764   //                ::= <expr-primary>      # simple expressions
3765   //                ::= J <template-arg>* E # argument pack
3766   if (!A.isInstantiationDependent() || A.isDependent())
3767     A = Context.getASTContext().getCanonicalTemplateArgument(A);
3768 
3769   switch (A.getKind()) {
3770   case TemplateArgument::Null:
3771     llvm_unreachable("Cannot mangle NULL template argument");
3772 
3773   case TemplateArgument::Type:
3774     mangleType(A.getAsType());
3775     break;
3776   case TemplateArgument::Template:
3777     // This is mangled as <type>.
3778     mangleType(A.getAsTemplate());
3779     break;
3780   case TemplateArgument::TemplateExpansion:
3781     // <type>  ::= Dp <type>          # pack expansion (C++0x)
3782     Out << "Dp";
3783     mangleType(A.getAsTemplateOrTemplatePattern());
3784     break;
3785   case TemplateArgument::Expression: {
3786     // It's possible to end up with a DeclRefExpr here in certain
3787     // dependent cases, in which case we should mangle as a
3788     // declaration.
3789     const Expr *E = A.getAsExpr()->IgnoreParens();
3790     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3791       const ValueDecl *D = DRE->getDecl();
3792       if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3793         Out << 'L';
3794         mangle(D);
3795         Out << 'E';
3796         break;
3797       }
3798     }
3799 
3800     Out << 'X';
3801     mangleExpression(E);
3802     Out << 'E';
3803     break;
3804   }
3805   case TemplateArgument::Integral:
3806     mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3807     break;
3808   case TemplateArgument::Declaration: {
3809     //  <expr-primary> ::= L <mangled-name> E # external name
3810     // Clang produces AST's where pointer-to-member-function expressions
3811     // and pointer-to-function expressions are represented as a declaration not
3812     // an expression. We compensate for it here to produce the correct mangling.
3813     ValueDecl *D = A.getAsDecl();
3814     bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
3815     if (compensateMangling) {
3816       Out << 'X';
3817       mangleOperatorName(OO_Amp, 1);
3818     }
3819 
3820     Out << 'L';
3821     // References to external entities use the mangled name; if the name would
3822     // not normally be mangled then mangle it as unqualified.
3823     mangle(D);
3824     Out << 'E';
3825 
3826     if (compensateMangling)
3827       Out << 'E';
3828 
3829     break;
3830   }
3831   case TemplateArgument::NullPtr: {
3832     //  <expr-primary> ::= L <type> 0 E
3833     Out << 'L';
3834     mangleType(A.getNullPtrType());
3835     Out << "0E";
3836     break;
3837   }
3838   case TemplateArgument::Pack: {
3839     //  <template-arg> ::= J <template-arg>* E
3840     Out << 'J';
3841     for (const auto &P : A.pack_elements())
3842       mangleTemplateArg(P);
3843     Out << 'E';
3844   }
3845   }
3846 }
3847 
3848 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3849   // <template-param> ::= T_    # first template parameter
3850   //                  ::= T <parameter-2 non-negative number> _
3851   if (Index == 0)
3852     Out << "T_";
3853   else
3854     Out << 'T' << (Index - 1) << '_';
3855 }
3856 
3857 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3858   if (SeqID == 1)
3859     Out << '0';
3860   else if (SeqID > 1) {
3861     SeqID--;
3862 
3863     // <seq-id> is encoded in base-36, using digits and upper case letters.
3864     char Buffer[7]; // log(2**32) / log(36) ~= 7
3865     MutableArrayRef<char> BufferRef(Buffer);
3866     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
3867 
3868     for (; SeqID != 0; SeqID /= 36) {
3869       unsigned C = SeqID % 36;
3870       *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3871     }
3872 
3873     Out.write(I.base(), I - BufferRef.rbegin());
3874   }
3875   Out << '_';
3876 }
3877 
3878 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3879   bool result = mangleSubstitution(type);
3880   assert(result && "no existing substitution for type");
3881   (void) result;
3882 }
3883 
3884 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3885   bool result = mangleSubstitution(tname);
3886   assert(result && "no existing substitution for template name");
3887   (void) result;
3888 }
3889 
3890 // <substitution> ::= S <seq-id> _
3891 //                ::= S_
3892 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3893   // Try one of the standard substitutions first.
3894   if (mangleStandardSubstitution(ND))
3895     return true;
3896 
3897   ND = cast<NamedDecl>(ND->getCanonicalDecl());
3898   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3899 }
3900 
3901 /// Determine whether the given type has any qualifiers that are relevant for
3902 /// substitutions.
3903 static bool hasMangledSubstitutionQualifiers(QualType T) {
3904   Qualifiers Qs = T.getQualifiers();
3905   return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3906 }
3907 
3908 bool CXXNameMangler::mangleSubstitution(QualType T) {
3909   if (!hasMangledSubstitutionQualifiers(T)) {
3910     if (const RecordType *RT = T->getAs<RecordType>())
3911       return mangleSubstitution(RT->getDecl());
3912   }
3913 
3914   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3915 
3916   return mangleSubstitution(TypePtr);
3917 }
3918 
3919 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3920   if (TemplateDecl *TD = Template.getAsTemplateDecl())
3921     return mangleSubstitution(TD);
3922 
3923   Template = Context.getASTContext().getCanonicalTemplateName(Template);
3924   return mangleSubstitution(
3925                       reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3926 }
3927 
3928 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3929   llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3930   if (I == Substitutions.end())
3931     return false;
3932 
3933   unsigned SeqID = I->second;
3934   Out << 'S';
3935   mangleSeqID(SeqID);
3936 
3937   return true;
3938 }
3939 
3940 static bool isCharType(QualType T) {
3941   if (T.isNull())
3942     return false;
3943 
3944   return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3945     T->isSpecificBuiltinType(BuiltinType::Char_U);
3946 }
3947 
3948 /// Returns whether a given type is a template specialization of a given name
3949 /// with a single argument of type char.
3950 static bool isCharSpecialization(QualType T, const char *Name) {
3951   if (T.isNull())
3952     return false;
3953 
3954   const RecordType *RT = T->getAs<RecordType>();
3955   if (!RT)
3956     return false;
3957 
3958   const ClassTemplateSpecializationDecl *SD =
3959     dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3960   if (!SD)
3961     return false;
3962 
3963   if (!isStdNamespace(getEffectiveDeclContext(SD)))
3964     return false;
3965 
3966   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3967   if (TemplateArgs.size() != 1)
3968     return false;
3969 
3970   if (!isCharType(TemplateArgs[0].getAsType()))
3971     return false;
3972 
3973   return SD->getIdentifier()->getName() == Name;
3974 }
3975 
3976 template <std::size_t StrLen>
3977 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3978                                        const char (&Str)[StrLen]) {
3979   if (!SD->getIdentifier()->isStr(Str))
3980     return false;
3981 
3982   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3983   if (TemplateArgs.size() != 2)
3984     return false;
3985 
3986   if (!isCharType(TemplateArgs[0].getAsType()))
3987     return false;
3988 
3989   if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3990     return false;
3991 
3992   return true;
3993 }
3994 
3995 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3996   // <substitution> ::= St # ::std::
3997   if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3998     if (isStd(NS)) {
3999       Out << "St";
4000       return true;
4001     }
4002   }
4003 
4004   if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4005     if (!isStdNamespace(getEffectiveDeclContext(TD)))
4006       return false;
4007 
4008     // <substitution> ::= Sa # ::std::allocator
4009     if (TD->getIdentifier()->isStr("allocator")) {
4010       Out << "Sa";
4011       return true;
4012     }
4013 
4014     // <<substitution> ::= Sb # ::std::basic_string
4015     if (TD->getIdentifier()->isStr("basic_string")) {
4016       Out << "Sb";
4017       return true;
4018     }
4019   }
4020 
4021   if (const ClassTemplateSpecializationDecl *SD =
4022         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4023     if (!isStdNamespace(getEffectiveDeclContext(SD)))
4024       return false;
4025 
4026     //    <substitution> ::= Ss # ::std::basic_string<char,
4027     //                            ::std::char_traits<char>,
4028     //                            ::std::allocator<char> >
4029     if (SD->getIdentifier()->isStr("basic_string")) {
4030       const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4031 
4032       if (TemplateArgs.size() != 3)
4033         return false;
4034 
4035       if (!isCharType(TemplateArgs[0].getAsType()))
4036         return false;
4037 
4038       if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4039         return false;
4040 
4041       if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4042         return false;
4043 
4044       Out << "Ss";
4045       return true;
4046     }
4047 
4048     //    <substitution> ::= Si # ::std::basic_istream<char,
4049     //                            ::std::char_traits<char> >
4050     if (isStreamCharSpecialization(SD, "basic_istream")) {
4051       Out << "Si";
4052       return true;
4053     }
4054 
4055     //    <substitution> ::= So # ::std::basic_ostream<char,
4056     //                            ::std::char_traits<char> >
4057     if (isStreamCharSpecialization(SD, "basic_ostream")) {
4058       Out << "So";
4059       return true;
4060     }
4061 
4062     //    <substitution> ::= Sd # ::std::basic_iostream<char,
4063     //                            ::std::char_traits<char> >
4064     if (isStreamCharSpecialization(SD, "basic_iostream")) {
4065       Out << "Sd";
4066       return true;
4067     }
4068   }
4069   return false;
4070 }
4071 
4072 void CXXNameMangler::addSubstitution(QualType T) {
4073   if (!hasMangledSubstitutionQualifiers(T)) {
4074     if (const RecordType *RT = T->getAs<RecordType>()) {
4075       addSubstitution(RT->getDecl());
4076       return;
4077     }
4078   }
4079 
4080   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4081   addSubstitution(TypePtr);
4082 }
4083 
4084 void CXXNameMangler::addSubstitution(TemplateName Template) {
4085   if (TemplateDecl *TD = Template.getAsTemplateDecl())
4086     return addSubstitution(TD);
4087 
4088   Template = Context.getASTContext().getCanonicalTemplateName(Template);
4089   addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4090 }
4091 
4092 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4093   assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4094   Substitutions[Ptr] = SeqID++;
4095 }
4096 
4097 //
4098 
4099 /// Mangles the name of the declaration D and emits that name to the given
4100 /// output stream.
4101 ///
4102 /// If the declaration D requires a mangled name, this routine will emit that
4103 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4104 /// and this routine will return false. In this case, the caller should just
4105 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4106 /// name.
4107 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4108                                              raw_ostream &Out) {
4109   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4110           "Invalid mangleName() call, argument is not a variable or function!");
4111   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4112          "Invalid mangleName() call on 'structor decl!");
4113 
4114   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4115                                  getASTContext().getSourceManager(),
4116                                  "Mangling declaration");
4117 
4118   CXXNameMangler Mangler(*this, Out, D);
4119   Mangler.mangle(D);
4120 }
4121 
4122 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4123                                              CXXCtorType Type,
4124                                              raw_ostream &Out) {
4125   CXXNameMangler Mangler(*this, Out, D, Type);
4126   Mangler.mangle(D);
4127 }
4128 
4129 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4130                                              CXXDtorType Type,
4131                                              raw_ostream &Out) {
4132   CXXNameMangler Mangler(*this, Out, D, Type);
4133   Mangler.mangle(D);
4134 }
4135 
4136 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4137                                                    raw_ostream &Out) {
4138   CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4139   Mangler.mangle(D);
4140 }
4141 
4142 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4143                                                    raw_ostream &Out) {
4144   CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4145   Mangler.mangle(D);
4146 }
4147 
4148 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4149                                            const ThunkInfo &Thunk,
4150                                            raw_ostream &Out) {
4151   //  <special-name> ::= T <call-offset> <base encoding>
4152   //                      # base is the nominal target function of thunk
4153   //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4154   //                      # base is the nominal target function of thunk
4155   //                      # first call-offset is 'this' adjustment
4156   //                      # second call-offset is result adjustment
4157 
4158   assert(!isa<CXXDestructorDecl>(MD) &&
4159          "Use mangleCXXDtor for destructor decls!");
4160   CXXNameMangler Mangler(*this, Out);
4161   Mangler.getStream() << "_ZT";
4162   if (!Thunk.Return.isEmpty())
4163     Mangler.getStream() << 'c';
4164 
4165   // Mangle the 'this' pointer adjustment.
4166   Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4167                            Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4168 
4169   // Mangle the return pointer adjustment if there is one.
4170   if (!Thunk.Return.isEmpty())
4171     Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4172                              Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4173 
4174   Mangler.mangleFunctionEncoding(MD);
4175 }
4176 
4177 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4178     const CXXDestructorDecl *DD, CXXDtorType Type,
4179     const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4180   //  <special-name> ::= T <call-offset> <base encoding>
4181   //                      # base is the nominal target function of thunk
4182   CXXNameMangler Mangler(*this, Out, DD, Type);
4183   Mangler.getStream() << "_ZT";
4184 
4185   // Mangle the 'this' pointer adjustment.
4186   Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
4187                            ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4188 
4189   Mangler.mangleFunctionEncoding(DD);
4190 }
4191 
4192 /// Returns the mangled name for a guard variable for the passed in VarDecl.
4193 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4194                                                          raw_ostream &Out) {
4195   //  <special-name> ::= GV <object name>       # Guard variable for one-time
4196   //                                            # initialization
4197   CXXNameMangler Mangler(*this, Out);
4198   Mangler.getStream() << "_ZGV";
4199   Mangler.mangleName(D);
4200 }
4201 
4202 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4203                                                         raw_ostream &Out) {
4204   // These symbols are internal in the Itanium ABI, so the names don't matter.
4205   // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4206   // avoid duplicate symbols.
4207   Out << "__cxx_global_var_init";
4208 }
4209 
4210 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4211                                                              raw_ostream &Out) {
4212   // Prefix the mangling of D with __dtor_.
4213   CXXNameMangler Mangler(*this, Out);
4214   Mangler.getStream() << "__dtor_";
4215   if (shouldMangleDeclName(D))
4216     Mangler.mangle(D);
4217   else
4218     Mangler.getStream() << D->getName();
4219 }
4220 
4221 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4222     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4223   CXXNameMangler Mangler(*this, Out);
4224   Mangler.getStream() << "__filt_";
4225   if (shouldMangleDeclName(EnclosingDecl))
4226     Mangler.mangle(EnclosingDecl);
4227   else
4228     Mangler.getStream() << EnclosingDecl->getName();
4229 }
4230 
4231 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4232     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4233   CXXNameMangler Mangler(*this, Out);
4234   Mangler.getStream() << "__fin_";
4235   if (shouldMangleDeclName(EnclosingDecl))
4236     Mangler.mangle(EnclosingDecl);
4237   else
4238     Mangler.getStream() << EnclosingDecl->getName();
4239 }
4240 
4241 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4242                                                             raw_ostream &Out) {
4243   //  <special-name> ::= TH <object name>
4244   CXXNameMangler Mangler(*this, Out);
4245   Mangler.getStream() << "_ZTH";
4246   Mangler.mangleName(D);
4247 }
4248 
4249 void
4250 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4251                                                           raw_ostream &Out) {
4252   //  <special-name> ::= TW <object name>
4253   CXXNameMangler Mangler(*this, Out);
4254   Mangler.getStream() << "_ZTW";
4255   Mangler.mangleName(D);
4256 }
4257 
4258 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4259                                                         unsigned ManglingNumber,
4260                                                         raw_ostream &Out) {
4261   // We match the GCC mangling here.
4262   //  <special-name> ::= GR <object name>
4263   CXXNameMangler Mangler(*this, Out);
4264   Mangler.getStream() << "_ZGR";
4265   Mangler.mangleName(D);
4266   assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4267   Mangler.mangleSeqID(ManglingNumber - 1);
4268 }
4269 
4270 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4271                                                raw_ostream &Out) {
4272   // <special-name> ::= TV <type>  # virtual table
4273   CXXNameMangler Mangler(*this, Out);
4274   Mangler.getStream() << "_ZTV";
4275   Mangler.mangleNameOrStandardSubstitution(RD);
4276 }
4277 
4278 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4279                                             raw_ostream &Out) {
4280   // <special-name> ::= TT <type>  # VTT structure
4281   CXXNameMangler Mangler(*this, Out);
4282   Mangler.getStream() << "_ZTT";
4283   Mangler.mangleNameOrStandardSubstitution(RD);
4284 }
4285 
4286 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4287                                                    int64_t Offset,
4288                                                    const CXXRecordDecl *Type,
4289                                                    raw_ostream &Out) {
4290   // <special-name> ::= TC <type> <offset number> _ <base type>
4291   CXXNameMangler Mangler(*this, Out);
4292   Mangler.getStream() << "_ZTC";
4293   Mangler.mangleNameOrStandardSubstitution(RD);
4294   Mangler.getStream() << Offset;
4295   Mangler.getStream() << '_';
4296   Mangler.mangleNameOrStandardSubstitution(Type);
4297 }
4298 
4299 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
4300   // <special-name> ::= TI <type>  # typeinfo structure
4301   assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4302   CXXNameMangler Mangler(*this, Out);
4303   Mangler.getStream() << "_ZTI";
4304   Mangler.mangleType(Ty);
4305 }
4306 
4307 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4308                                                  raw_ostream &Out) {
4309   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
4310   CXXNameMangler Mangler(*this, Out);
4311   Mangler.getStream() << "_ZTS";
4312   Mangler.mangleType(Ty);
4313 }
4314 
4315 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4316   mangleCXXRTTIName(Ty, Out);
4317 }
4318 
4319 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4320   llvm_unreachable("Can't mangle string literals");
4321 }
4322 
4323 ItaniumMangleContext *
4324 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4325   return new ItaniumMangleContextImpl(Context, Diags);
4326 }
4327