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