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