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