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