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