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