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