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