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