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