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