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