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