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