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