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