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