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