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