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