clang  20.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"
32 #include "clang/Basic/Module.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Basic/Thunk.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/TargetParser/RISCVTargetParser.h"
40 #include <optional>
41 
42 using namespace clang;
43 
44 namespace {
45 
46 static bool isLocalContainerContext(const DeclContext *DC) {
47  return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
48 }
49 
50 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
51  if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
52  return ftd->getTemplatedDecl();
53 
54  return fn;
55 }
56 
57 static const NamedDecl *getStructor(const NamedDecl *decl) {
58  const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
59  return (fn ? getStructor(fn) : decl);
60 }
61 
62 static bool isLambda(const NamedDecl *ND) {
63  const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
64  if (!Record)
65  return false;
66 
67  return Record->isLambda();
68 }
69 
70 static const unsigned UnknownArity = ~0U;
71 
72 class ItaniumMangleContextImpl : public ItaniumMangleContext {
73  typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
74  llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
75  llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
76  const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
77  NamespaceDecl *StdNamespace = nullptr;
78 
79  bool NeedsUniqueInternalLinkageNames = false;
80 
81 public:
82  explicit ItaniumMangleContextImpl(
83  ASTContext &Context, DiagnosticsEngine &Diags,
84  DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
85  : ItaniumMangleContext(Context, Diags, IsAux),
86  DiscriminatorOverride(DiscriminatorOverride) {}
87 
88  /// @name Mangler Entry Points
89  /// @{
90 
91  bool shouldMangleCXXName(const NamedDecl *D) override;
92  bool shouldMangleStringLiteral(const StringLiteral *) override {
93  return false;
94  }
95 
96  bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
97  void needsUniqueInternalLinkageNames() override {
98  NeedsUniqueInternalLinkageNames = true;
99  }
100 
101  void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
102  void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, bool,
103  raw_ostream &) override;
104  void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
105  const ThunkInfo &Thunk, bool, raw_ostream &) override;
106  void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
107  raw_ostream &) override;
108  void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
109  void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
110  void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
111  const CXXRecordDecl *Type, raw_ostream &) override;
112  void mangleCXXRTTI(QualType T, raw_ostream &) override;
113  void mangleCXXRTTIName(QualType T, raw_ostream &,
114  bool NormalizeIntegers) override;
115  void mangleCanonicalTypeName(QualType T, raw_ostream &,
116  bool NormalizeIntegers) override;
117 
118  void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
119  void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
120  void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
121  void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
122  void mangleDynamicAtExitDestructor(const VarDecl *D,
123  raw_ostream &Out) override;
124  void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
125  void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
126  raw_ostream &Out) override;
127  void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
128  raw_ostream &Out) override;
129  void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
130  void mangleItaniumThreadLocalWrapper(const VarDecl *D,
131  raw_ostream &) override;
132 
133  void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
134 
135  void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
136 
137  void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
138 
139  bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
140  // Lambda closure types are already numbered.
141  if (isLambda(ND))
142  return false;
143 
144  // Anonymous tags are already numbered.
145  if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
146  if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
147  return false;
148  }
149 
150  // Use the canonical number for externally visible decls.
151  if (ND->isExternallyVisible()) {
152  unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
153  if (discriminator == 1)
154  return false;
155  disc = discriminator - 2;
156  return true;
157  }
158 
159  // Make up a reasonable number for internal decls.
160  unsigned &discriminator = Uniquifier[ND];
161  if (!discriminator) {
162  const DeclContext *DC = getEffectiveDeclContext(ND);
163  discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
164  }
165  if (discriminator == 1)
166  return false;
167  disc = discriminator-2;
168  return true;
169  }
170 
171  std::string getLambdaString(const CXXRecordDecl *Lambda) override {
172  // This function matches the one in MicrosoftMangle, which returns
173  // the string that is used in lambda mangled names.
174  assert(Lambda->isLambda() && "RD must be a lambda!");
175  std::string Name("<lambda");
176  Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
177  unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
178  unsigned LambdaId;
179  const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
180  const FunctionDecl *Func =
181  Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
182 
183  if (Func) {
184  unsigned DefaultArgNo =
185  Func->getNumParams() - Parm->getFunctionScopeIndex();
186  Name += llvm::utostr(DefaultArgNo);
187  Name += "_";
188  }
189 
190  if (LambdaManglingNumber)
191  LambdaId = LambdaManglingNumber;
192  else
193  LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
194 
195  Name += llvm::utostr(LambdaId);
196  Name += '>';
197  return Name;
198  }
199 
200  DiscriminatorOverrideTy getDiscriminatorOverride() const override {
201  return DiscriminatorOverride;
202  }
203 
204  NamespaceDecl *getStdNamespace();
205 
206  const DeclContext *getEffectiveDeclContext(const Decl *D);
207  const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
208  return getEffectiveDeclContext(cast<Decl>(DC));
209  }
210 
211  bool isInternalLinkageDecl(const NamedDecl *ND);
212 
213  /// @}
214 };
215 
216 /// Manage the mangling of a single name.
217 class CXXNameMangler {
218  ItaniumMangleContextImpl &Context;
219  raw_ostream &Out;
220  /// Normalize integer types for cross-language CFI support with other
221  /// languages that can't represent and encode C/C++ integer types.
222  bool NormalizeIntegers = false;
223 
224  bool NullOut = false;
225  /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
226  /// This mode is used when mangler creates another mangler recursively to
227  /// calculate ABI tags for the function return value or the variable type.
228  /// Also it is required to avoid infinite recursion in some cases.
229  bool DisableDerivedAbiTags = false;
230 
231  /// The "structor" is the top-level declaration being mangled, if
232  /// that's not a template specialization; otherwise it's the pattern
233  /// for that specialization.
234  const NamedDecl *Structor;
235  unsigned StructorType = 0;
236 
237  // An offset to add to all template parameter depths while mangling. Used
238  // when mangling a template parameter list to see if it matches a template
239  // template parameter exactly.
240  unsigned TemplateDepthOffset = 0;
241 
242  /// The next substitution sequence number.
243  unsigned SeqID = 0;
244 
245  class FunctionTypeDepthState {
246  unsigned Bits = 0;
247 
248  enum { InResultTypeMask = 1 };
249 
250  public:
251  FunctionTypeDepthState() = default;
252 
253  /// The number of function types we're inside.
254  unsigned getDepth() const {
255  return Bits >> 1;
256  }
257 
258  /// True if we're in the return type of the innermost function type.
259  bool isInResultType() const {
260  return Bits & InResultTypeMask;
261  }
262 
263  FunctionTypeDepthState push() {
264  FunctionTypeDepthState tmp = *this;
265  Bits = (Bits & ~InResultTypeMask) + 2;
266  return tmp;
267  }
268 
269  void enterResultType() {
270  Bits |= InResultTypeMask;
271  }
272 
273  void leaveResultType() {
274  Bits &= ~InResultTypeMask;
275  }
276 
277  void pop(FunctionTypeDepthState saved) {
278  assert(getDepth() == saved.getDepth() + 1);
279  Bits = saved.Bits;
280  }
281 
282  } FunctionTypeDepth;
283 
284  // abi_tag is a gcc attribute, taking one or more strings called "tags".
285  // The goal is to annotate against which version of a library an object was
286  // built and to be able to provide backwards compatibility ("dual abi").
287  // For more information see docs/ItaniumMangleAbiTags.rst.
288  typedef SmallVector<StringRef, 4> AbiTagList;
289 
290  // State to gather all implicit and explicit tags used in a mangled name.
291  // Must always have an instance of this while emitting any name to keep
292  // track.
293  class AbiTagState final {
294  public:
295  explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
296  Parent = LinkHead;
297  LinkHead = this;
298  }
299 
300  // No copy, no move.
301  AbiTagState(const AbiTagState &) = delete;
302  AbiTagState &operator=(const AbiTagState &) = delete;
303 
304  ~AbiTagState() { pop(); }
305 
306  void write(raw_ostream &Out, const NamedDecl *ND,
307  const AbiTagList *AdditionalAbiTags) {
308  ND = cast<NamedDecl>(ND->getCanonicalDecl());
309  if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
310  assert(
311  !AdditionalAbiTags &&
312  "only function and variables need a list of additional abi tags");
313  if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
314  if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
315  UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
316  AbiTag->tags().end());
317  }
318  // Don't emit abi tags for namespaces.
319  return;
320  }
321  }
322 
323  AbiTagList TagList;
324  if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
325  UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
326  AbiTag->tags().end());
327  TagList.insert(TagList.end(), AbiTag->tags().begin(),
328  AbiTag->tags().end());
329  }
330 
331  if (AdditionalAbiTags) {
332  UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
333  AdditionalAbiTags->end());
334  TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
335  AdditionalAbiTags->end());
336  }
337 
338  llvm::sort(TagList);
339  TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
340 
341  writeSortedUniqueAbiTags(Out, TagList);
342  }
343 
344  const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
345  void setUsedAbiTags(const AbiTagList &AbiTags) {
346  UsedAbiTags = AbiTags;
347  }
348 
349  const AbiTagList &getEmittedAbiTags() const {
350  return EmittedAbiTags;
351  }
352 
353  const AbiTagList &getSortedUniqueUsedAbiTags() {
354  llvm::sort(UsedAbiTags);
355  UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
356  UsedAbiTags.end());
357  return UsedAbiTags;
358  }
359 
360  private:
361  //! All abi tags used implicitly or explicitly.
362  AbiTagList UsedAbiTags;
363  //! All explicit abi tags (i.e. not from namespace).
364  AbiTagList EmittedAbiTags;
365 
366  AbiTagState *&LinkHead;
367  AbiTagState *Parent = nullptr;
368 
369  void pop() {
370  assert(LinkHead == this &&
371  "abi tag link head must point to us on destruction");
372  if (Parent) {
373  Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
374  UsedAbiTags.begin(), UsedAbiTags.end());
375  Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
376  EmittedAbiTags.begin(),
377  EmittedAbiTags.end());
378  }
379  LinkHead = Parent;
380  }
381 
382  void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
383  for (const auto &Tag : AbiTags) {
384  EmittedAbiTags.push_back(Tag);
385  Out << "B";
386  Out << Tag.size();
387  Out << Tag;
388  }
389  }
390  };
391 
392  AbiTagState *AbiTags = nullptr;
393  AbiTagState AbiTagsRoot;
394 
395  llvm::DenseMap<uintptr_t, unsigned> Substitutions;
396  llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
397 
398  ASTContext &getASTContext() const { return Context.getASTContext(); }
399 
400  bool isCompatibleWith(LangOptions::ClangABI Ver) {
401  return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver;
402  }
403 
404  bool isStd(const NamespaceDecl *NS);
405  bool isStdNamespace(const DeclContext *DC);
406 
407  const RecordDecl *GetLocalClassDecl(const Decl *D);
408  bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
409  bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
410  llvm::StringRef Name, bool HasAllocator);
411 
412 public:
413  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
414  const NamedDecl *D = nullptr, bool NullOut_ = false)
415  : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
416  AbiTagsRoot(AbiTags) {
417  // These can't be mangled without a ctor type or dtor type.
418  assert(!D || (!isa<CXXDestructorDecl>(D) &&
419  !isa<CXXConstructorDecl>(D)));
420  }
421  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
423  : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
424  AbiTagsRoot(AbiTags) {}
425  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
427  : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
428  AbiTagsRoot(AbiTags) {}
429 
430  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
431  bool NormalizeIntegers_)
432  : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),
433  NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}
434  CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
435  : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
436  StructorType(Outer.StructorType), SeqID(Outer.SeqID),
437  FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
438  Substitutions(Outer.Substitutions),
439  ModuleSubstitutions(Outer.ModuleSubstitutions) {}
440 
441  CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
442  : CXXNameMangler(Outer, (raw_ostream &)Out_) {
443  NullOut = true;
444  }
445 
446  struct WithTemplateDepthOffset { unsigned Offset; };
447  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out,
448  WithTemplateDepthOffset Offset)
449  : CXXNameMangler(C, Out) {
450  TemplateDepthOffset = Offset.Offset;
451  }
452 
453  raw_ostream &getStream() { return Out; }
454 
455  void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
456  static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
457 
458  void mangle(GlobalDecl GD);
459  void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
460  void mangleNumber(const llvm::APSInt &I);
461  void mangleNumber(int64_t Number);
462  void mangleFloat(const llvm::APFloat &F);
463  void mangleFunctionEncoding(GlobalDecl GD);
464  void mangleSeqID(unsigned SeqID);
465  void mangleName(GlobalDecl GD);
466  void mangleType(QualType T);
467  void mangleNameOrStandardSubstitution(const NamedDecl *ND);
468  void mangleLambdaSig(const CXXRecordDecl *Lambda);
469  void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
470  void mangleVendorQualifier(StringRef Name);
471 
472 private:
473 
474  bool mangleSubstitution(const NamedDecl *ND);
475  bool mangleSubstitution(NestedNameSpecifier *NNS);
476  bool mangleSubstitution(QualType T);
477  bool mangleSubstitution(TemplateName Template);
478  bool mangleSubstitution(uintptr_t Ptr);
479 
480  void mangleExistingSubstitution(TemplateName name);
481 
482  bool mangleStandardSubstitution(const NamedDecl *ND);
483 
484  void addSubstitution(const NamedDecl *ND) {
485  ND = cast<NamedDecl>(ND->getCanonicalDecl());
486 
487  addSubstitution(reinterpret_cast<uintptr_t>(ND));
488  }
489  void addSubstitution(NestedNameSpecifier *NNS) {
490  NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
491 
492  addSubstitution(reinterpret_cast<uintptr_t>(NNS));
493  }
494  void addSubstitution(QualType T);
495  void addSubstitution(TemplateName Template);
496  void addSubstitution(uintptr_t Ptr);
497  // Destructive copy substitutions from other mangler.
498  void extendSubstitutions(CXXNameMangler* Other);
499 
500  void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
501  bool recursive = false);
502  void mangleUnresolvedName(NestedNameSpecifier *qualifier,
504  const TemplateArgumentLoc *TemplateArgs,
505  unsigned NumTemplateArgs,
506  unsigned KnownArity = UnknownArity);
507 
508  void mangleFunctionEncodingBareType(const FunctionDecl *FD);
509 
510  void mangleNameWithAbiTags(GlobalDecl GD,
511  const AbiTagList *AdditionalAbiTags);
512  void mangleModuleName(const NamedDecl *ND);
513  void mangleTemplateName(const TemplateDecl *TD,
515  void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
516  const AbiTagList *AdditionalAbiTags) {
517  mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
518  UnknownArity, AdditionalAbiTags);
519  }
520  void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
521  const DeclContext *DC, unsigned KnownArity,
522  const AbiTagList *AdditionalAbiTags);
523  void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
524  const AbiTagList *AdditionalAbiTags);
525  void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
526  const AbiTagList *AdditionalAbiTags);
527  void mangleSourceName(const IdentifierInfo *II);
528  void mangleRegCallName(const IdentifierInfo *II);
529  void mangleDeviceStubName(const IdentifierInfo *II);
530  void mangleSourceNameWithAbiTags(
531  const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
532  void mangleLocalName(GlobalDecl GD,
533  const AbiTagList *AdditionalAbiTags);
534  void mangleBlockForPrefix(const BlockDecl *Block);
535  void mangleUnqualifiedBlock(const BlockDecl *Block);
536  void mangleTemplateParamDecl(const NamedDecl *Decl);
537  void mangleTemplateParameterList(const TemplateParameterList *Params);
538  void mangleTypeConstraint(const ConceptDecl *Concept,
539  ArrayRef<TemplateArgument> Arguments);
540  void mangleTypeConstraint(const TypeConstraint *Constraint);
541  void mangleRequiresClause(const Expr *RequiresClause);
542  void mangleLambda(const CXXRecordDecl *Lambda);
543  void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
544  const AbiTagList *AdditionalAbiTags,
545  bool NoFunction=false);
546  void mangleNestedName(const TemplateDecl *TD,
548  void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
549  const NamedDecl *PrefixND,
550  const AbiTagList *AdditionalAbiTags);
551  void manglePrefix(NestedNameSpecifier *qualifier);
552  void manglePrefix(const DeclContext *DC, bool NoFunction=false);
553  void manglePrefix(QualType type);
554  void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
555  void mangleTemplatePrefix(TemplateName Template);
556  const NamedDecl *getClosurePrefix(const Decl *ND);
557  void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
558  bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
559  StringRef Prefix = "");
560  void mangleOperatorName(DeclarationName Name, unsigned Arity);
561  void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
562  void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
563  void mangleRefQualifier(RefQualifierKind RefQualifier);
564 
565  void mangleObjCMethodName(const ObjCMethodDecl *MD);
566 
567  // Declare manglers for every type class.
568 #define ABSTRACT_TYPE(CLASS, PARENT)
569 #define NON_CANONICAL_TYPE(CLASS, PARENT)
570 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
571 #include "clang/AST/TypeNodes.inc"
572 
573  void mangleType(const TagType*);
574  void mangleType(TemplateName);
575  static StringRef getCallingConvQualifierName(CallingConv CC);
576  void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
577  void mangleExtFunctionInfo(const FunctionType *T);
578  void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
579  const FunctionDecl *FD = nullptr);
580  void mangleNeonVectorType(const VectorType *T);
581  void mangleNeonVectorType(const DependentVectorType *T);
582  void mangleAArch64NeonVectorType(const VectorType *T);
583  void mangleAArch64NeonVectorType(const DependentVectorType *T);
584  void mangleAArch64FixedSveVectorType(const VectorType *T);
585  void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
586  void mangleRISCVFixedRVVVectorType(const VectorType *T);
587  void mangleRISCVFixedRVVVectorType(const DependentVectorType *T);
588 
589  void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
590  void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
591  void mangleFixedPointLiteral();
592  void mangleNullPointer(QualType T);
593 
594  void mangleMemberExprBase(const Expr *base, bool isArrow);
595  void mangleMemberExpr(const Expr *base, bool isArrow,
596  NestedNameSpecifier *qualifier,
597  NamedDecl *firstQualifierLookup,
599  const TemplateArgumentLoc *TemplateArgs,
600  unsigned NumTemplateArgs,
601  unsigned knownArity);
602  void mangleCastExpression(const Expr *E, StringRef CastEncoding);
603  void mangleInitListElements(const InitListExpr *InitList);
604  void mangleRequirement(SourceLocation RequiresExprLoc,
605  const concepts::Requirement *Req);
606  void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
607  bool AsTemplateArg = false);
608  void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
609  void mangleCXXDtorType(CXXDtorType T);
610 
611  struct TemplateArgManglingInfo;
612  void mangleTemplateArgs(TemplateName TN,
613  const TemplateArgumentLoc *TemplateArgs,
614  unsigned NumTemplateArgs);
615  void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);
616  void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
617  void mangleTemplateArg(TemplateArgManglingInfo &Info, unsigned Index,
618  TemplateArgument A);
619  void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
620  void mangleTemplateArgExpr(const Expr *E);
621  void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
622  bool NeedExactType = false);
623 
624  void mangleTemplateParameter(unsigned Depth, unsigned Index);
625 
626  void mangleFunctionParam(const ParmVarDecl *parm);
627 
628  void writeAbiTags(const NamedDecl *ND,
629  const AbiTagList *AdditionalAbiTags);
630 
631  // Returns sorted unique list of ABI tags.
632  AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
633  // Returns sorted unique list of ABI tags.
634  AbiTagList makeVariableTypeTags(const VarDecl *VD);
635 };
636 
637 }
638 
639 NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
640  if (!StdNamespace) {
641  StdNamespace = NamespaceDecl::Create(
642  getASTContext(), getASTContext().getTranslationUnitDecl(),
643  /*Inline=*/false, SourceLocation(), SourceLocation(),
644  &getASTContext().Idents.get("std"),
645  /*PrevDecl=*/nullptr, /*Nested=*/false);
646  StdNamespace->setImplicit();
647  }
648  return StdNamespace;
649 }
650 
651 /// Retrieve the declaration context that should be used when mangling the given
652 /// declaration.
653 const DeclContext *
654 ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
655  // The ABI assumes that lambda closure types that occur within
656  // default arguments live in the context of the function. However, due to
657  // the way in which Clang parses and creates function declarations, this is
658  // not the case: the lambda closure type ends up living in the context
659  // where the function itself resides, because the function declaration itself
660  // had not yet been created. Fix the context here.
661  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
662  if (RD->isLambda())
663  if (ParmVarDecl *ContextParam =
664  dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
665  return ContextParam->getDeclContext();
666  }
667 
668  // Perform the same check for block literals.
669  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
670  if (ParmVarDecl *ContextParam =
671  dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
672  return ContextParam->getDeclContext();
673  }
674 
675  // On ARM and AArch64, the va_list tag is always mangled as if in the std
676  // namespace. We do not represent va_list as actually being in the std
677  // namespace in C because this would result in incorrect debug info in C,
678  // among other things. It is important for both languages to have the same
679  // mangling in order for -fsanitize=cfi-icall to work.
680  if (D == getASTContext().getVaListTagDecl()) {
681  const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
682  if (T.isARM() || T.isThumb() || T.isAArch64())
683  return getStdNamespace();
684  }
685 
686  const DeclContext *DC = D->getDeclContext();
687  if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
688  isa<OMPDeclareMapperDecl>(DC)) {
689  return getEffectiveDeclContext(cast<Decl>(DC));
690  }
691 
692  if (const auto *VD = dyn_cast<VarDecl>(D))
693  if (VD->isExternC())
694  return getASTContext().getTranslationUnitDecl();
695 
696  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
697  if (FD->isExternC())
698  return getASTContext().getTranslationUnitDecl();
699  // Member-like constrained friends are mangled as if they were members of
700  // the enclosing class.
701  if (FD->isMemberLikeConstrainedFriend() &&
702  getASTContext().getLangOpts().getClangABICompat() >
705  }
706 
707  return DC->getRedeclContext();
708 }
709 
710 bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
711  if (ND && ND->getFormalLinkage() == Linkage::Internal &&
712  !ND->isExternallyVisible() &&
713  getEffectiveDeclContext(ND)->isFileContext() &&
714  !ND->isInAnonymousNamespace())
715  return true;
716  return false;
717 }
718 
719 // Check if this Function Decl needs a unique internal linkage name.
721  const NamedDecl *ND) {
722  if (!NeedsUniqueInternalLinkageNames || !ND)
723  return false;
724 
725  const auto *FD = dyn_cast<FunctionDecl>(ND);
726  if (!FD)
727  return false;
728 
729  // For C functions without prototypes, return false as their
730  // names should not be mangled.
731  if (!FD->getType()->getAs<FunctionProtoType>())
732  return false;
733 
734  if (isInternalLinkageDecl(ND))
735  return true;
736 
737  return false;
738 }
739 
740 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
741  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
742  LanguageLinkage L = FD->getLanguageLinkage();
743  // Overloadable functions need mangling.
744  if (FD->hasAttr<OverloadableAttr>())
745  return true;
746 
747  // "main" is not mangled.
748  if (FD->isMain())
749  return false;
750 
751  // The Windows ABI expects that we would never mangle "typical"
752  // user-defined entry points regardless of visibility or freestanding-ness.
753  //
754  // N.B. This is distinct from asking about "main". "main" has a lot of
755  // special rules associated with it in the standard while these
756  // user-defined entry points are outside of the purview of the standard.
757  // For example, there can be only one definition for "main" in a standards
758  // compliant program; however nothing forbids the existence of wmain and
759  // WinMain in the same translation unit.
760  if (FD->isMSVCRTEntryPoint())
761  return false;
762 
763  // C++ functions and those whose names are not a simple identifier need
764  // mangling.
765  if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
766  return true;
767 
768  // C functions are not mangled.
769  if (L == CLanguageLinkage)
770  return false;
771  }
772 
773  // Otherwise, no mangling is done outside C++ mode.
774  if (!getASTContext().getLangOpts().CPlusPlus)
775  return false;
776 
777  if (const auto *VD = dyn_cast<VarDecl>(D)) {
778  // Decompositions are mangled.
779  if (isa<DecompositionDecl>(VD))
780  return true;
781 
782  // C variables are not mangled.
783  if (VD->isExternC())
784  return false;
785 
786  // Variables at global scope are not mangled unless they have internal
787  // linkage or are specializations or are attached to a named module.
788  const DeclContext *DC = getEffectiveDeclContext(D);
789  // Check for extern variable declared locally.
790  if (DC->isFunctionOrMethod() && D->hasLinkage())
791  while (!DC->isFileContext())
792  DC = getEffectiveParentContext(DC);
793  if (DC->isTranslationUnit() && D->getFormalLinkage() != Linkage::Internal &&
794  !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
795  !isa<VarTemplateSpecializationDecl>(VD) &&
796  !VD->getOwningModuleForLinkage())
797  return false;
798  }
799 
800  return true;
801 }
802 
803 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
804  const AbiTagList *AdditionalAbiTags) {
805  assert(AbiTags && "require AbiTagState");
806  AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
807 }
808 
809 void CXXNameMangler::mangleSourceNameWithAbiTags(
810  const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
811  mangleSourceName(ND->getIdentifier());
812  writeAbiTags(ND, AdditionalAbiTags);
813 }
814 
815 void CXXNameMangler::mangle(GlobalDecl GD) {
816  // <mangled-name> ::= _Z <encoding>
817  // ::= <data name>
818  // ::= <special-name>
819  Out << "_Z";
820  if (isa<FunctionDecl>(GD.getDecl()))
821  mangleFunctionEncoding(GD);
823  BindingDecl>(GD.getDecl()))
824  mangleName(GD);
825  else if (const IndirectFieldDecl *IFD =
826  dyn_cast<IndirectFieldDecl>(GD.getDecl()))
827  mangleName(IFD->getAnonField());
828  else
829  llvm_unreachable("unexpected kind of global decl");
830 }
831 
832 void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
833  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
834  // <encoding> ::= <function name> <bare-function-type>
835 
836  // Don't mangle in the type if this isn't a decl we should typically mangle.
837  if (!Context.shouldMangleDeclName(FD)) {
838  mangleName(GD);
839  return;
840  }
841 
842  AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
843  if (ReturnTypeAbiTags.empty()) {
844  // There are no tags for return type, the simplest case. Enter the function
845  // parameter scope before mangling the name, because a template using
846  // constrained `auto` can have references to its parameters within its
847  // template argument list:
848  //
849  // template<typename T> void f(T x, C<decltype(x)> auto)
850  // ... is mangled as ...
851  // template<typename T, C<decltype(param 1)> U> void f(T, U)
852  FunctionTypeDepthState Saved = FunctionTypeDepth.push();
853  mangleName(GD);
854  FunctionTypeDepth.pop(Saved);
855  mangleFunctionEncodingBareType(FD);
856  return;
857  }
858 
859  // Mangle function name and encoding to temporary buffer.
860  // We have to output name and encoding to the same mangler to get the same
861  // substitution as it will be in final mangling.
862  SmallString<256> FunctionEncodingBuf;
863  llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
864  CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
865  // Output name of the function.
866  FunctionEncodingMangler.disableDerivedAbiTags();
867 
868  FunctionTypeDepthState Saved = FunctionTypeDepth.push();
869  FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
870  FunctionTypeDepth.pop(Saved);
871 
872  // Remember length of the function name in the buffer.
873  size_t EncodingPositionStart = FunctionEncodingStream.str().size();
874  FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
875 
876  // Get tags from return type that are not present in function name or
877  // encoding.
878  const AbiTagList &UsedAbiTags =
879  FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
880  AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
881  AdditionalAbiTags.erase(
882  std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
883  UsedAbiTags.begin(), UsedAbiTags.end(),
884  AdditionalAbiTags.begin()),
885  AdditionalAbiTags.end());
886 
887  // Output name with implicit tags and function encoding from temporary buffer.
888  Saved = FunctionTypeDepth.push();
889  mangleNameWithAbiTags(FD, &AdditionalAbiTags);
890  FunctionTypeDepth.pop(Saved);
891  Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
892 
893  // Function encoding could create new substitutions so we have to add
894  // temp mangled substitutions to main mangler.
895  extendSubstitutions(&FunctionEncodingMangler);
896 }
897 
898 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
899  if (FD->hasAttr<EnableIfAttr>()) {
900  FunctionTypeDepthState Saved = FunctionTypeDepth.push();
901  Out << "Ua9enable_ifI";
902  for (AttrVec::const_iterator I = FD->getAttrs().begin(),
903  E = FD->getAttrs().end();
904  I != E; ++I) {
905  EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
906  if (!EIA)
907  continue;
908  if (isCompatibleWith(LangOptions::ClangABI::Ver11)) {
909  // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
910  // even though <template-arg> should not include an X/E around
911  // <expr-primary>.
912  Out << 'X';
913  mangleExpression(EIA->getCond());
914  Out << 'E';
915  } else {
916  mangleTemplateArgExpr(EIA->getCond());
917  }
918  }
919  Out << 'E';
920  FunctionTypeDepth.pop(Saved);
921  }
922 
923  // When mangling an inheriting constructor, the bare function type used is
924  // that of the inherited constructor.
925  if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
926  if (auto Inherited = CD->getInheritedConstructor())
927  FD = Inherited.getConstructor();
928 
929  // Whether the mangling of a function type includes the return type depends on
930  // the context and the nature of the function. The rules for deciding whether
931  // the return type is included are:
932  //
933  // 1. Template functions (names or types) have return types encoded, with
934  // the exceptions listed below.
935  // 2. Function types not appearing as part of a function name mangling,
936  // e.g. parameters, pointer types, etc., have return type encoded, with the
937  // exceptions listed below.
938  // 3. Non-template function names do not have return types encoded.
939  //
940  // The exceptions mentioned in (1) and (2) above, for which the return type is
941  // never included, are
942  // 1. Constructors.
943  // 2. Destructors.
944  // 3. Conversion operator functions, e.g. operator int.
945  bool MangleReturnType = false;
946  if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
947  if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
948  isa<CXXConversionDecl>(FD)))
949  MangleReturnType = true;
950 
951  // Mangle the type of the primary template.
952  FD = PrimaryTemplate->getTemplatedDecl();
953  }
954 
955  mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
956  MangleReturnType, FD);
957 }
958 
959 /// Return whether a given namespace is the 'std' namespace.
960 bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
961  if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
962  return false;
963 
964  const IdentifierInfo *II = NS->getFirstDecl()->getIdentifier();
965  return II && II->isStr("std");
966 }
967 
968 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
969 // namespace.
970 bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
971  if (!DC->isNamespace())
972  return false;
973 
974  return isStd(cast<NamespaceDecl>(DC));
975 }
976 
977 static const GlobalDecl
978 isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
979  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
980  // Check if we have a function template.
981  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
982  if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
983  TemplateArgs = FD->getTemplateSpecializationArgs();
984  return GD.getWithDecl(TD);
985  }
986  }
987 
988  // Check if we have a class template.
989  if (const ClassTemplateSpecializationDecl *Spec =
990  dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
991  TemplateArgs = &Spec->getTemplateArgs();
992  return GD.getWithDecl(Spec->getSpecializedTemplate());
993  }
994 
995  // Check if we have a variable template.
996  if (const VarTemplateSpecializationDecl *Spec =
997  dyn_cast<VarTemplateSpecializationDecl>(ND)) {
998  TemplateArgs = &Spec->getTemplateArgs();
999  return GD.getWithDecl(Spec->getSpecializedTemplate());
1000  }
1001 
1002  return GlobalDecl();
1003 }
1004 
1006  const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
1007  return TemplateName(const_cast<TemplateDecl*>(TD));
1008 }
1009 
1010 void CXXNameMangler::mangleName(GlobalDecl GD) {
1011  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1012  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1013  // Variables should have implicit tags from its type.
1014  AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
1015  if (VariableTypeAbiTags.empty()) {
1016  // Simple case no variable type tags.
1017  mangleNameWithAbiTags(VD, nullptr);
1018  return;
1019  }
1020 
1021  // Mangle variable name to null stream to collect tags.
1022  llvm::raw_null_ostream NullOutStream;
1023  CXXNameMangler VariableNameMangler(*this, NullOutStream);
1024  VariableNameMangler.disableDerivedAbiTags();
1025  VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
1026 
1027  // Get tags from variable type that are not present in its name.
1028  const AbiTagList &UsedAbiTags =
1029  VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
1030  AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
1031  AdditionalAbiTags.erase(
1032  std::set_difference(VariableTypeAbiTags.begin(),
1033  VariableTypeAbiTags.end(), UsedAbiTags.begin(),
1034  UsedAbiTags.end(), AdditionalAbiTags.begin()),
1035  AdditionalAbiTags.end());
1036 
1037  // Output name with implicit tags.
1038  mangleNameWithAbiTags(VD, &AdditionalAbiTags);
1039  } else {
1040  mangleNameWithAbiTags(GD, nullptr);
1041  }
1042 }
1043 
1044 const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
1045  const DeclContext *DC = Context.getEffectiveDeclContext(D);
1046  while (!DC->isNamespace() && !DC->isTranslationUnit()) {
1047  if (isLocalContainerContext(DC))
1048  return dyn_cast<RecordDecl>(D);
1049  D = cast<Decl>(DC);
1050  DC = Context.getEffectiveDeclContext(D);
1051  }
1052  return nullptr;
1053 }
1054 
1055 void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
1056  const AbiTagList *AdditionalAbiTags) {
1057  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1058  // <name> ::= [<module-name>] <nested-name>
1059  // ::= [<module-name>] <unscoped-name>
1060  // ::= [<module-name>] <unscoped-template-name> <template-args>
1061  // ::= <local-name>
1062  //
1063  const DeclContext *DC = Context.getEffectiveDeclContext(ND);
1064  bool IsLambda = isLambda(ND);
1065 
1066  // If this is an extern variable declared locally, the relevant DeclContext
1067  // is that of the containing namespace, or the translation unit.
1068  // FIXME: This is a hack; extern variables declared locally should have
1069  // a proper semantic declaration context!
1070  if (isLocalContainerContext(DC) && ND->hasLinkage() && !IsLambda)
1071  while (!DC->isNamespace() && !DC->isTranslationUnit())
1072  DC = Context.getEffectiveParentContext(DC);
1073  else if (GetLocalClassDecl(ND) &&
1074  (!IsLambda || isCompatibleWith(LangOptions::ClangABI::Ver18))) {
1075  mangleLocalName(GD, AdditionalAbiTags);
1076  return;
1077  }
1078 
1079  assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");
1080 
1081  // Closures can require a nested-name mangling even if they're semantically
1082  // in the global namespace.
1083  if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
1084  mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
1085  return;
1086  }
1087 
1088  if (isLocalContainerContext(DC)) {
1089  mangleLocalName(GD, AdditionalAbiTags);
1090  return;
1091  }
1092 
1093  if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1094  // Check if we have a template.
1095  const TemplateArgumentList *TemplateArgs = nullptr;
1096  if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1097  mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
1098  mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1099  return;
1100  }
1101 
1102  mangleUnscopedName(GD, DC, AdditionalAbiTags);
1103  return;
1104  }
1105 
1106  mangleNestedName(GD, DC, AdditionalAbiTags);
1107 }
1108 
1109 void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
1110  if (ND->isExternallyVisible())
1111  if (Module *M = ND->getOwningModuleForLinkage())
1112  mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
1113 }
1114 
1115 // <module-name> ::= <module-subname>
1116 // ::= <module-name> <module-subname>
1117 // ::= <substitution>
1118 // <module-subname> ::= W <source-name>
1119 // ::= W P <source-name>
1120 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
1121  // <substitution> ::= S <seq-id> _
1122  auto It = ModuleSubstitutions.find(Name);
1123  if (It != ModuleSubstitutions.end()) {
1124  Out << 'S';
1125  mangleSeqID(It->second);
1126  return;
1127  }
1128 
1129  // FIXME: Preserve hierarchy in module names rather than flattening
1130  // them to strings; use Module*s as substitution keys.
1131  auto Parts = Name.rsplit('.');
1132  if (Parts.second.empty())
1133  Parts.second = Parts.first;
1134  else {
1135  mangleModuleNamePrefix(Parts.first, IsPartition);
1136  IsPartition = false;
1137  }
1138 
1139  Out << 'W';
1140  if (IsPartition)
1141  Out << 'P';
1142  Out << Parts.second.size() << Parts.second;
1143  ModuleSubstitutions.insert({Name, SeqID++});
1144 }
1145 
1146 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
1148  const DeclContext *DC = Context.getEffectiveDeclContext(TD);
1149 
1150  if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1151  mangleUnscopedTemplateName(TD, DC, nullptr);
1152  mangleTemplateArgs(asTemplateName(TD), Args);
1153  } else {
1154  mangleNestedName(TD, Args);
1155  }
1156 }
1157 
1158 void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
1159  const AbiTagList *AdditionalAbiTags) {
1160  // <unscoped-name> ::= <unqualified-name>
1161  // ::= St <unqualified-name> # ::std::
1162 
1163  assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");
1164  if (isStdNamespace(DC))
1165  Out << "St";
1166 
1167  mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1168 }
1169 
1170 void CXXNameMangler::mangleUnscopedTemplateName(
1171  GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
1172  const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
1173  // <unscoped-template-name> ::= <unscoped-name>
1174  // ::= <substitution>
1175  if (mangleSubstitution(ND))
1176  return;
1177 
1178  // <template-template-param> ::= <template-param>
1179  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1180  assert(!AdditionalAbiTags &&
1181  "template template param cannot have abi tags");
1182  mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1183  } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
1184  mangleUnscopedName(GD, DC, AdditionalAbiTags);
1185  } else {
1186  mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
1187  AdditionalAbiTags);
1188  }
1189 
1190  addSubstitution(ND);
1191 }
1192 
1193 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1194  // ABI:
1195  // Floating-point literals are encoded using a fixed-length
1196  // lowercase hexadecimal string corresponding to the internal
1197  // representation (IEEE on Itanium), high-order bytes first,
1198  // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1199  // on Itanium.
1200  // The 'without leading zeroes' thing seems to be an editorial
1201  // mistake; see the discussion on cxx-abi-dev beginning on
1202  // 2012-01-16.
1203 
1204  // Our requirements here are just barely weird enough to justify
1205  // using a custom algorithm instead of post-processing APInt::toString().
1206 
1207  llvm::APInt valueBits = f.bitcastToAPInt();
1208  unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1209  assert(numCharacters != 0);
1210 
1211  // Allocate a buffer of the right number of characters.
1212  SmallVector<char, 20> buffer(numCharacters);
1213 
1214  // Fill the buffer left-to-right.
1215  for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1216  // The bit-index of the next hex digit.
1217  unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1218 
1219  // Project out 4 bits starting at 'digitIndex'.
1220  uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1221  hexDigit >>= (digitBitIndex % 64);
1222  hexDigit &= 0xF;
1223 
1224  // Map that over to a lowercase hex digit.
1225  static const char charForHex[16] = {
1226  '0', '1', '2', '3', '4', '5', '6', '7',
1227  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1228  };
1229  buffer[stringIndex] = charForHex[hexDigit];
1230  }
1231 
1232  Out.write(buffer.data(), numCharacters);
1233 }
1234 
1235 void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1236  Out << 'L';
1237  mangleType(T);
1238  mangleFloat(V);
1239  Out << 'E';
1240 }
1241 
1242 void CXXNameMangler::mangleFixedPointLiteral() {
1243  DiagnosticsEngine &Diags = Context.getDiags();
1244  unsigned DiagID = Diags.getCustomDiagID(
1245  DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1246  Diags.Report(DiagID);
1247 }
1248 
1249 void CXXNameMangler::mangleNullPointer(QualType T) {
1250  // <expr-primary> ::= L <type> 0 E
1251  Out << 'L';
1252  mangleType(T);
1253  Out << "0E";
1254 }
1255 
1256 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1257  if (Value.isSigned() && Value.isNegative()) {
1258  Out << 'n';
1259  Value.abs().print(Out, /*signed*/ false);
1260  } else {
1261  Value.print(Out, /*signed*/ false);
1262  }
1263 }
1264 
1265 void CXXNameMangler::mangleNumber(int64_t Number) {
1266  // <number> ::= [n] <non-negative decimal integer>
1267  if (Number < 0) {
1268  Out << 'n';
1269  Number = -Number;
1270  }
1271 
1272  Out << Number;
1273 }
1274 
1275 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1276  // <call-offset> ::= h <nv-offset> _
1277  // ::= v <v-offset> _
1278  // <nv-offset> ::= <offset number> # non-virtual base override
1279  // <v-offset> ::= <offset number> _ <virtual offset number>
1280  // # virtual base override, with vcall offset
1281  if (!Virtual) {
1282  Out << 'h';
1283  mangleNumber(NonVirtual);
1284  Out << '_';
1285  return;
1286  }
1287 
1288  Out << 'v';
1289  mangleNumber(NonVirtual);
1290  Out << '_';
1291  mangleNumber(Virtual);
1292  Out << '_';
1293 }
1294 
1295 void CXXNameMangler::manglePrefix(QualType type) {
1296  if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1297  if (!mangleSubstitution(QualType(TST, 0))) {
1298  mangleTemplatePrefix(TST->getTemplateName());
1299 
1300  // FIXME: GCC does not appear to mangle the template arguments when
1301  // the template in question is a dependent template name. Should we
1302  // emulate that badness?
1303  mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());
1304  addSubstitution(QualType(TST, 0));
1305  }
1306  } else if (const auto *DTST =
1308  if (!mangleSubstitution(QualType(DTST, 0))) {
1309  TemplateName Template = getASTContext().getDependentTemplateName(
1310  DTST->getQualifier(), DTST->getIdentifier());
1311  mangleTemplatePrefix(Template);
1312 
1313  // FIXME: GCC does not appear to mangle the template arguments when
1314  // the template in question is a dependent template name. Should we
1315  // emulate that badness?
1316  mangleTemplateArgs(Template, DTST->template_arguments());
1317  addSubstitution(QualType(DTST, 0));
1318  }
1319  } else {
1320  // We use the QualType mangle type variant here because it handles
1321  // substitutions.
1322  mangleType(type);
1323  }
1324 }
1325 
1326 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1327 ///
1328 /// \param recursive - true if this is being called recursively,
1329 /// i.e. if there is more prefix "to the right".
1330 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1331  bool recursive) {
1332 
1333  // x, ::x
1334  // <unresolved-name> ::= [gs] <base-unresolved-name>
1335 
1336  // T::x / decltype(p)::x
1337  // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1338 
1339  // T::N::x /decltype(p)::N::x
1340  // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1341  // <base-unresolved-name>
1342 
1343  // A::x, N::y, A<T>::z; "gs" means leading "::"
1344  // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1345  // <base-unresolved-name>
1346 
1347  switch (qualifier->getKind()) {
1349  Out << "gs";
1350 
1351  // We want an 'sr' unless this is the entire NNS.
1352  if (recursive)
1353  Out << "sr";
1354 
1355  // We never want an 'E' here.
1356  return;
1357 
1359  llvm_unreachable("Can't mangle __super specifier");
1360 
1362  if (qualifier->getPrefix())
1363  mangleUnresolvedPrefix(qualifier->getPrefix(),
1364  /*recursive*/ true);
1365  else
1366  Out << "sr";
1367  mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1368  break;
1370  if (qualifier->getPrefix())
1371  mangleUnresolvedPrefix(qualifier->getPrefix(),
1372  /*recursive*/ true);
1373  else
1374  Out << "sr";
1375  mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1376  break;
1377 
1380  const Type *type = qualifier->getAsType();
1381 
1382  // We only want to use an unresolved-type encoding if this is one of:
1383  // - a decltype
1384  // - a template type parameter
1385  // - a template template parameter with arguments
1386  // In all of these cases, we should have no prefix.
1387  if (qualifier->getPrefix()) {
1388  mangleUnresolvedPrefix(qualifier->getPrefix(),
1389  /*recursive*/ true);
1390  } else {
1391  // Otherwise, all the cases want this.
1392  Out << "sr";
1393  }
1394 
1395  if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1396  return;
1397 
1398  break;
1399  }
1400 
1402  // Member expressions can have these without prefixes.
1403  if (qualifier->getPrefix())
1404  mangleUnresolvedPrefix(qualifier->getPrefix(),
1405  /*recursive*/ true);
1406  else
1407  Out << "sr";
1408 
1409  mangleSourceName(qualifier->getAsIdentifier());
1410  // An Identifier has no type information, so we can't emit abi tags for it.
1411  break;
1412  }
1413 
1414  // If this was the innermost part of the NNS, and we fell out to
1415  // here, append an 'E'.
1416  if (!recursive)
1417  Out << 'E';
1418 }
1419 
1420 /// Mangle an unresolved-name, which is generally used for names which
1421 /// weren't resolved to specific entities.
1422 void CXXNameMangler::mangleUnresolvedName(
1424  const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1425  unsigned knownArity) {
1426  if (qualifier) mangleUnresolvedPrefix(qualifier);
1427  switch (name.getNameKind()) {
1428  // <base-unresolved-name> ::= <simple-id>
1430  mangleSourceName(name.getAsIdentifierInfo());
1431  break;
1432  // <base-unresolved-name> ::= dn <destructor-name>
1434  Out << "dn";
1435  mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1436  break;
1437  // <base-unresolved-name> ::= on <operator-name>
1441  Out << "on";
1442  mangleOperatorName(name, knownArity);
1443  break;
1445  llvm_unreachable("Can't mangle a constructor name!");
1447  llvm_unreachable("Can't mangle a using directive name!");
1449  llvm_unreachable("Can't mangle a deduction guide name!");
1453  llvm_unreachable("Can't mangle Objective-C selector names here!");
1454  }
1455 
1456  // The <simple-id> and on <operator-name> productions end in an optional
1457  // <template-args>.
1458  if (TemplateArgs)
1459  mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
1460 }
1461 
1462 void CXXNameMangler::mangleUnqualifiedName(
1463  GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
1464  unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
1465  const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
1466  // <unqualified-name> ::= [<module-name>] [F] <operator-name>
1467  // ::= <ctor-dtor-name>
1468  // ::= [<module-name>] [F] <source-name>
1469  // ::= [<module-name>] DC <source-name>* E
1470 
1471  if (ND && DC && DC->isFileContext())
1472  mangleModuleName(ND);
1473 
1474  // A member-like constrained friend is mangled with a leading 'F'.
1475  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
1476  auto *FD = dyn_cast<FunctionDecl>(ND);
1477  auto *FTD = dyn_cast<FunctionTemplateDecl>(ND);
1478  if ((FD && FD->isMemberLikeConstrainedFriend()) ||
1479  (FTD && FTD->getTemplatedDecl()->isMemberLikeConstrainedFriend())) {
1480  if (!isCompatibleWith(LangOptions::ClangABI::Ver17))
1481  Out << 'F';
1482  }
1483 
1484  unsigned Arity = KnownArity;
1485  switch (Name.getNameKind()) {
1487  const IdentifierInfo *II = Name.getAsIdentifierInfo();
1488 
1489  // We mangle decomposition declarations as the names of their bindings.
1490  if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1491  // FIXME: Non-standard mangling for decomposition declarations:
1492  //
1493  // <unqualified-name> ::= DC <source-name>* E
1494  //
1495  // Proposed on cxx-abi-dev on 2016-08-12
1496  Out << "DC";
1497  for (auto *BD : DD->bindings())
1498  mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1499  Out << 'E';
1500  writeAbiTags(ND, AdditionalAbiTags);
1501  break;
1502  }
1503 
1504  if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
1505  // We follow MSVC in mangling GUID declarations as if they were variables
1506  // with a particular reserved name. Continue the pretense here.
1507  SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1508  llvm::raw_svector_ostream GUIDOS(GUID);
1509  Context.mangleMSGuidDecl(GD, GUIDOS);
1510  Out << GUID.size() << GUID;
1511  break;
1512  }
1513 
1514  if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1515  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1516  Out << "TA";
1517  mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1518  TPO->getValue(), /*TopLevel=*/true);
1519  break;
1520  }
1521 
1522  if (II) {
1523  // Match GCC's naming convention for internal linkage symbols, for
1524  // symbols that are not actually visible outside of this TU. GCC
1525  // distinguishes between internal and external linkage symbols in
1526  // its mangling, to support cases like this that were valid C++ prior
1527  // to DR426:
1528  //
1529  // void test() { extern void foo(); }
1530  // static void foo();
1531  //
1532  // Don't bother with the L marker for names in anonymous namespaces; the
1533  // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1534  // matches GCC anyway, because GCC does not treat anonymous namespaces as
1535  // implying internal linkage.
1536  if (Context.isInternalLinkageDecl(ND))
1537  Out << 'L';
1538 
1539  bool IsRegCall = FD &&
1540  FD->getType()->castAs<FunctionType>()->getCallConv() ==
1542  bool IsDeviceStub =
1543  FD && FD->hasAttr<CUDAGlobalAttr>() &&
1545  if (IsDeviceStub)
1546  mangleDeviceStubName(II);
1547  else if (IsRegCall)
1548  mangleRegCallName(II);
1549  else
1550  mangleSourceName(II);
1551 
1552  writeAbiTags(ND, AdditionalAbiTags);
1553  break;
1554  }
1555 
1556  // Otherwise, an anonymous entity. We must have a declaration.
1557  assert(ND && "mangling empty name without declaration");
1558 
1559  if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1560  if (NS->isAnonymousNamespace()) {
1561  // This is how gcc mangles these names.
1562  Out << "12_GLOBAL__N_1";
1563  break;
1564  }
1565  }
1566 
1567  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1568  // We must have an anonymous union or struct declaration.
1569  const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1570 
1571  // Itanium C++ ABI 5.1.2:
1572  //
1573  // For the purposes of mangling, the name of an anonymous union is
1574  // considered to be the name of the first named data member found by a
1575  // pre-order, depth-first, declaration-order walk of the data members of
1576  // the anonymous union. If there is no such data member (i.e., if all of
1577  // the data members in the union are unnamed), then there is no way for
1578  // a program to refer to the anonymous union, and there is therefore no
1579  // need to mangle its name.
1580  assert(RD->isAnonymousStructOrUnion()
1581  && "Expected anonymous struct or union!");
1582  const FieldDecl *FD = RD->findFirstNamedDataMember();
1583 
1584  // It's actually possible for various reasons for us to get here
1585  // with an empty anonymous struct / union. Fortunately, it
1586  // doesn't really matter what name we generate.
1587  if (!FD) break;
1588  assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1589 
1590  mangleSourceName(FD->getIdentifier());
1591  // Not emitting abi tags: internal name anyway.
1592  break;
1593  }
1594 
1595  // Class extensions have no name as a category, and it's possible
1596  // for them to be the semantic parent of certain declarations
1597  // (primarily, tag decls defined within declarations). Such
1598  // declarations will always have internal linkage, so the name
1599  // doesn't really matter, but we shouldn't crash on them. For
1600  // safety, just handle all ObjC containers here.
1601  if (isa<ObjCContainerDecl>(ND))
1602  break;
1603 
1604  // We must have an anonymous struct.
1605  const TagDecl *TD = cast<TagDecl>(ND);
1606  if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1607  assert(TD->getDeclContext() == D->getDeclContext() &&
1608  "Typedef should not be in another decl context!");
1609  assert(D->getDeclName().getAsIdentifierInfo() &&
1610  "Typedef was not named!");
1611  mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1612  assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1613  // Explicit abi tags are still possible; take from underlying type, not
1614  // from typedef.
1615  writeAbiTags(TD, nullptr);
1616  break;
1617  }
1618 
1619  // <unnamed-type-name> ::= <closure-type-name>
1620  //
1621  // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1622  // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1623  // # Parameter types or 'v' for 'void'.
1624  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1625  std::optional<unsigned> DeviceNumber =
1626  Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
1627 
1628  // If we have a device-number via the discriminator, use that to mangle
1629  // the lambda, otherwise use the typical lambda-mangling-number. In either
1630  // case, a '0' should be mangled as a normal unnamed class instead of as a
1631  // lambda.
1632  if (Record->isLambda() &&
1633  ((DeviceNumber && *DeviceNumber > 0) ||
1634  (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
1635  assert(!AdditionalAbiTags &&
1636  "Lambda type cannot have additional abi tags");
1637  mangleLambda(Record);
1638  break;
1639  }
1640  }
1641 
1642  if (TD->isExternallyVisible()) {
1643  unsigned UnnamedMangle =
1644  getASTContext().getManglingNumber(TD, Context.isAux());
1645  Out << "Ut";
1646  if (UnnamedMangle > 1)
1647  Out << UnnamedMangle - 2;
1648  Out << '_';
1649  writeAbiTags(TD, AdditionalAbiTags);
1650  break;
1651  }
1652 
1653  // Get a unique id for the anonymous struct. If it is not a real output
1654  // ID doesn't matter so use fake one.
1655  unsigned AnonStructId =
1656  NullOut ? 0
1657  : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));
1658 
1659  // Mangle it as a source name in the form
1660  // [n] $_<id>
1661  // where n is the length of the string.
1662  SmallString<8> Str;
1663  Str += "$_";
1664  Str += llvm::utostr(AnonStructId);
1665 
1666  Out << Str.size();
1667  Out << Str;
1668  break;
1669  }
1670 
1674  llvm_unreachable("Can't mangle Objective-C selector names here!");
1675 
1677  const CXXRecordDecl *InheritedFrom = nullptr;
1678  TemplateName InheritedTemplateName;
1679  const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1680  if (auto Inherited =
1681  cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1682  InheritedFrom = Inherited.getConstructor()->getParent();
1683  InheritedTemplateName =
1684  TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
1685  InheritedTemplateArgs =
1686  Inherited.getConstructor()->getTemplateSpecializationArgs();
1687  }
1688 
1689  if (ND == Structor)
1690  // If the named decl is the C++ constructor we're mangling, use the type
1691  // we were given.
1692  mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1693  else
1694  // Otherwise, use the complete constructor name. This is relevant if a
1695  // class with a constructor is declared within a constructor.
1696  mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1697 
1698  // FIXME: The template arguments are part of the enclosing prefix or
1699  // nested-name, but it's more convenient to mangle them here.
1700  if (InheritedTemplateArgs)
1701  mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
1702 
1703  writeAbiTags(ND, AdditionalAbiTags);
1704  break;
1705  }
1706 
1708  if (ND == Structor)
1709  // If the named decl is the C++ destructor we're mangling, use the type we
1710  // were given.
1711  mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1712  else
1713  // Otherwise, use the complete destructor name. This is relevant if a
1714  // class with a destructor is declared within a destructor.
1715  mangleCXXDtorType(Dtor_Complete);
1716  assert(ND);
1717  writeAbiTags(ND, AdditionalAbiTags);
1718  break;
1719 
1721  if (ND && Arity == UnknownArity) {
1722  Arity = cast<FunctionDecl>(ND)->getNumParams();
1723 
1724  // If we have a member function, we need to include the 'this' pointer.
1725  if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1726  if (MD->isImplicitObjectMemberFunction())
1727  Arity++;
1728  }
1729  [[fallthrough]];
1732  mangleOperatorName(Name, Arity);
1733  writeAbiTags(ND, AdditionalAbiTags);
1734  break;
1735 
1737  llvm_unreachable("Can't mangle a deduction guide name!");
1738 
1740  llvm_unreachable("Can't mangle a using directive name!");
1741  }
1742 }
1743 
1744 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1745  // <source-name> ::= <positive length number> __regcall3__ <identifier>
1746  // <number> ::= [n] <non-negative decimal integer>
1747  // <identifier> ::= <unqualified source code identifier>
1748  if (getASTContext().getLangOpts().RegCall4)
1749  Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"
1750  << II->getName();
1751  else
1752  Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1753  << II->getName();
1754 }
1755 
1756 void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1757  // <source-name> ::= <positive length number> __device_stub__ <identifier>
1758  // <number> ::= [n] <non-negative decimal integer>
1759  // <identifier> ::= <unqualified source code identifier>
1760  Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1761  << II->getName();
1762 }
1763 
1764 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1765  // <source-name> ::= <positive length number> <identifier>
1766  // <number> ::= [n] <non-negative decimal integer>
1767  // <identifier> ::= <unqualified source code identifier>
1768  Out << II->getLength() << II->getName();
1769 }
1770 
1771 void CXXNameMangler::mangleNestedName(GlobalDecl GD,
1772  const DeclContext *DC,
1773  const AbiTagList *AdditionalAbiTags,
1774  bool NoFunction) {
1775  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1776  // <nested-name>
1777  // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1778  // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1779  // <template-args> E
1780 
1781  Out << 'N';
1782  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1783  Qualifiers MethodQuals = Method->getMethodQualifiers();
1784  // We do not consider restrict a distinguishing attribute for overloading
1785  // purposes so we must not mangle it.
1786  if (Method->isExplicitObjectMemberFunction())
1787  Out << 'H';
1788  MethodQuals.removeRestrict();
1789  mangleQualifiers(MethodQuals);
1790  mangleRefQualifier(Method->getRefQualifier());
1791  }
1792 
1793  // Check if we have a template.
1794  const TemplateArgumentList *TemplateArgs = nullptr;
1795  if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1796  mangleTemplatePrefix(TD, NoFunction);
1797  mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1798  } else {
1799  manglePrefix(DC, NoFunction);
1800  mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1801  }
1802 
1803  Out << 'E';
1804 }
1805 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1807  // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1808 
1809  Out << 'N';
1810 
1811  mangleTemplatePrefix(TD);
1812  mangleTemplateArgs(asTemplateName(TD), Args);
1813 
1814  Out << 'E';
1815 }
1816 
1817 void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1818  GlobalDecl GD, const NamedDecl *PrefixND,
1819  const AbiTagList *AdditionalAbiTags) {
1820  // A <closure-prefix> represents a variable or field, not a regular
1821  // DeclContext, so needs special handling. In this case we're mangling a
1822  // limited form of <nested-name>:
1823  //
1824  // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1825 
1826  Out << 'N';
1827 
1828  mangleClosurePrefix(PrefixND);
1829  mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1830 
1831  Out << 'E';
1832 }
1833 
1835  GlobalDecl GD;
1836  // The Itanium spec says:
1837  // For entities in constructors and destructors, the mangling of the
1838  // complete object constructor or destructor is used as the base function
1839  // name, i.e. the C1 or D1 version.
1840  if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
1841  GD = GlobalDecl(CD, Ctor_Complete);
1842  else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
1843  GD = GlobalDecl(DD, Dtor_Complete);
1844  else
1845  GD = GlobalDecl(cast<FunctionDecl>(DC));
1846  return GD;
1847 }
1848 
1849 void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1850  const AbiTagList *AdditionalAbiTags) {
1851  const Decl *D = GD.getDecl();
1852  // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1853  // := Z <function encoding> E s [<discriminator>]
1854  // <local-name> := Z <function encoding> E d [ <parameter number> ]
1855  // _ <entity name>
1856  // <discriminator> := _ <non-negative number>
1857  assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1858  const RecordDecl *RD = GetLocalClassDecl(D);
1859  const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
1860 
1861  Out << 'Z';
1862 
1863  {
1864  AbiTagState LocalAbiTags(AbiTags);
1865 
1866  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1867  mangleObjCMethodName(MD);
1868  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1869  mangleBlockForPrefix(BD);
1870  else
1871  mangleFunctionEncoding(getParentOfLocalEntity(DC));
1872 
1873  // Implicit ABI tags (from namespace) are not available in the following
1874  // entity; reset to actually emitted tags, which are available.
1875  LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1876  }
1877 
1878  Out << 'E';
1879 
1880  // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1881  // be a bug that is fixed in trunk.
1882 
1883  if (RD) {
1884  // The parameter number is omitted for the last parameter, 0 for the
1885  // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1886  // <entity name> will of course contain a <closure-type-name>: Its
1887  // numbering will be local to the particular argument in which it appears
1888  // -- other default arguments do not affect its encoding.
1889  const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1890  if (CXXRD && CXXRD->isLambda()) {
1891  if (const ParmVarDecl *Parm
1892  = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1893  if (const FunctionDecl *Func
1894  = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1895  Out << 'd';
1896  unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1897  if (Num > 1)
1898  mangleNumber(Num - 2);
1899  Out << '_';
1900  }
1901  }
1902  }
1903 
1904  // Mangle the name relative to the closest enclosing function.
1905  // equality ok because RD derived from ND above
1906  if (D == RD) {
1907  mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
1908  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1909  if (const NamedDecl *PrefixND = getClosurePrefix(BD))
1910  mangleClosurePrefix(PrefixND, true /*NoFunction*/);
1911  else
1912  manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
1913  assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1914  mangleUnqualifiedBlock(BD);
1915  } else {
1916  const NamedDecl *ND = cast<NamedDecl>(D);
1917  mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
1918  AdditionalAbiTags, true /*NoFunction*/);
1919  }
1920  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1921  // Mangle a block in a default parameter; see above explanation for
1922  // lambdas.
1923  if (const ParmVarDecl *Parm
1924  = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1925  if (const FunctionDecl *Func
1926  = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1927  Out << 'd';
1928  unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1929  if (Num > 1)
1930  mangleNumber(Num - 2);
1931  Out << '_';
1932  }
1933  }
1934 
1935  assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1936  mangleUnqualifiedBlock(BD);
1937  } else {
1938  mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1939  }
1940 
1941  if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1942  unsigned disc;
1943  if (Context.getNextDiscriminator(ND, disc)) {
1944  if (disc < 10)
1945  Out << '_' << disc;
1946  else
1947  Out << "__" << disc << '_';
1948  }
1949  }
1950 }
1951 
1952 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1953  if (GetLocalClassDecl(Block)) {
1954  mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1955  return;
1956  }
1957  const DeclContext *DC = Context.getEffectiveDeclContext(Block);
1958  if (isLocalContainerContext(DC)) {
1959  mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1960  return;
1961  }
1962  if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1963  mangleClosurePrefix(PrefixND);
1964  else
1965  manglePrefix(DC);
1966  mangleUnqualifiedBlock(Block);
1967 }
1968 
1969 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1970  // When trying to be ABI-compatibility with clang 12 and before, mangle a
1971  // <data-member-prefix> now, with no substitutions and no <template-args>.
1972  if (Decl *Context = Block->getBlockManglingContextDecl()) {
1973  if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
1974  (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1975  Context->getDeclContext()->isRecord()) {
1976  const auto *ND = cast<NamedDecl>(Context);
1977  if (ND->getIdentifier()) {
1978  mangleSourceNameWithAbiTags(ND);
1979  Out << 'M';
1980  }
1981  }
1982  }
1983 
1984  // If we have a block mangling number, use it.
1985  unsigned Number = Block->getBlockManglingNumber();
1986  // Otherwise, just make up a number. It doesn't matter what it is because
1987  // the symbol in question isn't externally visible.
1988  if (!Number)
1989  Number = Context.getBlockId(Block, false);
1990  else {
1991  // Stored mangling numbers are 1-based.
1992  --Number;
1993  }
1994  Out << "Ub";
1995  if (Number > 0)
1996  Out << Number - 1;
1997  Out << '_';
1998 }
1999 
2000 // <template-param-decl>
2001 // ::= Ty # template type parameter
2002 // ::= Tk <concept name> [<template-args>] # constrained type parameter
2003 // ::= Tn <type> # template non-type parameter
2004 // ::= Tt <template-param-decl>* E [Q <requires-clause expr>]
2005 // # template template parameter
2006 // ::= Tp <template-param-decl> # template parameter pack
2007 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
2008  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
2009  if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
2010  if (Ty->isParameterPack())
2011  Out << "Tp";
2012  const TypeConstraint *Constraint = Ty->getTypeConstraint();
2013  if (Constraint && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2014  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2015  Out << "Tk";
2016  mangleTypeConstraint(Constraint);
2017  } else {
2018  Out << "Ty";
2019  }
2020  } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
2021  if (Tn->isExpandedParameterPack()) {
2022  for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
2023  Out << "Tn";
2024  mangleType(Tn->getExpansionType(I));
2025  }
2026  } else {
2027  QualType T = Tn->getType();
2028  if (Tn->isParameterPack()) {
2029  Out << "Tp";
2030  if (auto *PackExpansion = T->getAs<PackExpansionType>())
2031  T = PackExpansion->getPattern();
2032  }
2033  Out << "Tn";
2034  mangleType(T);
2035  }
2036  } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
2037  if (Tt->isExpandedParameterPack()) {
2038  for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
2039  ++I)
2040  mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I));
2041  } else {
2042  if (Tt->isParameterPack())
2043  Out << "Tp";
2044  mangleTemplateParameterList(Tt->getTemplateParameters());
2045  }
2046  }
2047 }
2048 
2049 void CXXNameMangler::mangleTemplateParameterList(
2050  const TemplateParameterList *Params) {
2051  Out << "Tt";
2052  for (auto *Param : *Params)
2053  mangleTemplateParamDecl(Param);
2054  mangleRequiresClause(Params->getRequiresClause());
2055  Out << "E";
2056 }
2057 
2058 void CXXNameMangler::mangleTypeConstraint(
2059  const ConceptDecl *Concept, ArrayRef<TemplateArgument> Arguments) {
2060  const DeclContext *DC = Context.getEffectiveDeclContext(Concept);
2061  if (!Arguments.empty())
2062  mangleTemplateName(Concept, Arguments);
2063  else if (DC->isTranslationUnit() || isStdNamespace(DC))
2064  mangleUnscopedName(Concept, DC, nullptr);
2065  else
2066  mangleNestedName(Concept, DC, nullptr);
2067 }
2068 
2069 void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) {
2071  if (Constraint->getTemplateArgsAsWritten()) {
2072  for (const TemplateArgumentLoc &ArgLoc :
2073  Constraint->getTemplateArgsAsWritten()->arguments())
2074  Args.push_back(ArgLoc.getArgument());
2075  }
2076  return mangleTypeConstraint(Constraint->getNamedConcept(), Args);
2077 }
2078 
2079 void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) {
2080  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2081  if (RequiresClause && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2082  Out << 'Q';
2083  mangleExpression(RequiresClause);
2084  }
2085 }
2086 
2087 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
2088  // When trying to be ABI-compatibility with clang 12 and before, mangle a
2089  // <data-member-prefix> now, with no substitutions.
2090  if (Decl *Context = Lambda->getLambdaContextDecl()) {
2091  if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
2092  (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
2093  !isa<ParmVarDecl>(Context)) {
2094  if (const IdentifierInfo *Name
2095  = cast<NamedDecl>(Context)->getIdentifier()) {
2096  mangleSourceName(Name);
2097  const TemplateArgumentList *TemplateArgs = nullptr;
2098  if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
2099  mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2100  Out << 'M';
2101  }
2102  }
2103  }
2104 
2105  Out << "Ul";
2106  mangleLambdaSig(Lambda);
2107  Out << "E";
2108 
2109  // The number is omitted for the first closure type with a given
2110  // <lambda-sig> in a given context; it is n-2 for the nth closure type
2111  // (in lexical order) with that same <lambda-sig> and context.
2112  //
2113  // The AST keeps track of the number for us.
2114  //
2115  // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2116  // and host-side compilations, an extra device mangle context may be created
2117  // if the host-side CXX ABI has different numbering for lambda. In such case,
2118  // if the mangle context is that device-side one, use the device-side lambda
2119  // mangling number for this lambda.
2120  std::optional<unsigned> DeviceNumber =
2121  Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
2122  unsigned Number =
2123  DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2124 
2125  assert(Number > 0 && "Lambda should be mangled as an unnamed class");
2126  if (Number > 1)
2127  mangleNumber(Number - 2);
2128  Out << '_';
2129 }
2130 
2131 void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
2132  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.
2133  for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2134  mangleTemplateParamDecl(D);
2135 
2136  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2137  if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList())
2138  mangleRequiresClause(TPL->getRequiresClause());
2139 
2140  auto *Proto =
2142  mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
2143  Lambda->getLambdaStaticInvoker());
2144 }
2145 
2146 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
2147  switch (qualifier->getKind()) {
2149  // nothing
2150  return;
2151 
2153  llvm_unreachable("Can't mangle __super specifier");
2154 
2156  mangleName(qualifier->getAsNamespace());
2157  return;
2158 
2160  mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
2161  return;
2162 
2165  manglePrefix(QualType(qualifier->getAsType(), 0));
2166  return;
2167 
2169  // Clang 14 and before did not consider this substitutable.
2170  bool Clang14Compat = isCompatibleWith(LangOptions::ClangABI::Ver14);
2171  if (!Clang14Compat && mangleSubstitution(qualifier))
2172  return;
2173 
2174  // Member expressions can have these without prefixes, but that
2175  // should end up in mangleUnresolvedPrefix instead.
2176  assert(qualifier->getPrefix());
2177  manglePrefix(qualifier->getPrefix());
2178 
2179  mangleSourceName(qualifier->getAsIdentifier());
2180 
2181  if (!Clang14Compat)
2182  addSubstitution(qualifier);
2183  return;
2184  }
2185 
2186  llvm_unreachable("unexpected nested name specifier");
2187 }
2188 
2189 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
2190  // <prefix> ::= <prefix> <unqualified-name>
2191  // ::= <template-prefix> <template-args>
2192  // ::= <closure-prefix>
2193  // ::= <template-param>
2194  // ::= # empty
2195  // ::= <substitution>
2196 
2197  assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
2198 
2199  if (DC->isTranslationUnit())
2200  return;
2201 
2202  if (NoFunction && isLocalContainerContext(DC))
2203  return;
2204 
2205  const NamedDecl *ND = cast<NamedDecl>(DC);
2206  if (mangleSubstitution(ND))
2207  return;
2208 
2209  // Check if we have a template-prefix or a closure-prefix.
2210  const TemplateArgumentList *TemplateArgs = nullptr;
2211  if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2212  mangleTemplatePrefix(TD);
2213  mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2214  } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2215  mangleClosurePrefix(PrefixND, NoFunction);
2216  mangleUnqualifiedName(ND, nullptr, nullptr);
2217  } else {
2218  const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2219  manglePrefix(DC, NoFunction);
2220  mangleUnqualifiedName(ND, DC, nullptr);
2221  }
2222 
2223  addSubstitution(ND);
2224 }
2225 
2226 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
2227  // <template-prefix> ::= <prefix> <template unqualified-name>
2228  // ::= <template-param>
2229  // ::= <substitution>
2230  if (TemplateDecl *TD = Template.getAsTemplateDecl())
2231  return mangleTemplatePrefix(TD);
2232 
2234  assert(Dependent && "unexpected template name kind");
2235 
2236  // Clang 11 and before mangled the substitution for a dependent template name
2237  // after already having emitted (a substitution for) the prefix.
2238  bool Clang11Compat = isCompatibleWith(LangOptions::ClangABI::Ver11);
2239  if (!Clang11Compat && mangleSubstitution(Template))
2240  return;
2241 
2242  if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
2243  manglePrefix(Qualifier);
2244 
2245  if (Clang11Compat && mangleSubstitution(Template))
2246  return;
2247 
2248  if (const IdentifierInfo *Id = Dependent->getIdentifier())
2249  mangleSourceName(Id);
2250  else
2251  mangleOperatorName(Dependent->getOperator(), UnknownArity);
2252 
2253  addSubstitution(Template);
2254 }
2255 
2256 void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2257  bool NoFunction) {
2258  const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
2259  // <template-prefix> ::= <prefix> <template unqualified-name>
2260  // ::= <template-param>
2261  // ::= <substitution>
2262  // <template-template-param> ::= <template-param>
2263  // <substitution>
2264 
2265  if (mangleSubstitution(ND))
2266  return;
2267 
2268  // <template-template-param> ::= <template-param>
2269  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2270  mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2271  } else {
2272  const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2273  manglePrefix(DC, NoFunction);
2274  if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
2275  mangleUnqualifiedName(GD, DC, nullptr);
2276  else
2277  mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
2278  nullptr);
2279  }
2280 
2281  addSubstitution(ND);
2282 }
2283 
2284 const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2285  if (isCompatibleWith(LangOptions::ClangABI::Ver12))
2286  return nullptr;
2287 
2288  const NamedDecl *Context = nullptr;
2289  if (auto *Block = dyn_cast<BlockDecl>(ND)) {
2290  Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
2291  } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
2292  if (RD->isLambda())
2293  Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2294  }
2295  if (!Context)
2296  return nullptr;
2297 
2298  // Only lambdas within the initializer of a non-local variable or non-static
2299  // data member get a <closure-prefix>.
2300  if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
2301  isa<FieldDecl>(Context))
2302  return Context;
2303 
2304  return nullptr;
2305 }
2306 
2307 void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2308  // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2309  // ::= <template-prefix> <template-args> M
2310  if (mangleSubstitution(ND))
2311  return;
2312 
2313  const TemplateArgumentList *TemplateArgs = nullptr;
2314  if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2315  mangleTemplatePrefix(TD, NoFunction);
2316  mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2317  } else {
2318  const auto *DC = Context.getEffectiveDeclContext(ND);
2319  manglePrefix(DC, NoFunction);
2320  mangleUnqualifiedName(ND, DC, nullptr);
2321  }
2322 
2323  Out << 'M';
2324 
2325  addSubstitution(ND);
2326 }
2327 
2328 /// Mangles a template name under the production <type>. Required for
2329 /// template template arguments.
2330 /// <type> ::= <class-enum-type>
2331 /// ::= <template-param>
2332 /// ::= <substitution>
2333 void CXXNameMangler::mangleType(TemplateName TN) {
2334  if (mangleSubstitution(TN))
2335  return;
2336 
2337  TemplateDecl *TD = nullptr;
2338 
2339  switch (TN.getKind()) {
2343  TD = TN.getAsTemplateDecl();
2344  goto HaveDecl;
2345 
2346  HaveDecl:
2347  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2348  mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2349  else
2350  mangleName(TD);
2351  break;
2352 
2355  llvm_unreachable("can't mangle an overloaded template name as a <type>");
2356 
2359  assert(Dependent->isIdentifier());
2360 
2361  // <class-enum-type> ::= <name>
2362  // <name> ::= <nested-name>
2363  mangleUnresolvedPrefix(Dependent->getQualifier());
2364  mangleSourceName(Dependent->getIdentifier());
2365  break;
2366  }
2367 
2369  // Substituted template parameters are mangled as the substituted
2370  // template. This will check for the substitution twice, which is
2371  // fine, but we have to return early so that we don't try to *add*
2372  // the substitution twice.
2375  mangleType(subst->getReplacement());
2376  return;
2377  }
2378 
2380  // FIXME: not clear how to mangle this!
2381  // template <template <class> class T...> class A {
2382  // template <template <class> class U...> void foo(B<T,U> x...);
2383  // };
2384  Out << "_SUBSTPACK_";
2385  break;
2386  }
2387  }
2388 
2389  addSubstitution(TN);
2390 }
2391 
2392 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2393  StringRef Prefix) {
2394  // Only certain other types are valid as prefixes; enumerate them.
2395  switch (Ty->getTypeClass()) {
2396  case Type::Builtin:
2397  case Type::Complex:
2398  case Type::Adjusted:
2399  case Type::Decayed:
2400  case Type::ArrayParameter:
2401  case Type::Pointer:
2402  case Type::BlockPointer:
2403  case Type::LValueReference:
2404  case Type::RValueReference:
2405  case Type::MemberPointer:
2406  case Type::ConstantArray:
2407  case Type::IncompleteArray:
2408  case Type::VariableArray:
2409  case Type::DependentSizedArray:
2410  case Type::DependentAddressSpace:
2411  case Type::DependentVector:
2412  case Type::DependentSizedExtVector:
2413  case Type::Vector:
2414  case Type::ExtVector:
2415  case Type::ConstantMatrix:
2416  case Type::DependentSizedMatrix:
2417  case Type::FunctionProto:
2418  case Type::FunctionNoProto:
2419  case Type::Paren:
2420  case Type::Attributed:
2421  case Type::BTFTagAttributed:
2422  case Type::Auto:
2423  case Type::DeducedTemplateSpecialization:
2424  case Type::PackExpansion:
2425  case Type::ObjCObject:
2426  case Type::ObjCInterface:
2427  case Type::ObjCObjectPointer:
2428  case Type::ObjCTypeParam:
2429  case Type::Atomic:
2430  case Type::Pipe:
2431  case Type::MacroQualified:
2432  case Type::BitInt:
2433  case Type::DependentBitInt:
2434  case Type::CountAttributed:
2435  llvm_unreachable("type is illegal as a nested name specifier");
2436 
2437  case Type::SubstTemplateTypeParmPack:
2438  // FIXME: not clear how to mangle this!
2439  // template <class T...> class A {
2440  // template <class U...> void foo(decltype(T::foo(U())) x...);
2441  // };
2442  Out << "_SUBSTPACK_";
2443  break;
2444 
2445  // <unresolved-type> ::= <template-param>
2446  // ::= <decltype>
2447  // ::= <template-template-param> <template-args>
2448  // (this last is not official yet)
2449  case Type::TypeOfExpr:
2450  case Type::TypeOf:
2451  case Type::Decltype:
2452  case Type::PackIndexing:
2453  case Type::TemplateTypeParm:
2454  case Type::UnaryTransform:
2455  case Type::SubstTemplateTypeParm:
2456  unresolvedType:
2457  // Some callers want a prefix before the mangled type.
2458  Out << Prefix;
2459 
2460  // This seems to do everything we want. It's not really
2461  // sanctioned for a substituted template parameter, though.
2462  mangleType(Ty);
2463 
2464  // We never want to print 'E' directly after an unresolved-type,
2465  // so we return directly.
2466  return true;
2467 
2468  case Type::Typedef:
2469  mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2470  break;
2471 
2472  case Type::UnresolvedUsing:
2473  mangleSourceNameWithAbiTags(
2474  cast<UnresolvedUsingType>(Ty)->getDecl());
2475  break;
2476 
2477  case Type::Enum:
2478  case Type::Record:
2479  mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2480  break;
2481 
2482  case Type::TemplateSpecialization: {
2483  const TemplateSpecializationType *TST =
2484  cast<TemplateSpecializationType>(Ty);
2485  TemplateName TN = TST->getTemplateName();
2486  switch (TN.getKind()) {
2489  TemplateDecl *TD = TN.getAsTemplateDecl();
2490 
2491  // If the base is a template template parameter, this is an
2492  // unresolved type.
2493  assert(TD && "no template for template specialization type");
2494  if (isa<TemplateTemplateParmDecl>(TD))
2495  goto unresolvedType;
2496 
2497  mangleSourceNameWithAbiTags(TD);
2498  break;
2499  }
2500 
2504  llvm_unreachable("invalid base for a template specialization type");
2505 
2509  mangleExistingSubstitution(subst->getReplacement());
2510  break;
2511  }
2512 
2514  // FIXME: not clear how to mangle this!
2515  // template <template <class U> class T...> class A {
2516  // template <class U...> void foo(decltype(T<U>::foo) x...);
2517  // };
2518  Out << "_SUBSTPACK_";
2519  break;
2520  }
2522  TemplateDecl *TD = TN.getAsTemplateDecl();
2523  assert(TD && !isa<TemplateTemplateParmDecl>(TD));
2524  mangleSourceNameWithAbiTags(TD);
2525  break;
2526  }
2527  }
2528 
2529  // Note: we don't pass in the template name here. We are mangling the
2530  // original source-level template arguments, so we shouldn't consider
2531  // conversions to the corresponding template parameter.
2532  // FIXME: Other compilers mangle partially-resolved template arguments in
2533  // unresolved-qualifier-levels.
2534  mangleTemplateArgs(TemplateName(), TST->template_arguments());
2535  break;
2536  }
2537 
2538  case Type::InjectedClassName:
2539  mangleSourceNameWithAbiTags(
2540  cast<InjectedClassNameType>(Ty)->getDecl());
2541  break;
2542 
2543  case Type::DependentName:
2544  mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2545  break;
2546 
2547  case Type::DependentTemplateSpecialization: {
2549  cast<DependentTemplateSpecializationType>(Ty);
2550  TemplateName Template = getASTContext().getDependentTemplateName(
2551  DTST->getQualifier(), DTST->getIdentifier());
2552  mangleSourceName(DTST->getIdentifier());
2553  mangleTemplateArgs(Template, DTST->template_arguments());
2554  break;
2555  }
2556 
2557  case Type::Using:
2558  return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2559  Prefix);
2560  case Type::Elaborated:
2561  return mangleUnresolvedTypeOrSimpleId(
2562  cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2563  }
2564 
2565  return false;
2566 }
2567 
2568 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2569  switch (Name.getNameKind()) {
2578  llvm_unreachable("Not an operator name");
2579 
2581  // <operator-name> ::= cv <type> # (cast)
2582  Out << "cv";
2583  mangleType(Name.getCXXNameType());
2584  break;
2585 
2587  Out << "li";
2588  mangleSourceName(Name.getCXXLiteralIdentifier());
2589  return;
2590 
2592  mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2593  break;
2594  }
2595 }
2596 
2597 void
2598 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2599  switch (OO) {
2600  // <operator-name> ::= nw # new
2601  case OO_New: Out << "nw"; break;
2602  // ::= na # new[]
2603  case OO_Array_New: Out << "na"; break;
2604  // ::= dl # delete
2605  case OO_Delete: Out << "dl"; break;
2606  // ::= da # delete[]
2607  case OO_Array_Delete: Out << "da"; break;
2608  // ::= ps # + (unary)
2609  // ::= pl # + (binary or unknown)
2610  case OO_Plus:
2611  Out << (Arity == 1? "ps" : "pl"); break;
2612  // ::= ng # - (unary)
2613  // ::= mi # - (binary or unknown)
2614  case OO_Minus:
2615  Out << (Arity == 1? "ng" : "mi"); break;
2616  // ::= ad # & (unary)
2617  // ::= an # & (binary or unknown)
2618  case OO_Amp:
2619  Out << (Arity == 1? "ad" : "an"); break;
2620  // ::= de # * (unary)
2621  // ::= ml # * (binary or unknown)
2622  case OO_Star:
2623  // Use binary when unknown.
2624  Out << (Arity == 1? "de" : "ml"); break;
2625  // ::= co # ~
2626  case OO_Tilde: Out << "co"; break;
2627  // ::= dv # /
2628  case OO_Slash: Out << "dv"; break;
2629  // ::= rm # %
2630  case OO_Percent: Out << "rm"; break;
2631  // ::= or # |
2632  case OO_Pipe: Out << "or"; break;
2633  // ::= eo # ^
2634  case OO_Caret: Out << "eo"; break;
2635  // ::= aS # =
2636  case OO_Equal: Out << "aS"; break;
2637  // ::= pL # +=
2638  case OO_PlusEqual: Out << "pL"; break;
2639  // ::= mI # -=
2640  case OO_MinusEqual: Out << "mI"; break;
2641  // ::= mL # *=
2642  case OO_StarEqual: Out << "mL"; break;
2643  // ::= dV # /=
2644  case OO_SlashEqual: Out << "dV"; break;
2645  // ::= rM # %=
2646  case OO_PercentEqual: Out << "rM"; break;
2647  // ::= aN # &=
2648  case OO_AmpEqual: Out << "aN"; break;
2649  // ::= oR # |=
2650  case OO_PipeEqual: Out << "oR"; break;
2651  // ::= eO # ^=
2652  case OO_CaretEqual: Out << "eO"; break;
2653  // ::= ls # <<
2654  case OO_LessLess: Out << "ls"; break;
2655  // ::= rs # >>
2656  case OO_GreaterGreater: Out << "rs"; break;
2657  // ::= lS # <<=
2658  case OO_LessLessEqual: Out << "lS"; break;
2659  // ::= rS # >>=
2660  case OO_GreaterGreaterEqual: Out << "rS"; break;
2661  // ::= eq # ==
2662  case OO_EqualEqual: Out << "eq"; break;
2663  // ::= ne # !=
2664  case OO_ExclaimEqual: Out << "ne"; break;
2665  // ::= lt # <
2666  case OO_Less: Out << "lt"; break;
2667  // ::= gt # >
2668  case OO_Greater: Out << "gt"; break;
2669  // ::= le # <=
2670  case OO_LessEqual: Out << "le"; break;
2671  // ::= ge # >=
2672  case OO_GreaterEqual: Out << "ge"; break;
2673  // ::= nt # !
2674  case OO_Exclaim: Out << "nt"; break;
2675  // ::= aa # &&
2676  case OO_AmpAmp: Out << "aa"; break;
2677  // ::= oo # ||
2678  case OO_PipePipe: Out << "oo"; break;
2679  // ::= pp # ++
2680  case OO_PlusPlus: Out << "pp"; break;
2681  // ::= mm # --
2682  case OO_MinusMinus: Out << "mm"; break;
2683  // ::= cm # ,
2684  case OO_Comma: Out << "cm"; break;
2685  // ::= pm # ->*
2686  case OO_ArrowStar: Out << "pm"; break;
2687  // ::= pt # ->
2688  case OO_Arrow: Out << "pt"; break;
2689  // ::= cl # ()
2690  case OO_Call: Out << "cl"; break;
2691  // ::= ix # []
2692  case OO_Subscript: Out << "ix"; break;
2693 
2694  // ::= qu # ?
2695  // The conditional operator can't be overloaded, but we still handle it when
2696  // mangling expressions.
2697  case OO_Conditional: Out << "qu"; break;
2698  // Proposal on cxx-abi-dev, 2015-10-21.
2699  // ::= aw # co_await
2700  case OO_Coawait: Out << "aw"; break;
2701  // Proposed in cxx-abi github issue 43.
2702  // ::= ss # <=>
2703  case OO_Spaceship: Out << "ss"; break;
2704 
2705  case OO_None:
2707  llvm_unreachable("Not an overloaded operator");
2708  }
2709 }
2710 
2711 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2712  // Vendor qualifiers come first and if they are order-insensitive they must
2713  // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2714 
2715  // <type> ::= U <addrspace-expr>
2716  if (DAST) {
2717  Out << "U2ASI";
2718  mangleExpression(DAST->getAddrSpaceExpr());
2719  Out << "E";
2720  }
2721 
2722  // Address space qualifiers start with an ordinary letter.
2723  if (Quals.hasAddressSpace()) {
2724  // Address space extension:
2725  //
2726  // <type> ::= U <target-addrspace>
2727  // <type> ::= U <OpenCL-addrspace>
2728  // <type> ::= U <CUDA-addrspace>
2729 
2730  SmallString<64> ASString;
2731  LangAS AS = Quals.getAddressSpace();
2732 
2733  if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2734  // <target-addrspace> ::= "AS" <address-space-number>
2735  unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2736  if (TargetAS != 0 ||
2737  Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
2738  ASString = "AS" + llvm::utostr(TargetAS);
2739  } else {
2740  switch (AS) {
2741  default: llvm_unreachable("Not a language specific address space");
2742  // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2743  // "private"| "generic" | "device" |
2744  // "host" ]
2745  case LangAS::opencl_global:
2746  ASString = "CLglobal";
2747  break;
2749  ASString = "CLdevice";
2750  break;
2752  ASString = "CLhost";
2753  break;
2754  case LangAS::opencl_local:
2755  ASString = "CLlocal";
2756  break;
2758  ASString = "CLconstant";
2759  break;
2761  ASString = "CLprivate";
2762  break;
2764  ASString = "CLgeneric";
2765  break;
2766  // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2767  // "device" | "host" ]
2768  case LangAS::sycl_global:
2769  ASString = "SYglobal";
2770  break;
2772  ASString = "SYglobaldevice";
2773  break;
2775  ASString = "SYglobalhost";
2776  break;
2777  case LangAS::sycl_local:
2778  ASString = "SYlocal";
2779  break;
2780  case LangAS::sycl_private:
2781  ASString = "SYprivate";
2782  break;
2783  // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2784  case LangAS::cuda_device:
2785  ASString = "CUdevice";
2786  break;
2787  case LangAS::cuda_constant:
2788  ASString = "CUconstant";
2789  break;
2790  case LangAS::cuda_shared:
2791  ASString = "CUshared";
2792  break;
2793  // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2794  case LangAS::ptr32_sptr:
2795  ASString = "ptr32_sptr";
2796  break;
2797  case LangAS::ptr32_uptr:
2798  // For z/OS, there are no special mangling rules applied to the ptr32
2799  // qualifier. Ex: void foo(int * __ptr32 p) -> _Z3f2Pi. The mangling for
2800  // "p" is treated the same as a regular integer pointer.
2801  if (!getASTContext().getTargetInfo().getTriple().isOSzOS())
2802  ASString = "ptr32_uptr";
2803  break;
2804  case LangAS::ptr64:
2805  ASString = "ptr64";
2806  break;
2807  }
2808  }
2809  if (!ASString.empty())
2810  mangleVendorQualifier(ASString);
2811  }
2812 
2813  // The ARC ownership qualifiers start with underscores.
2814  // Objective-C ARC Extension:
2815  //
2816  // <type> ::= U "__strong"
2817  // <type> ::= U "__weak"
2818  // <type> ::= U "__autoreleasing"
2819  //
2820  // Note: we emit __weak first to preserve the order as
2821  // required by the Itanium ABI.
2822  if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2823  mangleVendorQualifier("__weak");
2824 
2825  // __unaligned (from -fms-extensions)
2826  if (Quals.hasUnaligned())
2827  mangleVendorQualifier("__unaligned");
2828 
2829  // Remaining ARC ownership qualifiers.
2830  switch (Quals.getObjCLifetime()) {
2831  case Qualifiers::OCL_None:
2832  break;
2833 
2834  case Qualifiers::OCL_Weak:
2835  // Do nothing as we already handled this case above.
2836  break;
2837 
2839  mangleVendorQualifier("__strong");
2840  break;
2841 
2843  mangleVendorQualifier("__autoreleasing");
2844  break;
2845 
2847  // The __unsafe_unretained qualifier is *not* mangled, so that
2848  // __unsafe_unretained types in ARC produce the same manglings as the
2849  // equivalent (but, naturally, unqualified) types in non-ARC, providing
2850  // better ABI compatibility.
2851  //
2852  // It's safe to do this because unqualified 'id' won't show up
2853  // in any type signatures that need to be mangled.
2854  break;
2855  }
2856 
2857  // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2858  if (Quals.hasRestrict())
2859  Out << 'r';
2860  if (Quals.hasVolatile())
2861  Out << 'V';
2862  if (Quals.hasConst())
2863  Out << 'K';
2864 }
2865 
2866 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2867  Out << 'U' << name.size() << name;
2868 }
2869 
2870 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2871  // <ref-qualifier> ::= R # lvalue reference
2872  // ::= O # rvalue-reference
2873  switch (RefQualifier) {
2874  case RQ_None:
2875  break;
2876 
2877  case RQ_LValue:
2878  Out << 'R';
2879  break;
2880 
2881  case RQ_RValue:
2882  Out << 'O';
2883  break;
2884  }
2885 }
2886 
2887 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2888  Context.mangleObjCMethodNameAsSourceName(MD, Out);
2889 }
2890 
2891 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2892  ASTContext &Ctx) {
2893  if (Quals)
2894  return true;
2895  if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2896  return true;
2897  if (Ty->isOpenCLSpecificType())
2898  return true;
2899  // From Clang 18.0 we correctly treat SVE types as substitution candidates.
2900  if (Ty->isSVESizelessBuiltinType() &&
2901  Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)
2902  return true;
2903  if (Ty->isBuiltinType())
2904  return false;
2905  // Through to Clang 6.0, we accidentally treated undeduced auto types as
2906  // substitution candidates.
2907  if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2908  isa<AutoType>(Ty))
2909  return false;
2910  // A placeholder type for class template deduction is substitutable with
2911  // its corresponding template name; this is handled specially when mangling
2912  // the type.
2913  if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2914  if (DeducedTST->getDeducedType().isNull())
2915  return false;
2916  return true;
2917 }
2918 
2919 void CXXNameMangler::mangleType(QualType T) {
2920  // If our type is instantiation-dependent but not dependent, we mangle
2921  // it as it was written in the source, removing any top-level sugar.
2922  // Otherwise, use the canonical type.
2923  //
2924  // FIXME: This is an approximation of the instantiation-dependent name
2925  // mangling rules, since we should really be using the type as written and
2926  // augmented via semantic analysis (i.e., with implicit conversions and
2927  // default template arguments) for any instantiation-dependent type.
2928  // Unfortunately, that requires several changes to our AST:
2929  // - Instantiation-dependent TemplateSpecializationTypes will need to be
2930  // uniqued, so that we can handle substitutions properly
2931  // - Default template arguments will need to be represented in the
2932  // TemplateSpecializationType, since they need to be mangled even though
2933  // they aren't written.
2934  // - Conversions on non-type template arguments need to be expressed, since
2935  // they can affect the mangling of sizeof/alignof.
2936  //
2937  // FIXME: This is wrong when mapping to the canonical type for a dependent
2938  // type discards instantiation-dependent portions of the type, such as for:
2939  //
2940  // template<typename T, int N> void f(T (&)[sizeof(N)]);
2941  // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2942  //
2943  // It's also wrong in the opposite direction when instantiation-dependent,
2944  // canonically-equivalent types differ in some irrelevant portion of inner
2945  // type sugar. In such cases, we fail to form correct substitutions, eg:
2946  //
2947  // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2948  //
2949  // We should instead canonicalize the non-instantiation-dependent parts,
2950  // regardless of whether the type as a whole is dependent or instantiation
2951  // dependent.
2953  T = T.getCanonicalType();
2954  else {
2955  // Desugar any types that are purely sugar.
2956  do {
2957  // Don't desugar through template specialization types that aren't
2958  // type aliases. We need to mangle the template arguments as written.
2959  if (const TemplateSpecializationType *TST
2960  = dyn_cast<TemplateSpecializationType>(T))
2961  if (!TST->isTypeAlias())
2962  break;
2963 
2964  // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2965  // instantation-dependent qualifiers. See
2966  // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2967 
2968  QualType Desugared
2969  = T.getSingleStepDesugaredType(Context.getASTContext());
2970  if (Desugared == T)
2971  break;
2972 
2973  T = Desugared;
2974  } while (true);
2975  }
2976  SplitQualType split = T.split();
2977  Qualifiers quals = split.Quals;
2978  const Type *ty = split.Ty;
2979 
2980  bool isSubstitutable =
2981  isTypeSubstitutable(quals, ty, Context.getASTContext());
2982  if (isSubstitutable && mangleSubstitution(T))
2983  return;
2984 
2985  // If we're mangling a qualified array type, push the qualifiers to
2986  // the element type.
2987  if (quals && isa<ArrayType>(T)) {
2988  ty = Context.getASTContext().getAsArrayType(T);
2989  quals = Qualifiers();
2990 
2991  // Note that we don't update T: we want to add the
2992  // substitution at the original type.
2993  }
2994 
2995  if (quals || ty->isDependentAddressSpaceType()) {
2996  if (const DependentAddressSpaceType *DAST =
2997  dyn_cast<DependentAddressSpaceType>(ty)) {
2998  SplitQualType splitDAST = DAST->getPointeeType().split();
2999  mangleQualifiers(splitDAST.Quals, DAST);
3000  mangleType(QualType(splitDAST.Ty, 0));
3001  } else {
3002  mangleQualifiers(quals);
3003 
3004  // Recurse: even if the qualified type isn't yet substitutable,
3005  // the unqualified type might be.
3006  mangleType(QualType(ty, 0));
3007  }
3008  } else {
3009  switch (ty->getTypeClass()) {
3010 #define ABSTRACT_TYPE(CLASS, PARENT)
3011 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
3012  case Type::CLASS: \
3013  llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
3014  return;
3015 #define TYPE(CLASS, PARENT) \
3016  case Type::CLASS: \
3017  mangleType(static_cast<const CLASS##Type*>(ty)); \
3018  break;
3019 #include "clang/AST/TypeNodes.inc"
3020  }
3021  }
3022 
3023  // Add the substitution.
3024  if (isSubstitutable)
3025  addSubstitution(T);
3026 }
3027 
3028 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
3029  if (!mangleStandardSubstitution(ND))
3030  mangleName(ND);
3031 }
3032 
3033 void CXXNameMangler::mangleType(const BuiltinType *T) {
3034  // <type> ::= <builtin-type>
3035  // <builtin-type> ::= v # void
3036  // ::= w # wchar_t
3037  // ::= b # bool
3038  // ::= c # char
3039  // ::= a # signed char
3040  // ::= h # unsigned char
3041  // ::= s # short
3042  // ::= t # unsigned short
3043  // ::= i # int
3044  // ::= j # unsigned int
3045  // ::= l # long
3046  // ::= m # unsigned long
3047  // ::= x # long long, __int64
3048  // ::= y # unsigned long long, __int64
3049  // ::= n # __int128
3050  // ::= o # unsigned __int128
3051  // ::= f # float
3052  // ::= d # double
3053  // ::= e # long double, __float80
3054  // ::= g # __float128
3055  // ::= g # __ibm128
3056  // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
3057  // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
3058  // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
3059  // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3060  // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
3061  // ::= Di # char32_t
3062  // ::= Ds # char16_t
3063  // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3064  // ::= [DS] DA # N1169 fixed-point [_Sat] T _Accum
3065  // ::= [DS] DR # N1169 fixed-point [_Sat] T _Fract
3066  // ::= u <source-name> # vendor extended type
3067  //
3068  // <fixed-point-size>
3069  // ::= s # short
3070  // ::= t # unsigned short
3071  // ::= i # plain
3072  // ::= j # unsigned
3073  // ::= l # long
3074  // ::= m # unsigned long
3075  std::string type_name;
3076  // Normalize integer types as vendor extended types:
3077  // u<length>i<type size>
3078  // u<length>u<type size>
3079  if (NormalizeIntegers && T->isInteger()) {
3080  if (T->isSignedInteger()) {
3081  switch (getASTContext().getTypeSize(T)) {
3082  case 8:
3083  // Pick a representative for each integer size in the substitution
3084  // dictionary. (Its actual defined size is not relevant.)
3085  if (mangleSubstitution(BuiltinType::SChar))
3086  break;
3087  Out << "u2i8";
3088  addSubstitution(BuiltinType::SChar);
3089  break;
3090  case 16:
3091  if (mangleSubstitution(BuiltinType::Short))
3092  break;
3093  Out << "u3i16";
3094  addSubstitution(BuiltinType::Short);
3095  break;
3096  case 32:
3097  if (mangleSubstitution(BuiltinType::Int))
3098  break;
3099  Out << "u3i32";
3100  addSubstitution(BuiltinType::Int);
3101  break;
3102  case 64:
3103  if (mangleSubstitution(BuiltinType::Long))
3104  break;
3105  Out << "u3i64";
3106  addSubstitution(BuiltinType::Long);
3107  break;
3108  case 128:
3109  if (mangleSubstitution(BuiltinType::Int128))
3110  break;
3111  Out << "u4i128";
3112  addSubstitution(BuiltinType::Int128);
3113  break;
3114  default:
3115  llvm_unreachable("Unknown integer size for normalization");
3116  }
3117  } else {
3118  switch (getASTContext().getTypeSize(T)) {
3119  case 8:
3120  if (mangleSubstitution(BuiltinType::UChar))
3121  break;
3122  Out << "u2u8";
3123  addSubstitution(BuiltinType::UChar);
3124  break;
3125  case 16:
3126  if (mangleSubstitution(BuiltinType::UShort))
3127  break;
3128  Out << "u3u16";
3129  addSubstitution(BuiltinType::UShort);
3130  break;
3131  case 32:
3132  if (mangleSubstitution(BuiltinType::UInt))
3133  break;
3134  Out << "u3u32";
3135  addSubstitution(BuiltinType::UInt);
3136  break;
3137  case 64:
3138  if (mangleSubstitution(BuiltinType::ULong))
3139  break;
3140  Out << "u3u64";
3141  addSubstitution(BuiltinType::ULong);
3142  break;
3143  case 128:
3144  if (mangleSubstitution(BuiltinType::UInt128))
3145  break;
3146  Out << "u4u128";
3147  addSubstitution(BuiltinType::UInt128);
3148  break;
3149  default:
3150  llvm_unreachable("Unknown integer size for normalization");
3151  }
3152  }
3153  return;
3154  }
3155  switch (T->getKind()) {
3156  case BuiltinType::Void:
3157  Out << 'v';
3158  break;
3159  case BuiltinType::Bool:
3160  Out << 'b';
3161  break;
3162  case BuiltinType::Char_U:
3163  case BuiltinType::Char_S:
3164  Out << 'c';
3165  break;
3166  case BuiltinType::UChar:
3167  Out << 'h';
3168  break;
3169  case BuiltinType::UShort:
3170  Out << 't';
3171  break;
3172  case BuiltinType::UInt:
3173  Out << 'j';
3174  break;
3175  case BuiltinType::ULong:
3176  Out << 'm';
3177  break;
3178  case BuiltinType::ULongLong:
3179  Out << 'y';
3180  break;
3181  case BuiltinType::UInt128:
3182  Out << 'o';
3183  break;
3184  case BuiltinType::SChar:
3185  Out << 'a';
3186  break;
3187  case BuiltinType::WChar_S:
3188  case BuiltinType::WChar_U:
3189  Out << 'w';
3190  break;
3191  case BuiltinType::Char8:
3192  Out << "Du";
3193  break;
3194  case BuiltinType::Char16:
3195  Out << "Ds";
3196  break;
3197  case BuiltinType::Char32:
3198  Out << "Di";
3199  break;
3200  case BuiltinType::Short:
3201  Out << 's';
3202  break;
3203  case BuiltinType::Int:
3204  Out << 'i';
3205  break;
3206  case BuiltinType::Long:
3207  Out << 'l';
3208  break;
3209  case BuiltinType::LongLong:
3210  Out << 'x';
3211  break;
3212  case BuiltinType::Int128:
3213  Out << 'n';
3214  break;
3215  case BuiltinType::Float16:
3216  Out << "DF16_";
3217  break;
3218  case BuiltinType::ShortAccum:
3219  Out << "DAs";
3220  break;
3221  case BuiltinType::Accum:
3222  Out << "DAi";
3223  break;
3224  case BuiltinType::LongAccum:
3225  Out << "DAl";
3226  break;
3227  case BuiltinType::UShortAccum:
3228  Out << "DAt";
3229  break;
3230  case BuiltinType::UAccum:
3231  Out << "DAj";
3232  break;
3233  case BuiltinType::ULongAccum:
3234  Out << "DAm";
3235  break;
3236  case BuiltinType::ShortFract:
3237  Out << "DRs";
3238  break;
3239  case BuiltinType::Fract:
3240  Out << "DRi";
3241  break;
3242  case BuiltinType::LongFract:
3243  Out << "DRl";
3244  break;
3245  case BuiltinType::UShortFract:
3246  Out << "DRt";
3247  break;
3248  case BuiltinType::UFract:
3249  Out << "DRj";
3250  break;
3251  case BuiltinType::ULongFract:
3252  Out << "DRm";
3253  break;
3254  case BuiltinType::SatShortAccum:
3255  Out << "DSDAs";
3256  break;
3257  case BuiltinType::SatAccum:
3258  Out << "DSDAi";
3259  break;
3260  case BuiltinType::SatLongAccum:
3261  Out << "DSDAl";
3262  break;
3263  case BuiltinType::SatUShortAccum:
3264  Out << "DSDAt";
3265  break;
3266  case BuiltinType::SatUAccum:
3267  Out << "DSDAj";
3268  break;
3269  case BuiltinType::SatULongAccum:
3270  Out << "DSDAm";
3271  break;
3272  case BuiltinType::SatShortFract:
3273  Out << "DSDRs";
3274  break;
3275  case BuiltinType::SatFract:
3276  Out << "DSDRi";
3277  break;
3278  case BuiltinType::SatLongFract:
3279  Out << "DSDRl";
3280  break;
3281  case BuiltinType::SatUShortFract:
3282  Out << "DSDRt";
3283  break;
3284  case BuiltinType::SatUFract:
3285  Out << "DSDRj";
3286  break;
3287  case BuiltinType::SatULongFract:
3288  Out << "DSDRm";
3289  break;
3290  case BuiltinType::Half:
3291  Out << "Dh";
3292  break;
3293  case BuiltinType::Float:
3294  Out << 'f';
3295  break;
3296  case BuiltinType::Double:
3297  Out << 'd';
3298  break;
3299  case BuiltinType::LongDouble: {
3300  const TargetInfo *TI =
3301  getASTContext().getLangOpts().OpenMP &&
3302  getASTContext().getLangOpts().OpenMPIsTargetDevice
3303  ? getASTContext().getAuxTargetInfo()
3304  : &getASTContext().getTargetInfo();
3305  Out << TI->getLongDoubleMangling();
3306  break;
3307  }
3308  case BuiltinType::Float128: {
3309  const TargetInfo *TI =
3310  getASTContext().getLangOpts().OpenMP &&
3311  getASTContext().getLangOpts().OpenMPIsTargetDevice
3312  ? getASTContext().getAuxTargetInfo()
3313  : &getASTContext().getTargetInfo();
3314  Out << TI->getFloat128Mangling();
3315  break;
3316  }
3317  case BuiltinType::BFloat16: {
3318  const TargetInfo *TI =
3319  ((getASTContext().getLangOpts().OpenMP &&
3320  getASTContext().getLangOpts().OpenMPIsTargetDevice) ||
3321  getASTContext().getLangOpts().SYCLIsDevice)
3322  ? getASTContext().getAuxTargetInfo()
3323  : &getASTContext().getTargetInfo();
3324  Out << TI->getBFloat16Mangling();
3325  break;
3326  }
3327  case BuiltinType::Ibm128: {
3328  const TargetInfo *TI = &getASTContext().getTargetInfo();
3329  Out << TI->getIbm128Mangling();
3330  break;
3331  }
3332  case BuiltinType::NullPtr:
3333  Out << "Dn";
3334  break;
3335 
3336 #define BUILTIN_TYPE(Id, SingletonId)
3337 #define PLACEHOLDER_TYPE(Id, SingletonId) \
3338  case BuiltinType::Id:
3339 #include "clang/AST/BuiltinTypes.def"
3340  case BuiltinType::Dependent:
3341  if (!NullOut)
3342  llvm_unreachable("mangling a placeholder type");
3343  break;
3344  case BuiltinType::ObjCId:
3345  Out << "11objc_object";
3346  break;
3347  case BuiltinType::ObjCClass:
3348  Out << "10objc_class";
3349  break;
3350  case BuiltinType::ObjCSel:
3351  Out << "13objc_selector";
3352  break;
3353 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3354  case BuiltinType::Id: \
3355  type_name = "ocl_" #ImgType "_" #Suffix; \
3356  Out << type_name.size() << type_name; \
3357  break;
3358 #include "clang/Basic/OpenCLImageTypes.def"
3359 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3360  case BuiltinType::Sampled##Id: \
3361  type_name = "__spirv_SampledImage__" #ImgType "_" #Suffix; \
3362  Out << type_name.size() << type_name; \
3363  break;
3364 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
3365 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
3366 #include "clang/Basic/OpenCLImageTypes.def"
3367  case BuiltinType::OCLSampler:
3368  Out << "11ocl_sampler";
3369  break;
3370  case BuiltinType::OCLEvent:
3371  Out << "9ocl_event";
3372  break;
3373  case BuiltinType::OCLClkEvent:
3374  Out << "12ocl_clkevent";
3375  break;
3376  case BuiltinType::OCLQueue:
3377  Out << "9ocl_queue";
3378  break;
3379  case BuiltinType::OCLReserveID:
3380  Out << "13ocl_reserveid";
3381  break;
3382 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3383  case BuiltinType::Id: \
3384  type_name = "ocl_" #ExtType; \
3385  Out << type_name.size() << type_name; \
3386  break;
3387 #include "clang/Basic/OpenCLExtensionTypes.def"
3388  // The SVE types are effectively target-specific. The mangling scheme
3389  // is defined in the appendices to the Procedure Call Standard for the
3390  // Arm Architecture.
3391 #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \
3392  ElBits, IsSigned, IsFP, IsBF) \
3393  case BuiltinType::Id: \
3394  if (T->getKind() == BuiltinType::SveBFloat16 && \
3395  isCompatibleWith(LangOptions::ClangABI::Ver17)) { \
3396  /* Prior to Clang 18.0 we used this incorrect mangled name */ \
3397  type_name = "__SVBFloat16_t"; \
3398  Out << "u" << type_name.size() << type_name; \
3399  } else { \
3400  type_name = MangledName; \
3401  Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3402  << type_name; \
3403  } \
3404  break;
3405 #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
3406  case BuiltinType::Id: \
3407  type_name = MangledName; \
3408  Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3409  << type_name; \
3410  break;
3411 #define SVE_OPAQUE_TYPE(InternalName, MangledName, Id, SingletonId) \
3412  case BuiltinType::Id: \
3413  type_name = MangledName; \
3414  Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3415  << type_name; \
3416  break;
3417 #include "clang/Basic/AArch64SVEACLETypes.def"
3418 #define PPC_VECTOR_TYPE(Name, Id, Size) \
3419  case BuiltinType::Id: \
3420  type_name = #Name; \
3421  Out << 'u' << type_name.size() << type_name; \
3422  break;
3423 #include "clang/Basic/PPCTypes.def"
3424  // TODO: Check the mangling scheme for RISC-V V.
3425 #define RVV_TYPE(Name, Id, SingletonId) \
3426  case BuiltinType::Id: \
3427  type_name = Name; \
3428  Out << 'u' << type_name.size() << type_name; \
3429  break;
3430 #include "clang/Basic/RISCVVTypes.def"
3431 #define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \
3432  case BuiltinType::Id: \
3433  type_name = MangledName; \
3434  Out << 'u' << type_name.size() << type_name; \
3435  break;
3436 #include "clang/Basic/WebAssemblyReferenceTypes.def"
3437 #define AMDGPU_TYPE(Name, Id, SingletonId) \
3438  case BuiltinType::Id: \
3439  type_name = Name; \
3440  Out << 'u' << type_name.size() << type_name; \
3441  break;
3442 #include "clang/Basic/AMDGPUTypes.def"
3443 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3444  case BuiltinType::Id: \
3445  type_name = #Name; \
3446  Out << 'u' << type_name.size() << type_name; \
3447  break;
3448 #include "clang/Basic/HLSLIntangibleTypes.def"
3449  }
3450 }
3451 
3452 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3453  switch (CC) {
3454  case CC_C:
3455  return "";
3456 
3457  case CC_X86VectorCall:
3458  case CC_X86Pascal:
3459  case CC_X86RegCall:
3460  case CC_AAPCS:
3461  case CC_AAPCS_VFP:
3462  case CC_AArch64VectorCall:
3463  case CC_AArch64SVEPCS:
3464  case CC_AMDGPUKernelCall:
3465  case CC_IntelOclBicc:
3466  case CC_SpirFunction:
3467  case CC_OpenCLKernel:
3468  case CC_PreserveMost:
3469  case CC_PreserveAll:
3470  case CC_M68kRTD:
3471  case CC_PreserveNone:
3472  case CC_RISCVVectorCall:
3473  // FIXME: we should be mangling all of the above.
3474  return "";
3475 
3476  case CC_X86ThisCall:
3477  // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3478  // used explicitly. At this point, we don't have that much information in
3479  // the AST, since clang tends to bake the convention into the canonical
3480  // function type. thiscall only rarely used explicitly, so don't mangle it
3481  // for now.
3482  return "";
3483 
3484  case CC_X86StdCall:
3485  return "stdcall";
3486  case CC_X86FastCall:
3487  return "fastcall";
3488  case CC_X86_64SysV:
3489  return "sysv_abi";
3490  case CC_Win64:
3491  return "ms_abi";
3492  case CC_Swift:
3493  return "swiftcall";
3494  case CC_SwiftAsync:
3495  return "swiftasynccall";
3496  }
3497  llvm_unreachable("bad calling convention");
3498 }
3499 
3500 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3501  // Fast path.
3502  if (T->getExtInfo() == FunctionType::ExtInfo())
3503  return;
3504 
3505  // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3506  // This will get more complicated in the future if we mangle other
3507  // things here; but for now, since we mangle ns_returns_retained as
3508  // a qualifier on the result type, we can get away with this:
3509  StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
3510  if (!CCQualifier.empty())
3511  mangleVendorQualifier(CCQualifier);
3512 
3513  // FIXME: regparm
3514  // FIXME: noreturn
3515 }
3516 
3517 void
3518 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3519  // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3520 
3521  // Note that these are *not* substitution candidates. Demanglers might
3522  // have trouble with this if the parameter type is fully substituted.
3523 
3524  switch (PI.getABI()) {
3526  break;
3527 
3528  // All of these start with "swift", so they come before "ns_consumed".
3533  mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3534  break;
3535  }
3536 
3537  if (PI.isConsumed())
3538  mangleVendorQualifier("ns_consumed");
3539 
3540  if (PI.isNoEscape())
3541  mangleVendorQualifier("noescape");
3542 }
3543 
3544 // <type> ::= <function-type>
3545 // <function-type> ::= [<CV-qualifiers>] F [Y]
3546 // <bare-function-type> [<ref-qualifier>] E
3547 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3548  mangleExtFunctionInfo(T);
3549 
3550  // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3551  // e.g. "const" in "int (A::*)() const".
3552  mangleQualifiers(T->getMethodQuals());
3553 
3554  // Mangle instantiation-dependent exception-specification, if present,
3555  // per cxx-abi-dev proposal on 2016-10-11.
3558  Out << "DO";
3559  mangleExpression(T->getNoexceptExpr());
3560  Out << "E";
3561  } else {
3562  assert(T->getExceptionSpecType() == EST_Dynamic);
3563  Out << "Dw";
3564  for (auto ExceptTy : T->exceptions())
3565  mangleType(ExceptTy);
3566  Out << "E";
3567  }
3568  } else if (T->isNothrow()) {
3569  Out << "Do";
3570  }
3571 
3572  Out << 'F';
3573 
3574  // FIXME: We don't have enough information in the AST to produce the 'Y'
3575  // encoding for extern "C" function types.
3576  mangleBareFunctionType(T, /*MangleReturnType=*/true);
3577 
3578  // Mangle the ref-qualifier, if present.
3579  mangleRefQualifier(T->getRefQualifier());
3580 
3581  Out << 'E';
3582 }
3583 
3584 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3585  // Function types without prototypes can arise when mangling a function type
3586  // within an overloadable function in C. We mangle these as the absence of any
3587  // parameter types (not even an empty parameter list).
3588  Out << 'F';
3589 
3590  FunctionTypeDepthState saved = FunctionTypeDepth.push();
3591 
3592  FunctionTypeDepth.enterResultType();
3593  mangleType(T->getReturnType());
3594  FunctionTypeDepth.leaveResultType();
3595 
3596  FunctionTypeDepth.pop(saved);
3597  Out << 'E';
3598 }
3599 
3600 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3601  bool MangleReturnType,
3602  const FunctionDecl *FD) {
3603  // Record that we're in a function type. See mangleFunctionParam
3604  // for details on what we're trying to achieve here.
3605  FunctionTypeDepthState saved = FunctionTypeDepth.push();
3606 
3607  // <bare-function-type> ::= <signature type>+
3608  if (MangleReturnType) {
3609  FunctionTypeDepth.enterResultType();
3610 
3611  // Mangle ns_returns_retained as an order-sensitive qualifier here.
3612  if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3613  mangleVendorQualifier("ns_returns_retained");
3614 
3615  // Mangle the return type without any direct ARC ownership qualifiers.
3616  QualType ReturnTy = Proto->getReturnType();
3617  if (ReturnTy.getObjCLifetime()) {
3618  auto SplitReturnTy = ReturnTy.split();
3619  SplitReturnTy.Quals.removeObjCLifetime();
3620  ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3621  }
3622  mangleType(ReturnTy);
3623 
3624  FunctionTypeDepth.leaveResultType();
3625  }
3626 
3627  if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3628  // <builtin-type> ::= v # void
3629  Out << 'v';
3630  } else {
3631  assert(!FD || FD->getNumParams() == Proto->getNumParams());
3632  for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3633  // Mangle extended parameter info as order-sensitive qualifiers here.
3634  if (Proto->hasExtParameterInfos() && FD == nullptr) {
3635  mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3636  }
3637 
3638  // Mangle the type.
3639  QualType ParamTy = Proto->getParamType(I);
3640  mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3641 
3642  if (FD) {
3643  if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3644  // Attr can only take 1 character, so we can hardcode the length
3645  // below.
3646  assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3647  if (Attr->isDynamic())
3648  Out << "U25pass_dynamic_object_size" << Attr->getType();
3649  else
3650  Out << "U17pass_object_size" << Attr->getType();
3651  }
3652  }
3653  }
3654 
3655  // <builtin-type> ::= z # ellipsis
3656  if (Proto->isVariadic())
3657  Out << 'z';
3658  }
3659 
3660  if (FD) {
3661  FunctionTypeDepth.enterResultType();
3662  mangleRequiresClause(FD->getTrailingRequiresClause());
3663  }
3664 
3665  FunctionTypeDepth.pop(saved);
3666 }
3667 
3668 // <type> ::= <class-enum-type>
3669 // <class-enum-type> ::= <name>
3670 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3671  mangleName(T->getDecl());
3672 }
3673 
3674 // <type> ::= <class-enum-type>
3675 // <class-enum-type> ::= <name>
3676 void CXXNameMangler::mangleType(const EnumType *T) {
3677  mangleType(static_cast<const TagType*>(T));
3678 }
3679 void CXXNameMangler::mangleType(const RecordType *T) {
3680  mangleType(static_cast<const TagType*>(T));
3681 }
3682 void CXXNameMangler::mangleType(const TagType *T) {
3683  mangleName(T->getDecl());
3684 }
3685 
3686 // <type> ::= <array-type>
3687 // <array-type> ::= A <positive dimension number> _ <element type>
3688 // ::= A [<dimension expression>] _ <element type>
3689 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3690  Out << 'A' << T->getSize() << '_';
3691  mangleType(T->getElementType());
3692 }
3693 void CXXNameMangler::mangleType(const VariableArrayType *T) {
3694  Out << 'A';
3695  // decayed vla types (size 0) will just be skipped.
3696  if (T->getSizeExpr())
3697  mangleExpression(T->getSizeExpr());
3698  Out << '_';
3699  mangleType(T->getElementType());
3700 }
3701 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3702  Out << 'A';
3703  // A DependentSizedArrayType might not have size expression as below
3704  //
3705  // template<int ...N> int arr[] = {N...};
3706  if (T->getSizeExpr())
3707  mangleExpression(T->getSizeExpr());
3708  Out << '_';
3709  mangleType(T->getElementType());
3710 }
3711 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3712  Out << "A_";
3713  mangleType(T->getElementType());
3714 }
3715 
3716 // <type> ::= <pointer-to-member-type>
3717 // <pointer-to-member-type> ::= M <class type> <member type>
3718 void CXXNameMangler::mangleType(const MemberPointerType *T) {
3719  Out << 'M';
3720  mangleType(QualType(T->getClass(), 0));
3721  QualType PointeeType = T->getPointeeType();
3722  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3723  mangleType(FPT);
3724 
3725  // Itanium C++ ABI 5.1.8:
3726  //
3727  // The type of a non-static member function is considered to be different,
3728  // for the purposes of substitution, from the type of a namespace-scope or
3729  // static member function whose type appears similar. The types of two
3730  // non-static member functions are considered to be different, for the
3731  // purposes of substitution, if the functions are members of different
3732  // classes. In other words, for the purposes of substitution, the class of
3733  // which the function is a member is considered part of the type of
3734  // function.
3735 
3736  // Given that we already substitute member function pointers as a
3737  // whole, the net effect of this rule is just to unconditionally
3738  // suppress substitution on the function type in a member pointer.
3739  // We increment the SeqID here to emulate adding an entry to the
3740  // substitution table.
3741  ++SeqID;
3742  } else
3743  mangleType(PointeeType);
3744 }
3745 
3746 // <type> ::= <template-param>
3747 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3748  mangleTemplateParameter(T->getDepth(), T->getIndex());
3749 }
3750 
3751 // <type> ::= <template-param>
3752 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3753  // FIXME: not clear how to mangle this!
3754  // template <class T...> class A {
3755  // template <class U...> void foo(T(*)(U) x...);
3756  // };
3757  Out << "_SUBSTPACK_";
3758 }
3759 
3760 // <type> ::= P <type> # pointer-to
3761 void CXXNameMangler::mangleType(const PointerType *T) {
3762  Out << 'P';
3763  mangleType(T->getPointeeType());
3764 }
3765 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3766  Out << 'P';
3767  mangleType(T->getPointeeType());
3768 }
3769 
3770 // <type> ::= R <type> # reference-to
3771 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3772  Out << 'R';
3773  mangleType(T->getPointeeType());
3774 }
3775 
3776 // <type> ::= O <type> # rvalue reference-to (C++0x)
3777 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3778  Out << 'O';
3779  mangleType(T->getPointeeType());
3780 }
3781 
3782 // <type> ::= C <type> # complex pair (C 2000)
3783 void CXXNameMangler::mangleType(const ComplexType *T) {
3784  Out << 'C';
3785  mangleType(T->getElementType());
3786 }
3787 
3788 // ARM's ABI for Neon vector types specifies that they should be mangled as
3789 // if they are structs (to match ARM's initial implementation). The
3790 // vector type must be one of the special types predefined by ARM.
3791 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3792  QualType EltType = T->getElementType();
3793  assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3794  const char *EltName = nullptr;
3795  if (T->getVectorKind() == VectorKind::NeonPoly) {
3796  switch (cast<BuiltinType>(EltType)->getKind()) {
3797  case BuiltinType::SChar:
3798  case BuiltinType::UChar:
3799  EltName = "poly8_t";
3800  break;
3801  case BuiltinType::Short:
3802  case BuiltinType::UShort:
3803  EltName = "poly16_t";
3804  break;
3805  case BuiltinType::LongLong:
3806  case BuiltinType::ULongLong:
3807  EltName = "poly64_t";
3808  break;
3809  default: llvm_unreachable("unexpected Neon polynomial vector element type");
3810  }
3811  } else {
3812  switch (cast<BuiltinType>(EltType)->getKind()) {
3813  case BuiltinType::SChar: EltName = "int8_t"; break;
3814  case BuiltinType::UChar: EltName = "uint8_t"; break;
3815  case BuiltinType::Short: EltName = "int16_t"; break;
3816  case BuiltinType::UShort: EltName = "uint16_t"; break;
3817  case BuiltinType::Int: EltName = "int32_t"; break;
3818  case BuiltinType::UInt: EltName = "uint32_t"; break;
3819  case BuiltinType::LongLong: EltName = "int64_t"; break;
3820  case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3821  case BuiltinType::Double: EltName = "float64_t"; break;
3822  case BuiltinType::Float: EltName = "float32_t"; break;
3823  case BuiltinType::Half: EltName = "float16_t"; break;
3824  case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
3825  default:
3826  llvm_unreachable("unexpected Neon vector element type");
3827  }
3828  }
3829  const char *BaseName = nullptr;
3830  unsigned BitSize = (T->getNumElements() *
3831  getASTContext().getTypeSize(EltType));
3832  if (BitSize == 64)
3833  BaseName = "__simd64_";
3834  else {
3835  assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3836  BaseName = "__simd128_";
3837  }
3838  Out << strlen(BaseName) + strlen(EltName);
3839  Out << BaseName << EltName;
3840 }
3841 
3842 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3843  DiagnosticsEngine &Diags = Context.getDiags();
3844  unsigned DiagID = Diags.getCustomDiagID(
3846  "cannot mangle this dependent neon vector type yet");
3847  Diags.Report(T->getAttributeLoc(), DiagID);
3848 }
3849 
3850 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3851  switch (EltType->getKind()) {
3852  case BuiltinType::SChar:
3853  return "Int8";
3854  case BuiltinType::Short:
3855  return "Int16";
3856  case BuiltinType::Int:
3857  return "Int32";
3858  case BuiltinType::Long:
3859  case BuiltinType::LongLong:
3860  return "Int64";
3861  case BuiltinType::UChar:
3862  return "Uint8";
3863  case BuiltinType::UShort:
3864  return "Uint16";
3865  case BuiltinType::UInt:
3866  return "Uint32";
3867  case BuiltinType::ULong:
3868  case BuiltinType::ULongLong:
3869  return "Uint64";
3870  case BuiltinType::Half:
3871  return "Float16";
3872  case BuiltinType::Float:
3873  return "Float32";
3874  case BuiltinType::Double:
3875  return "Float64";
3876  case BuiltinType::BFloat16:
3877  return "Bfloat16";
3878  default:
3879  llvm_unreachable("Unexpected vector element base type");
3880  }
3881 }
3882 
3883 // AArch64's ABI for Neon vector types specifies that they should be mangled as
3884 // the equivalent internal name. The vector type must be one of the special
3885 // types predefined by ARM.
3886 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3887  QualType EltType = T->getElementType();
3888  assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3889  unsigned BitSize =
3890  (T->getNumElements() * getASTContext().getTypeSize(EltType));
3891  (void)BitSize; // Silence warning.
3892 
3893  assert((BitSize == 64 || BitSize == 128) &&
3894  "Neon vector type not 64 or 128 bits");
3895 
3896  StringRef EltName;
3897  if (T->getVectorKind() == VectorKind::NeonPoly) {
3898  switch (cast<BuiltinType>(EltType)->getKind()) {
3899  case BuiltinType::UChar:
3900  EltName = "Poly8";
3901  break;
3902  case BuiltinType::UShort:
3903  EltName = "Poly16";
3904  break;
3905  case BuiltinType::ULong:
3906  case BuiltinType::ULongLong:
3907  EltName = "Poly64";
3908  break;
3909  default:
3910  llvm_unreachable("unexpected Neon polynomial vector element type");
3911  }
3912  } else
3913  EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3914 
3915  std::string TypeName =
3916  ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3917  Out << TypeName.length() << TypeName;
3918 }
3919 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3920  DiagnosticsEngine &Diags = Context.getDiags();
3921  unsigned DiagID = Diags.getCustomDiagID(
3923  "cannot mangle this dependent neon vector type yet");
3924  Diags.Report(T->getAttributeLoc(), DiagID);
3925 }
3926 
3927 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3928 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3929 // type as the sizeless variants.
3930 //
3931 // The mangling scheme for VLS types is implemented as a "pseudo" template:
3932 //
3933 // '__SVE_VLS<<type>, <vector length>>'
3934 //
3935 // Combining the existing SVE type and a specific vector length (in bits).
3936 // For example:
3937 //
3938 // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3939 //
3940 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3941 //
3942 // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3943 //
3944 // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3945 //
3946 // The latest ACLE specification (00bet5) does not contain details of this
3947 // mangling scheme, it will be specified in the next revision. The mangling
3948 // scheme is otherwise defined in the appendices to the Procedure Call Standard
3949 // for the Arm Architecture, see
3950 // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
3951 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
3952  assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||
3953  T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
3954  "expected fixed-length SVE vector!");
3955 
3956  QualType EltType = T->getElementType();
3957  assert(EltType->isBuiltinType() &&
3958  "expected builtin type for fixed-length SVE vector!");
3959 
3960  StringRef TypeName;
3961  switch (cast<BuiltinType>(EltType)->getKind()) {
3962  case BuiltinType::SChar:
3963  TypeName = "__SVInt8_t";
3964  break;
3965  case BuiltinType::UChar: {
3966  if (T->getVectorKind() == VectorKind::SveFixedLengthData)
3967  TypeName = "__SVUint8_t";
3968  else
3969  TypeName = "__SVBool_t";
3970  break;
3971  }
3972  case BuiltinType::Short:
3973  TypeName = "__SVInt16_t";
3974  break;
3975  case BuiltinType::UShort:
3976  TypeName = "__SVUint16_t";
3977  break;
3978  case BuiltinType::Int:
3979  TypeName = "__SVInt32_t";
3980  break;
3981  case BuiltinType::UInt:
3982  TypeName = "__SVUint32_t";
3983  break;
3984  case BuiltinType::Long:
3985  TypeName = "__SVInt64_t";
3986  break;
3987  case BuiltinType::ULong:
3988  TypeName = "__SVUint64_t";
3989  break;
3990  case BuiltinType::Half:
3991  TypeName = "__SVFloat16_t";
3992  break;
3993  case BuiltinType::Float:
3994  TypeName = "__SVFloat32_t";
3995  break;
3996  case BuiltinType::Double:
3997  TypeName = "__SVFloat64_t";
3998  break;
3999  case BuiltinType::BFloat16:
4000  TypeName = "__SVBfloat16_t";
4001  break;
4002  default:
4003  llvm_unreachable("unexpected element type for fixed-length SVE vector!");
4004  }
4005 
4006  unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4007 
4008  if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)
4009  VecSizeInBits *= 8;
4010 
4011  Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
4012  << VecSizeInBits << "EE";
4013 }
4014 
4015 void CXXNameMangler::mangleAArch64FixedSveVectorType(
4016  const DependentVectorType *T) {
4017  DiagnosticsEngine &Diags = Context.getDiags();
4018  unsigned DiagID = Diags.getCustomDiagID(
4020  "cannot mangle this dependent fixed-length SVE vector type yet");
4021  Diags.Report(T->getAttributeLoc(), DiagID);
4022 }
4023 
4024 void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {
4025  assert((T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4026  T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4027  T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4028  T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4029  T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) &&
4030  "expected fixed-length RVV vector!");
4031 
4032  QualType EltType = T->getElementType();
4033  assert(EltType->isBuiltinType() &&
4034  "expected builtin type for fixed-length RVV vector!");
4035 
4036  SmallString<20> TypeNameStr;
4037  llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
4038  TypeNameOS << "__rvv_";
4039  switch (cast<BuiltinType>(EltType)->getKind()) {
4040  case BuiltinType::SChar:
4041  TypeNameOS << "int8";
4042  break;
4043  case BuiltinType::UChar:
4044  if (T->getVectorKind() == VectorKind::RVVFixedLengthData)
4045  TypeNameOS << "uint8";
4046  else
4047  TypeNameOS << "bool";
4048  break;
4049  case BuiltinType::Short:
4050  TypeNameOS << "int16";
4051  break;
4052  case BuiltinType::UShort:
4053  TypeNameOS << "uint16";
4054  break;
4055  case BuiltinType::Int:
4056  TypeNameOS << "int32";
4057  break;
4058  case BuiltinType::UInt:
4059  TypeNameOS << "uint32";
4060  break;
4061  case BuiltinType::Long:
4062  TypeNameOS << "int64";
4063  break;
4064  case BuiltinType::ULong:
4065  TypeNameOS << "uint64";
4066  break;
4067  case BuiltinType::Float16:
4068  TypeNameOS << "float16";
4069  break;
4070  case BuiltinType::Float:
4071  TypeNameOS << "float32";
4072  break;
4073  case BuiltinType::Double:
4074  TypeNameOS << "float64";
4075  break;
4076  default:
4077  llvm_unreachable("unexpected element type for fixed-length RVV vector!");
4078  }
4079 
4080  unsigned VecSizeInBits;
4081  switch (T->getVectorKind()) {
4083  VecSizeInBits = 1;
4084  break;
4086  VecSizeInBits = 2;
4087  break;
4089  VecSizeInBits = 4;
4090  break;
4091  default:
4092  VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4093  break;
4094  }
4095 
4096  // Apend the LMUL suffix.
4097  auto VScale = getASTContext().getTargetInfo().getVScaleRange(
4098  getASTContext().getLangOpts());
4099  unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;
4100 
4101  if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4102  TypeNameOS << 'm';
4103  if (VecSizeInBits >= VLen)
4104  TypeNameOS << (VecSizeInBits / VLen);
4105  else
4106  TypeNameOS << 'f' << (VLen / VecSizeInBits);
4107  } else {
4108  TypeNameOS << (VLen / VecSizeInBits);
4109  }
4110  TypeNameOS << "_t";
4111 
4112  Out << "9__RVV_VLSI" << 'u' << TypeNameStr.size() << TypeNameStr << "Lj"
4113  << VecSizeInBits << "EE";
4114 }
4115 
4116 void CXXNameMangler::mangleRISCVFixedRVVVectorType(
4117  const DependentVectorType *T) {
4118  DiagnosticsEngine &Diags = Context.getDiags();
4119  unsigned DiagID = Diags.getCustomDiagID(
4121  "cannot mangle this dependent fixed-length RVV vector type yet");
4122  Diags.Report(T->getAttributeLoc(), DiagID);
4123 }
4124 
4125 // GNU extension: vector types
4126 // <type> ::= <vector-type>
4127 // <vector-type> ::= Dv <positive dimension number> _
4128 // <extended element type>
4129 // ::= Dv [<dimension expression>] _ <element type>
4130 // <extended element type> ::= <element type>
4131 // ::= p # AltiVec vector pixel
4132 // ::= b # Altivec vector bool
4133 void CXXNameMangler::mangleType(const VectorType *T) {
4134  if ((T->getVectorKind() == VectorKind::Neon ||
4135  T->getVectorKind() == VectorKind::NeonPoly)) {
4136  llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4137  llvm::Triple::ArchType Arch =
4138  getASTContext().getTargetInfo().getTriple().getArch();
4139  if ((Arch == llvm::Triple::aarch64 ||
4140  Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
4141  mangleAArch64NeonVectorType(T);
4142  else
4143  mangleNeonVectorType(T);
4144  return;
4145  } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4146  T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4147  mangleAArch64FixedSveVectorType(T);
4148  return;
4149  } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4150  T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4151  T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4152  T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4153  T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
4154  mangleRISCVFixedRVVVectorType(T);
4155  return;
4156  }
4157  Out << "Dv" << T->getNumElements() << '_';
4158  if (T->getVectorKind() == VectorKind::AltiVecPixel)
4159  Out << 'p';
4160  else if (T->getVectorKind() == VectorKind::AltiVecBool)
4161  Out << 'b';
4162  else
4163  mangleType(T->getElementType());
4164 }
4165 
4166 void CXXNameMangler::mangleType(const DependentVectorType *T) {
4167  if ((T->getVectorKind() == VectorKind::Neon ||
4168  T->getVectorKind() == VectorKind::NeonPoly)) {
4169  llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4170  llvm::Triple::ArchType Arch =
4171  getASTContext().getTargetInfo().getTriple().getArch();
4172  if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
4173  !Target.isOSDarwin())
4174  mangleAArch64NeonVectorType(T);
4175  else
4176  mangleNeonVectorType(T);
4177  return;
4178  } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4179  T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4180  mangleAArch64FixedSveVectorType(T);
4181  return;
4182  } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4183  mangleRISCVFixedRVVVectorType(T);
4184  return;
4185  }
4186 
4187  Out << "Dv";
4188  mangleExpression(T->getSizeExpr());
4189  Out << '_';
4190  if (T->getVectorKind() == VectorKind::AltiVecPixel)
4191  Out << 'p';
4192  else if (T->getVectorKind() == VectorKind::AltiVecBool)
4193  Out << 'b';
4194  else
4195  mangleType(T->getElementType());
4196 }
4197 
4198 void CXXNameMangler::mangleType(const ExtVectorType *T) {
4199  mangleType(static_cast<const VectorType*>(T));
4200 }
4201 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
4202  Out << "Dv";
4203  mangleExpression(T->getSizeExpr());
4204  Out << '_';
4205  mangleType(T->getElementType());
4206 }
4207 
4208 void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
4209  // Mangle matrix types as a vendor extended type:
4210  // u<Len>matrix_typeI<Rows><Columns><element type>E
4211 
4212  StringRef VendorQualifier = "matrix_type";
4213  Out << "u" << VendorQualifier.size() << VendorQualifier;
4214 
4215  Out << "I";
4216  auto &ASTCtx = getASTContext();
4217  unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
4218  llvm::APSInt Rows(BitWidth);
4219  Rows = T->getNumRows();
4220  mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
4221  llvm::APSInt Columns(BitWidth);
4222  Columns = T->getNumColumns();
4223  mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
4224  mangleType(T->getElementType());
4225  Out << "E";
4226 }
4227 
4228 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
4229  // Mangle matrix types as a vendor extended type:
4230  // u<Len>matrix_typeI<row expr><column expr><element type>E
4231  StringRef VendorQualifier = "matrix_type";
4232  Out << "u" << VendorQualifier.size() << VendorQualifier;
4233 
4234  Out << "I";
4235  mangleTemplateArgExpr(T->getRowExpr());
4236  mangleTemplateArgExpr(T->getColumnExpr());
4237  mangleType(T->getElementType());
4238  Out << "E";
4239 }
4240 
4241 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
4242  SplitQualType split = T->getPointeeType().split();
4243  mangleQualifiers(split.Quals, T);
4244  mangleType(QualType(split.Ty, 0));
4245 }
4246 
4247 void CXXNameMangler::mangleType(const PackExpansionType *T) {
4248  // <type> ::= Dp <type> # pack expansion (C++0x)
4249  Out << "Dp";
4250  mangleType(T->getPattern());
4251 }
4252 
4253 void CXXNameMangler::mangleType(const PackIndexingType *T) {
4254  if (!T->hasSelectedType())
4255  mangleType(T->getPattern());
4256  else
4257  mangleType(T->getSelectedType());
4258 }
4259 
4260 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
4261  mangleSourceName(T->getDecl()->getIdentifier());
4262 }
4263 
4264 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
4265  // Treat __kindof as a vendor extended type qualifier.
4266  if (T->isKindOfType())
4267  Out << "U8__kindof";
4268 
4269  if (!T->qual_empty()) {
4270  // Mangle protocol qualifiers.
4271  SmallString<64> QualStr;
4272  llvm::raw_svector_ostream QualOS(QualStr);
4273  QualOS << "objcproto";
4274  for (const auto *I : T->quals()) {
4275  StringRef name = I->getName();
4276  QualOS << name.size() << name;
4277  }
4278  Out << 'U' << QualStr.size() << QualStr;
4279  }
4280 
4281  mangleType(T->getBaseType());
4282 
4283  if (T->isSpecialized()) {
4284  // Mangle type arguments as I <type>+ E
4285  Out << 'I';
4286  for (auto typeArg : T->getTypeArgs())
4287  mangleType(typeArg);
4288  Out << 'E';
4289  }
4290 }
4291 
4292 void CXXNameMangler::mangleType(const BlockPointerType *T) {
4293  Out << "U13block_pointer";
4294  mangleType(T->getPointeeType());
4295 }
4296 
4297 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
4298  // Mangle injected class name types as if the user had written the
4299  // specialization out fully. It may not actually be possible to see
4300  // this mangling, though.
4301  mangleType(T->getInjectedSpecializationType());
4302 }
4303 
4304 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
4305  if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
4306  mangleTemplateName(TD, T->template_arguments());
4307  } else {
4308  if (mangleSubstitution(QualType(T, 0)))
4309  return;
4310 
4311  mangleTemplatePrefix(T->getTemplateName());
4312 
4313  // FIXME: GCC does not appear to mangle the template arguments when
4314  // the template in question is a dependent template name. Should we
4315  // emulate that badness?
4316  mangleTemplateArgs(T->getTemplateName(), T->template_arguments());
4317  addSubstitution(QualType(T, 0));
4318  }
4319 }
4320 
4321 void CXXNameMangler::mangleType(const DependentNameType *T) {
4322  // Proposal by cxx-abi-dev, 2014-03-26
4323  // <class-enum-type> ::= <name> # non-dependent or dependent type name or
4324  // # dependent elaborated type specifier using
4325  // # 'typename'
4326  // ::= Ts <name> # dependent elaborated type specifier using
4327  // # 'struct' or 'class'
4328  // ::= Tu <name> # dependent elaborated type specifier using
4329  // # 'union'
4330  // ::= Te <name> # dependent elaborated type specifier using
4331  // # 'enum'
4332  switch (T->getKeyword()) {
4335  break;
4339  Out << "Ts";
4340  break;
4342  Out << "Tu";
4343  break;
4345  Out << "Te";
4346  break;
4347  }
4348  // Typename types are always nested
4349  Out << 'N';
4350  manglePrefix(T->getQualifier());
4351  mangleSourceName(T->getIdentifier());
4352  Out << 'E';
4353 }
4354 
4355 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
4356  // Dependently-scoped template types are nested if they have a prefix.
4357  Out << 'N';
4358 
4359  // TODO: avoid making this TemplateName.
4360  TemplateName Prefix =
4361  getASTContext().getDependentTemplateName(T->getQualifier(),
4362  T->getIdentifier());
4363  mangleTemplatePrefix(Prefix);
4364 
4365  // FIXME: GCC does not appear to mangle the template arguments when
4366  // the template in question is a dependent template name. Should we
4367  // emulate that badness?
4368  mangleTemplateArgs(Prefix, T->template_arguments());
4369  Out << 'E';
4370 }
4371 
4372 void CXXNameMangler::mangleType(const TypeOfType *T) {
4373  // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4374  // "extension with parameters" mangling.
4375  Out << "u6typeof";
4376 }
4377 
4378 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
4379  // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4380  // "extension with parameters" mangling.
4381  Out << "u6typeof";
4382 }
4383 
4384 void CXXNameMangler::mangleType(const DecltypeType *T) {
4385  Expr *E = T->getUnderlyingExpr();
4386 
4387  // type ::= Dt <expression> E # decltype of an id-expression
4388  // # or class member access
4389  // ::= DT <expression> E # decltype of an expression
4390 
4391  // This purports to be an exhaustive list of id-expressions and
4392  // class member accesses. Note that we do not ignore parentheses;
4393  // parentheses change the semantics of decltype for these
4394  // expressions (and cause the mangler to use the other form).
4395  if (isa<DeclRefExpr>(E) ||
4396  isa<MemberExpr>(E) ||
4397  isa<UnresolvedLookupExpr>(E) ||
4398  isa<DependentScopeDeclRefExpr>(E) ||
4399  isa<CXXDependentScopeMemberExpr>(E) ||
4400  isa<UnresolvedMemberExpr>(E))
4401  Out << "Dt";
4402  else
4403  Out << "DT";
4404  mangleExpression(E);
4405  Out << 'E';
4406 }
4407 
4408 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
4409  // If this is dependent, we need to record that. If not, we simply
4410  // mangle it as the underlying type since they are equivalent.
4411  if (T->isDependentType()) {
4412  Out << "u";
4413 
4414  StringRef BuiltinName;
4415  switch (T->getUTTKind()) {
4416 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
4417  case UnaryTransformType::Enum: \
4418  BuiltinName = "__" #Trait; \
4419  break;
4420 #include "clang/Basic/TransformTypeTraits.def"
4421  }
4422  Out << BuiltinName.size() << BuiltinName;
4423  }
4424 
4425  Out << "I";
4426  mangleType(T->getBaseType());
4427  Out << "E";
4428 }
4429 
4430 void CXXNameMangler::mangleType(const AutoType *T) {
4431  assert(T->getDeducedType().isNull() &&
4432  "Deduced AutoType shouldn't be handled here!");
4433  assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
4434  "shouldn't need to mangle __auto_type!");
4435  // <builtin-type> ::= Da # auto
4436  // ::= Dc # decltype(auto)
4437  // ::= Dk # constrained auto
4438  // ::= DK # constrained decltype(auto)
4439  if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
4440  Out << (T->isDecltypeAuto() ? "DK" : "Dk");
4441  mangleTypeConstraint(T->getTypeConstraintConcept(),
4442  T->getTypeConstraintArguments());
4443  } else {
4444  Out << (T->isDecltypeAuto() ? "Dc" : "Da");
4445  }
4446 }
4447 
4448 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4449  QualType Deduced = T->getDeducedType();
4450  if (!Deduced.isNull())
4451  return mangleType(Deduced);
4452 
4453  TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
4454  assert(TD && "shouldn't form deduced TST unless we know we have a template");
4455 
4456  if (mangleSubstitution(TD))
4457  return;
4458 
4459  mangleName(GlobalDecl(TD));
4460  addSubstitution(TD);
4461 }
4462 
4463 void CXXNameMangler::mangleType(const AtomicType *T) {
4464  // <type> ::= U <source-name> <type> # vendor extended type qualifier
4465  // (Until there's a standardized mangling...)
4466  Out << "U7_Atomic";
4467  mangleType(T->getValueType());
4468 }
4469 
4470 void CXXNameMangler::mangleType(const PipeType *T) {
4471  // Pipe type mangling rules are described in SPIR 2.0 specification
4472  // A.1 Data types and A.3 Summary of changes
4473  // <type> ::= 8ocl_pipe
4474  Out << "8ocl_pipe";
4475 }
4476 
4477 void CXXNameMangler::mangleType(const BitIntType *T) {
4478  // 5.1.5.2 Builtin types
4479  // <type> ::= DB <number | instantiation-dependent expression> _
4480  // ::= DU <number | instantiation-dependent expression> _
4481  Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4482 }
4483 
4484 void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4485  // 5.1.5.2 Builtin types
4486  // <type> ::= DB <number | instantiation-dependent expression> _
4487  // ::= DU <number | instantiation-dependent expression> _
4488  Out << "D" << (T->isUnsigned() ? "U" : "B");
4489  mangleExpression(T->getNumBitsExpr());
4490  Out << "_";
4491 }
4492 
4493 void CXXNameMangler::mangleType(const ArrayParameterType *T) {
4494  mangleType(cast<ConstantArrayType>(T));
4495 }
4496 
4497 void CXXNameMangler::mangleIntegerLiteral(QualType T,
4498  const llvm::APSInt &Value) {
4499  // <expr-primary> ::= L <type> <value number> E # integer literal
4500  Out << 'L';
4501 
4502  mangleType(T);
4503  if (T->isBooleanType()) {
4504  // Boolean values are encoded as 0/1.
4505  Out << (Value.getBoolValue() ? '1' : '0');
4506  } else {
4507  mangleNumber(Value);
4508  }
4509  Out << 'E';
4510 
4511 }
4512 
4513 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4514  // Ignore member expressions involving anonymous unions.
4515  while (const auto *RT = Base->getType()->getAs<RecordType>()) {
4516  if (!RT->getDecl()->isAnonymousStructOrUnion())
4517  break;
4518  const auto *ME = dyn_cast<MemberExpr>(Base);
4519  if (!ME)
4520  break;
4521  Base = ME->getBase();
4522  IsArrow = ME->isArrow();
4523  }
4524 
4525  if (Base->isImplicitCXXThis()) {
4526  // Note: GCC mangles member expressions to the implicit 'this' as
4527  // *this., whereas we represent them as this->. The Itanium C++ ABI
4528  // does not specify anything here, so we follow GCC.
4529  Out << "dtdefpT";
4530  } else {
4531  Out << (IsArrow ? "pt" : "dt");
4532  mangleExpression(Base);
4533  }
4534 }
4535 
4536 /// Mangles a member expression.
4537 void CXXNameMangler::mangleMemberExpr(const Expr *base,
4538  bool isArrow,
4539  NestedNameSpecifier *qualifier,
4540  NamedDecl *firstQualifierLookup,
4542  const TemplateArgumentLoc *TemplateArgs,
4543  unsigned NumTemplateArgs,
4544  unsigned arity) {
4545  // <expression> ::= dt <expression> <unresolved-name>
4546  // ::= pt <expression> <unresolved-name>
4547  if (base)
4548  mangleMemberExprBase(base, isArrow);
4549  mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
4550 }
4551 
4552 /// Look at the callee of the given call expression and determine if
4553 /// it's a parenthesized id-expression which would have triggered ADL
4554 /// otherwise.
4555 static bool isParenthesizedADLCallee(const CallExpr *call) {
4556  const Expr *callee = call->getCallee();
4557  const Expr *fn = callee->IgnoreParens();
4558 
4559  // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4560  // too, but for those to appear in the callee, it would have to be
4561  // parenthesized.
4562  if (callee == fn) return false;
4563 
4564  // Must be an unresolved lookup.
4565  const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
4566  if (!lookup) return false;
4567 
4568  assert(!lookup->requiresADL());
4569 
4570  // Must be an unqualified lookup.
4571  if (lookup->getQualifier()) return false;
4572 
4573  // Must not have found a class member. Note that if one is a class
4574  // member, they're all class members.
4575  if (lookup->getNumDecls() > 0 &&
4576  (*lookup->decls_begin())->isCXXClassMember())
4577  return false;
4578 
4579  // Otherwise, ADL would have been triggered.
4580  return true;
4581 }
4582 
4583 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4584  const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
4585  Out << CastEncoding;
4586  mangleType(ECE->getType());
4587  mangleExpression(ECE->getSubExpr());
4588 }
4589 
4590 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
4591  if (auto *Syntactic = InitList->getSyntacticForm())
4592  InitList = Syntactic;
4593  for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
4594  mangleExpression(InitList->getInit(i));
4595 }
4596 
4597 void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc,
4598  const concepts::Requirement *Req) {
4599  using concepts::Requirement;
4600 
4601  // TODO: We can't mangle the result of a failed substitution. It's not clear
4602  // whether we should be mangling the original form prior to any substitution
4603  // instead. See https://lists.isocpp.org/core/2023/04/14118.php
4604  auto HandleSubstitutionFailure =
4605  [&](SourceLocation Loc) {
4606  DiagnosticsEngine &Diags = Context.getDiags();
4607  unsigned DiagID = Diags.getCustomDiagID(
4608  DiagnosticsEngine::Error, "cannot mangle this requires-expression "
4609  "containing a substitution failure");
4610  Diags.Report(Loc, DiagID);
4611  Out << 'F';
4612  };
4613 
4614  switch (Req->getKind()) {
4615  case Requirement::RK_Type: {
4616  const auto *TR = cast<concepts::TypeRequirement>(Req);
4617  if (TR->isSubstitutionFailure())
4618  return HandleSubstitutionFailure(
4619  TR->getSubstitutionDiagnostic()->DiagLoc);
4620 
4621  Out << 'T';
4622  mangleType(TR->getType()->getType());
4623  break;
4624  }
4625 
4626  case Requirement::RK_Simple:
4627  case Requirement::RK_Compound: {
4628  const auto *ER = cast<concepts::ExprRequirement>(Req);
4629  if (ER->isExprSubstitutionFailure())
4630  return HandleSubstitutionFailure(
4631  ER->getExprSubstitutionDiagnostic()->DiagLoc);
4632 
4633  Out << 'X';
4634  mangleExpression(ER->getExpr());
4635 
4636  if (ER->hasNoexceptRequirement())
4637  Out << 'N';
4638 
4639  if (!ER->getReturnTypeRequirement().isEmpty()) {
4640  if (ER->getReturnTypeRequirement().isSubstitutionFailure())
4641  return HandleSubstitutionFailure(ER->getReturnTypeRequirement()
4642  .getSubstitutionDiagnostic()
4643  ->DiagLoc);
4644 
4645  Out << 'R';
4646  mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());
4647  }
4648  break;
4649  }
4650 
4651  case Requirement::RK_Nested:
4652  const auto *NR = cast<concepts::NestedRequirement>(Req);
4653  if (NR->hasInvalidConstraint()) {
4654  // FIXME: NestedRequirement should track the location of its requires
4655  // keyword.
4656  return HandleSubstitutionFailure(RequiresExprLoc);
4657  }
4658 
4659  Out << 'Q';
4660  mangleExpression(NR->getConstraintExpr());
4661  break;
4662  }
4663 }
4664 
4665 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4666  bool AsTemplateArg) {
4667  // <expression> ::= <unary operator-name> <expression>
4668  // ::= <binary operator-name> <expression> <expression>
4669  // ::= <trinary operator-name> <expression> <expression> <expression>
4670  // ::= cv <type> expression # conversion with one argument
4671  // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4672  // ::= dc <type> <expression> # dynamic_cast<type> (expression)
4673  // ::= sc <type> <expression> # static_cast<type> (expression)
4674  // ::= cc <type> <expression> # const_cast<type> (expression)
4675  // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4676  // ::= st <type> # sizeof (a type)
4677  // ::= at <type> # alignof (a type)
4678  // ::= <template-param>
4679  // ::= <function-param>
4680  // ::= fpT # 'this' expression (part of <function-param>)
4681  // ::= sr <type> <unqualified-name> # dependent name
4682  // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
4683  // ::= ds <expression> <expression> # expr.*expr
4684  // ::= sZ <template-param> # size of a parameter pack
4685  // ::= sZ <function-param> # size of a function parameter pack
4686  // ::= u <source-name> <template-arg>* E # vendor extended expression
4687  // ::= <expr-primary>
4688  // <expr-primary> ::= L <type> <value number> E # integer literal
4689  // ::= L <type> <value float> E # floating literal
4690  // ::= L <type> <string type> E # string literal
4691  // ::= L <nullptr type> E # nullptr literal "LDnE"
4692  // ::= L <pointer type> 0 E # null pointer template argument
4693  // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
4694  // ::= L <mangled-name> E # external name
4695  QualType ImplicitlyConvertedToType;
4696 
4697  // A top-level expression that's not <expr-primary> needs to be wrapped in
4698  // X...E in a template arg.
4699  bool IsPrimaryExpr = true;
4700  auto NotPrimaryExpr = [&] {
4701  if (AsTemplateArg && IsPrimaryExpr)
4702  Out << 'X';
4703  IsPrimaryExpr = false;
4704  };
4705 
4706  auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4707  switch (D->getKind()) {
4708  default:
4709  // <expr-primary> ::= L <mangled-name> E # external name
4710  Out << 'L';
4711  mangle(D);
4712  Out << 'E';
4713  break;
4714 
4715  case Decl::ParmVar:
4716  NotPrimaryExpr();
4717  mangleFunctionParam(cast<ParmVarDecl>(D));
4718  break;
4719 
4720  case Decl::EnumConstant: {
4721  // <expr-primary>
4722  const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4723  mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4724  break;
4725  }
4726 
4727  case Decl::NonTypeTemplateParm:
4728  NotPrimaryExpr();
4729  const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4730  mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4731  break;
4732  }
4733  };
4734 
4735  // 'goto recurse' is used when handling a simple "unwrapping" node which
4736  // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4737  // to be preserved.
4738 recurse:
4739  switch (E->getStmtClass()) {
4740  case Expr::NoStmtClass:
4741 #define ABSTRACT_STMT(Type)
4742 #define EXPR(Type, Base)
4743 #define STMT(Type, Base) \
4744  case Expr::Type##Class:
4745 #include "clang/AST/StmtNodes.inc"
4746  // fallthrough
4747 
4748  // These all can only appear in local or variable-initialization
4749  // contexts and so should never appear in a mangling.
4750  case Expr::AddrLabelExprClass:
4751  case Expr::DesignatedInitUpdateExprClass:
4752  case Expr::ImplicitValueInitExprClass:
4753  case Expr::ArrayInitLoopExprClass:
4754  case Expr::ArrayInitIndexExprClass:
4755  case Expr::NoInitExprClass:
4756  case Expr::ParenListExprClass:
4757  case Expr::MSPropertyRefExprClass:
4758  case Expr::MSPropertySubscriptExprClass:
4759  case Expr::TypoExprClass: // This should no longer exist in the AST by now.
4760  case Expr::RecoveryExprClass:
4761  case Expr::ArraySectionExprClass:
4762  case Expr::OMPArrayShapingExprClass:
4763  case Expr::OMPIteratorExprClass:
4764  case Expr::CXXInheritedCtorInitExprClass:
4765  case Expr::CXXParenListInitExprClass:
4766  case Expr::PackIndexingExprClass:
4767  llvm_unreachable("unexpected statement kind");
4768 
4769  case Expr::ConstantExprClass:
4770  E = cast<ConstantExpr>(E)->getSubExpr();
4771  goto recurse;
4772 
4773  // FIXME: invent manglings for all these.
4774  case Expr::BlockExprClass:
4775  case Expr::ChooseExprClass:
4776  case Expr::CompoundLiteralExprClass:
4777  case Expr::ExtVectorElementExprClass:
4778  case Expr::GenericSelectionExprClass:
4779  case Expr::ObjCEncodeExprClass:
4780  case Expr::ObjCIsaExprClass:
4781  case Expr::ObjCIvarRefExprClass:
4782  case Expr::ObjCMessageExprClass:
4783  case Expr::ObjCPropertyRefExprClass:
4784  case Expr::ObjCProtocolExprClass:
4785  case Expr::ObjCSelectorExprClass:
4786  case Expr::ObjCStringLiteralClass:
4787  case Expr::ObjCBoxedExprClass:
4788  case Expr::ObjCArrayLiteralClass:
4789  case Expr::ObjCDictionaryLiteralClass:
4790  case Expr::ObjCSubscriptRefExprClass:
4791  case Expr::ObjCIndirectCopyRestoreExprClass:
4792  case Expr::ObjCAvailabilityCheckExprClass:
4793  case Expr::OffsetOfExprClass:
4794  case Expr::PredefinedExprClass:
4795  case Expr::ShuffleVectorExprClass:
4796  case Expr::ConvertVectorExprClass:
4797  case Expr::StmtExprClass:
4798  case Expr::ArrayTypeTraitExprClass:
4799  case Expr::ExpressionTraitExprClass:
4800  case Expr::VAArgExprClass:
4801  case Expr::CUDAKernelCallExprClass:
4802  case Expr::AsTypeExprClass:
4803  case Expr::PseudoObjectExprClass:
4804  case Expr::AtomicExprClass:
4805  case Expr::SourceLocExprClass:
4806  case Expr::EmbedExprClass:
4807  case Expr::BuiltinBitCastExprClass:
4808  case Expr::SYCLBuiltinNumFieldsExprClass:
4809  case Expr::SYCLBuiltinFieldTypeExprClass:
4810  case Expr::SYCLBuiltinNumBasesExprClass:
4811  case Expr::SYCLBuiltinBaseTypeExprClass:
4812  {
4813  NotPrimaryExpr();
4814  if (!NullOut) {
4815  // As bad as this diagnostic is, it's better than crashing.
4816  DiagnosticsEngine &Diags = Context.getDiags();
4817  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4818  "cannot yet mangle expression type %0");
4819  Diags.Report(E->getExprLoc(), DiagID)
4820  << E->getStmtClassName() << E->getSourceRange();
4821  return;
4822  }
4823  break;
4824  }
4825 
4826  case Expr::CXXUuidofExprClass: {
4827  NotPrimaryExpr();
4828  const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4829  // As of clang 12, uuidof uses the vendor extended expression
4830  // mangling. Previously, it used a special-cased nonstandard extension.
4831  if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
4832  Out << "u8__uuidof";
4833  if (UE->isTypeOperand())
4834  mangleType(UE->getTypeOperand(Context.getASTContext()));
4835  else
4836  mangleTemplateArgExpr(UE->getExprOperand());
4837  Out << 'E';
4838  } else {
4839  if (UE->isTypeOperand()) {
4840  QualType UuidT = UE->getTypeOperand(Context.getASTContext());
4841  Out << "u8__uuidoft";
4842  mangleType(UuidT);
4843  } else {
4844  Expr *UuidExp = UE->getExprOperand();
4845  Out << "u8__uuidofz";
4846  mangleExpression(UuidExp);
4847  }
4848  }
4849  break;
4850  }
4851 
4852  // Even gcc-4.5 doesn't mangle this.
4853  case Expr::BinaryConditionalOperatorClass: {
4854  NotPrimaryExpr();
4855  DiagnosticsEngine &Diags = Context.getDiags();
4856  unsigned DiagID =
4858  "?: operator with omitted middle operand cannot be mangled");
4859  Diags.Report(E->getExprLoc(), DiagID)
4860  << E->getStmtClassName() << E->getSourceRange();
4861  return;
4862  }
4863 
4864  // These are used for internal purposes and cannot be meaningfully mangled.
4865  case Expr::OpaqueValueExprClass:
4866  llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
4867 
4868  case Expr::InitListExprClass: {
4869  NotPrimaryExpr();
4870  Out << "il";
4871  mangleInitListElements(cast<InitListExpr>(E));
4872  Out << "E";
4873  break;
4874  }
4875 
4876  case Expr::DesignatedInitExprClass: {
4877  NotPrimaryExpr();
4878  auto *DIE = cast<DesignatedInitExpr>(E);
4879  for (const auto &Designator : DIE->designators()) {
4880  if (Designator.isFieldDesignator()) {
4881  Out << "di";
4882  mangleSourceName(Designator.getFieldName());
4883  } else if (Designator.isArrayDesignator()) {
4884  Out << "dx";
4885  mangleExpression(DIE->getArrayIndex(Designator));
4886  } else {
4888  "unknown designator kind");
4889  Out << "dX";
4890  mangleExpression(DIE->getArrayRangeStart(Designator));
4891  mangleExpression(DIE->getArrayRangeEnd(Designator));
4892  }
4893  }
4894  mangleExpression(DIE->getInit());
4895  break;
4896  }
4897 
4898  case Expr::CXXDefaultArgExprClass:
4899  E = cast<CXXDefaultArgExpr>(E)->getExpr();
4900  goto recurse;
4901 
4902  case Expr::CXXDefaultInitExprClass:
4903  E = cast<CXXDefaultInitExpr>(E)->getExpr();
4904  goto recurse;
4905 
4906  case Expr::CXXStdInitializerListExprClass:
4907  E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
4908  goto recurse;
4909 
4910  case Expr::SubstNonTypeTemplateParmExprClass: {
4911  // Mangle a substituted parameter the same way we mangle the template
4912  // argument.
4913  auto *SNTTPE = cast<SubstNonTypeTemplateParmExpr>(E);
4914  if (auto *CE = dyn_cast<ConstantExpr>(SNTTPE->getReplacement())) {
4915  // Pull out the constant value and mangle it as a template argument.
4916  QualType ParamType = SNTTPE->getParameterType(Context.getASTContext());
4917  assert(CE->hasAPValueResult() && "expected the NTTP to have an APValue");
4918  mangleValueInTemplateArg(ParamType, CE->getAPValueResult(), false,
4919  /*NeedExactType=*/true);
4920  break;
4921  }
4922  // The remaining cases all happen to be substituted with expressions that
4923  // mangle the same as a corresponding template argument anyway.
4924  E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
4925  goto recurse;
4926  }
4927 
4928  case Expr::UserDefinedLiteralClass:
4929  // We follow g++'s approach of mangling a UDL as a call to the literal
4930  // operator.
4931  case Expr::CXXMemberCallExprClass: // fallthrough
4932  case Expr::CallExprClass: {
4933  NotPrimaryExpr();
4934  const CallExpr *CE = cast<CallExpr>(E);
4935 
4936  // <expression> ::= cp <simple-id> <expression>* E
4937  // We use this mangling only when the call would use ADL except
4938  // for being parenthesized. Per discussion with David
4939  // Vandervoorde, 2011.04.25.
4940  if (isParenthesizedADLCallee(CE)) {
4941  Out << "cp";
4942  // The callee here is a parenthesized UnresolvedLookupExpr with
4943  // no qualifier and should always get mangled as a <simple-id>
4944  // anyway.
4945 
4946  // <expression> ::= cl <expression>* E
4947  } else {
4948  Out << "cl";
4949  }
4950 
4951  unsigned CallArity = CE->getNumArgs();
4952  for (const Expr *Arg : CE->arguments())
4953  if (isa<PackExpansionExpr>(Arg))
4954  CallArity = UnknownArity;
4955 
4956  mangleExpression(CE->getCallee(), CallArity);
4957  for (const Expr *Arg : CE->arguments())
4958  mangleExpression(Arg);
4959  Out << 'E';
4960  break;
4961  }
4962 
4963  case Expr::CXXNewExprClass: {
4964  NotPrimaryExpr();
4965  const CXXNewExpr *New = cast<CXXNewExpr>(E);
4966  if (New->isGlobalNew()) Out << "gs";
4967  Out << (New->isArray() ? "na" : "nw");
4969  E = New->placement_arg_end(); I != E; ++I)
4970  mangleExpression(*I);
4971  Out << '_';
4972  mangleType(New->getAllocatedType());
4973  if (New->hasInitializer()) {
4975  Out << "il";
4976  else
4977  Out << "pi";
4978  const Expr *Init = New->getInitializer();
4979  if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
4980  // Directly inline the initializers.
4981  for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
4982  E = CCE->arg_end();
4983  I != E; ++I)
4984  mangleExpression(*I);
4985  } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
4986  for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
4987  mangleExpression(PLE->getExpr(i));
4988  } else if (New->getInitializationStyle() ==
4990  isa<InitListExpr>(Init)) {
4991  // Only take InitListExprs apart for list-initialization.
4992  mangleInitListElements(cast<InitListExpr>(Init));
4993  } else
4994  mangleExpression(Init);
4995  }
4996  Out << 'E';
4997  break;
4998  }
4999 
5000  case Expr::CXXPseudoDestructorExprClass: {
5001  NotPrimaryExpr();
5002  const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
5003  if (const Expr *Base = PDE->getBase())
5004  mangleMemberExprBase(Base, PDE->isArrow());
5005  NestedNameSpecifier *Qualifier = PDE->getQualifier();
5006  if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
5007  if (Qualifier) {
5008  mangleUnresolvedPrefix(Qualifier,
5009  /*recursive=*/true);
5010  mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
5011  Out << 'E';
5012  } else {
5013  Out << "sr";
5014  if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
5015  Out << 'E';
5016  }
5017  } else if (Qualifier) {
5018  mangleUnresolvedPrefix(Qualifier);
5019  }
5020  // <base-unresolved-name> ::= dn <destructor-name>
5021  Out << "dn";
5022  QualType DestroyedType = PDE->getDestroyedType();
5023  mangleUnresolvedTypeOrSimpleId(DestroyedType);
5024  break;
5025  }
5026 
5027  case Expr::MemberExprClass: {
5028  NotPrimaryExpr();
5029  const MemberExpr *ME = cast<MemberExpr>(E);
5030  mangleMemberExpr(ME->getBase(), ME->isArrow(),
5031  ME->getQualifier(), nullptr,
5032  ME->getMemberDecl()->getDeclName(),
5033  ME->getTemplateArgs(), ME->getNumTemplateArgs(),
5034  Arity);
5035  break;
5036  }
5037 
5038  case Expr::UnresolvedMemberExprClass: {
5039  NotPrimaryExpr();
5040  const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
5041  mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
5042  ME->isArrow(), ME->getQualifier(), nullptr,
5043  ME->getMemberName(),
5044  ME->getTemplateArgs(), ME->getNumTemplateArgs(),
5045  Arity);
5046  break;
5047  }
5048 
5049  case Expr::CXXDependentScopeMemberExprClass: {
5050  NotPrimaryExpr();
5051  const CXXDependentScopeMemberExpr *ME
5052  = cast<CXXDependentScopeMemberExpr>(E);
5053  mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
5054  ME->isArrow(), ME->getQualifier(),
5056  ME->getMember(),
5057  ME->getTemplateArgs(), ME->getNumTemplateArgs(),
5058  Arity);
5059  break;
5060  }
5061 
5062  case Expr::UnresolvedLookupExprClass: {
5063  NotPrimaryExpr();
5064  const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
5065  mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
5066  ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
5067  Arity);
5068  break;
5069  }
5070 
5071  case Expr::CXXUnresolvedConstructExprClass: {
5072  NotPrimaryExpr();
5073  const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
5074  unsigned N = CE->getNumArgs();
5075 
5076  if (CE->isListInitialization()) {
5077  assert(N == 1 && "unexpected form for list initialization");
5078  auto *IL = cast<InitListExpr>(CE->getArg(0));
5079  Out << "tl";
5080  mangleType(CE->getType());
5081  mangleInitListElements(IL);
5082  Out << "E";
5083  break;
5084  }
5085 
5086  Out << "cv";
5087  mangleType(CE->getType());
5088  if (N != 1) Out << '_';
5089  for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
5090  if (N != 1) Out << 'E';
5091  break;
5092  }
5093 
5094  case Expr::CXXConstructExprClass: {
5095  // An implicit cast is silent, thus may contain <expr-primary>.
5096  const auto *CE = cast<CXXConstructExpr>(E);
5097  if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
5098  assert(
5099  CE->getNumArgs() >= 1 &&
5100  (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
5101  "implicit CXXConstructExpr must have one argument");
5102  E = cast<CXXConstructExpr>(E)->getArg(0);
5103  goto recurse;
5104  }
5105  NotPrimaryExpr();
5106  Out << "il";
5107  for (auto *E : CE->arguments())
5108  mangleExpression(E);
5109  Out << "E";
5110  break;
5111  }
5112 
5113  case Expr::CXXTemporaryObjectExprClass: {
5114  NotPrimaryExpr();
5115  const auto *CE = cast<CXXTemporaryObjectExpr>(E);
5116  unsigned N = CE->getNumArgs();
5117  bool List = CE->isListInitialization();
5118 
5119  if (List)
5120  Out << "tl";
5121  else
5122  Out << "cv";
5123  mangleType(CE->getType());
5124  if (!List && N != 1)
5125  Out << '_';
5126  if (CE->isStdInitListInitialization()) {
5127  // We implicitly created a std::initializer_list<T> for the first argument
5128  // of a constructor of type U in an expression of the form U{a, b, c}.
5129  // Strip all the semantic gunk off the initializer list.
5130  auto *SILE =
5131  cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
5132  auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
5133  mangleInitListElements(ILE);
5134  } else {
5135  for (auto *E : CE->arguments())
5136  mangleExpression(E);
5137  }
5138  if (List || N != 1)
5139  Out << 'E';
5140  break;
5141  }
5142 
5143  case Expr::CXXScalarValueInitExprClass:
5144  NotPrimaryExpr();
5145  Out << "cv";
5146  mangleType(E->getType());
5147  Out << "_E";
5148  break;
5149 
5150  case Expr::CXXNoexceptExprClass:
5151  NotPrimaryExpr();
5152  Out << "nx";
5153  mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
5154  break;
5155 
5156  case Expr::UnaryExprOrTypeTraitExprClass: {
5157  // Non-instantiation-dependent traits are an <expr-primary> integer literal.
5158  const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
5159 
5160  if (!SAE->isInstantiationDependent()) {
5161  // Itanium C++ ABI:
5162  // If the operand of a sizeof or alignof operator is not
5163  // instantiation-dependent it is encoded as an integer literal
5164  // reflecting the result of the operator.
5165  //
5166  // If the result of the operator is implicitly converted to a known
5167  // integer type, that type is used for the literal; otherwise, the type
5168  // of std::size_t or std::ptrdiff_t is used.
5169  //
5170  // FIXME: We still include the operand in the profile in this case. This
5171  // can lead to mangling collisions between function templates that we
5172  // consider to be different.
5173  QualType T = (ImplicitlyConvertedToType.isNull() ||
5174  !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
5175  : ImplicitlyConvertedToType;
5176  llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
5177  mangleIntegerLiteral(T, V);
5178  break;
5179  }
5180 
5181  NotPrimaryExpr(); // But otherwise, they are not.
5182 
5183  auto MangleAlignofSizeofArg = [&] {
5184  if (SAE->isArgumentType()) {
5185  Out << 't';
5186  mangleType(SAE->getArgumentType());
5187  } else {
5188  Out << 'z';
5189  mangleExpression(SAE->getArgumentExpr());
5190  }
5191  };
5192 
5193  switch(SAE->getKind()) {
5194  case UETT_SizeOf:
5195  Out << 's';
5196  MangleAlignofSizeofArg();
5197  break;
5198  case UETT_PreferredAlignOf:
5199  // As of clang 12, we mangle __alignof__ differently than alignof. (They
5200  // have acted differently since Clang 8, but were previously mangled the
5201  // same.)
5202  if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
5203  Out << "u11__alignof__";
5204  if (SAE->isArgumentType())
5205  mangleType(SAE->getArgumentType());
5206  else
5207  mangleTemplateArgExpr(SAE->getArgumentExpr());
5208  Out << 'E';
5209  break;
5210  }
5211  [[fallthrough]];
5212  case UETT_AlignOf:
5213  Out << 'a';
5214  MangleAlignofSizeofArg();
5215  break;
5216  case UETT_DataSizeOf: {
5217  DiagnosticsEngine &Diags = Context.getDiags();
5218  unsigned DiagID =
5220  "cannot yet mangle __datasizeof expression");
5221  Diags.Report(DiagID);
5222  return;
5223  }
5224  case UETT_PtrAuthTypeDiscriminator: {
5225  DiagnosticsEngine &Diags = Context.getDiags();
5226  unsigned DiagID = Diags.getCustomDiagID(
5228  "cannot yet mangle __builtin_ptrauth_type_discriminator expression");
5229  Diags.Report(E->getExprLoc(), DiagID);
5230  return;
5231  }
5232  case UETT_VecStep: {
5233  DiagnosticsEngine &Diags = Context.getDiags();
5234  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
5235  "cannot yet mangle vec_step expression");
5236  Diags.Report(DiagID);
5237  return;
5238  }
5239  case UETT_OpenMPRequiredSimdAlign: {
5240  DiagnosticsEngine &Diags = Context.getDiags();
5241  unsigned DiagID = Diags.getCustomDiagID(
5243  "cannot yet mangle __builtin_omp_required_simd_align expression");
5244  Diags.Report(DiagID);
5245  return;
5246  }
5247  case UETT_VectorElements: {
5248  DiagnosticsEngine &Diags = Context.getDiags();
5249  unsigned DiagID = Diags.getCustomDiagID(
5251  "cannot yet mangle __builtin_vectorelements expression");
5252  Diags.Report(DiagID);
5253  return;
5254  }
5255  }
5256  break;
5257  }
5258 
5259  case Expr::TypeTraitExprClass: {
5260  // <expression> ::= u <source-name> <template-arg>* E # vendor extension
5261  const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);
5262  NotPrimaryExpr();
5263  Out << 'u';
5264  llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());
5265  Out << Spelling.size() << Spelling;
5266  for (TypeSourceInfo *TSI : TTE->getArgs()) {
5267  mangleType(TSI->getType());
5268  }
5269  Out << 'E';
5270  break;
5271  }
5272 
5273  case Expr::CXXThrowExprClass: {
5274  NotPrimaryExpr();
5275  const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
5276  // <expression> ::= tw <expression> # throw expression
5277  // ::= tr # rethrow
5278  if (TE->getSubExpr()) {
5279  Out << "tw";
5280  mangleExpression(TE->getSubExpr());
5281  } else {
5282  Out << "tr";
5283  }
5284  break;
5285  }
5286 
5287  case Expr::CXXTypeidExprClass: {
5288  NotPrimaryExpr();
5289  const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
5290  // <expression> ::= ti <type> # typeid (type)
5291  // ::= te <expression> # typeid (expression)
5292  if (TIE->isTypeOperand()) {
5293  Out << "ti";
5294  mangleType(TIE->getTypeOperand(Context.getASTContext()));
5295  } else {
5296  Out << "te";
5297  mangleExpression(TIE->getExprOperand());
5298  }
5299  break;
5300  }
5301 
5302  case Expr::CXXDeleteExprClass: {
5303  NotPrimaryExpr();
5304  const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
5305  // <expression> ::= [gs] dl <expression> # [::] delete expr
5306  // ::= [gs] da <expression> # [::] delete [] expr
5307  if (DE->isGlobalDelete()) Out << "gs";
5308  Out << (DE->isArrayForm() ? "da" : "dl");
5309  mangleExpression(DE->getArgument());
5310  break;
5311  }
5312 
5313  case Expr::UnaryOperatorClass: {
5314  NotPrimaryExpr();
5315  const UnaryOperator *UO = cast<UnaryOperator>(E);
5316  mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
5317  /*Arity=*/1);
5318  mangleExpression(UO->getSubExpr());
5319  break;
5320  }
5321 
5322  case Expr::ArraySubscriptExprClass: {
5323  NotPrimaryExpr();
5324  const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
5325 
5326  // Array subscript is treated as a syntactically weird form of
5327  // binary operator.
5328  Out << "ix";
5329  mangleExpression(AE->getLHS());
5330  mangleExpression(AE->getRHS());
5331  break;
5332  }
5333 
5334  case Expr::MatrixSubscriptExprClass: {
5335  NotPrimaryExpr();
5336  const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
5337  Out << "ixix";
5338  mangleExpression(ME->getBase());
5339  mangleExpression(ME->getRowIdx());
5340  mangleExpression(ME->getColumnIdx());
5341  break;
5342  }
5343 
5344  case Expr::CompoundAssignOperatorClass: // fallthrough
5345  case Expr::BinaryOperatorClass: {
5346  NotPrimaryExpr();
5347  const BinaryOperator *BO = cast<BinaryOperator>(E);
5348  if (BO->getOpcode() == BO_PtrMemD)
5349  Out << "ds";
5350  else
5351  mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
5352  /*Arity=*/2);
5353  mangleExpression(BO->getLHS());
5354  mangleExpression(BO->getRHS());
5355  break;
5356  }
5357 
5358  case Expr::CXXRewrittenBinaryOperatorClass: {
5359  NotPrimaryExpr();
5360  // The mangled form represents the original syntax.
5362  cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
5363  mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
5364  /*Arity=*/2);
5365  mangleExpression(Decomposed.LHS);
5366  mangleExpression(Decomposed.RHS);
5367  break;
5368  }
5369 
5370  case Expr::ConditionalOperatorClass: {
5371  NotPrimaryExpr();
5372  const ConditionalOperator *CO = cast<ConditionalOperator>(E);
5373  mangleOperatorName(OO_Conditional, /*Arity=*/3);
5374  mangleExpression(CO->getCond());
5375  mangleExpression(CO->getLHS(), Arity);
5376  mangleExpression(CO->getRHS(), Arity);
5377  break;
5378  }
5379 
5380  case Expr::ImplicitCastExprClass: {
5381  ImplicitlyConvertedToType = E->getType();
5382  E = cast<ImplicitCastExpr>(E)->getSubExpr();
5383  goto recurse;
5384  }
5385 
5386  case Expr::ObjCBridgedCastExprClass: {
5387  NotPrimaryExpr();
5388  // Mangle ownership casts as a vendor extended operator __bridge,
5389  // __bridge_transfer, or __bridge_retain.
5390  StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
5391  Out << "v1U" << Kind.size() << Kind;
5392  mangleCastExpression(E, "cv");
5393  break;
5394  }
5395 
5396  case Expr::CStyleCastExprClass:
5397  NotPrimaryExpr();
5398  mangleCastExpression(E, "cv");
5399  break;
5400 
5401  case Expr::CXXFunctionalCastExprClass: {
5402  NotPrimaryExpr();
5403  auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
5404  // FIXME: Add isImplicit to CXXConstructExpr.
5405  if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
5406  if (CCE->getParenOrBraceRange().isInvalid())
5407  Sub = CCE->getArg(0)->IgnoreImplicit();
5408  if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
5409  Sub = StdInitList->getSubExpr()->IgnoreImplicit();
5410  if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
5411  Out << "tl";
5412  mangleType(E->getType());
5413  mangleInitListElements(IL);
5414  Out << "E";
5415  } else {
5416  mangleCastExpression(E, "cv");
5417  }
5418  break;
5419  }
5420 
5421  case Expr::CXXStaticCastExprClass:
5422  NotPrimaryExpr();
5423  mangleCastExpression(E, "sc");
5424  break;
5425  case Expr::CXXDynamicCastExprClass:
5426  NotPrimaryExpr();
5427  mangleCastExpression(E, "dc");
5428  break;
5429  case Expr::CXXReinterpretCastExprClass:
5430  NotPrimaryExpr();
5431  mangleCastExpression(E, "rc");
5432  break;
5433  case Expr::CXXConstCastExprClass:
5434  NotPrimaryExpr();
5435  mangleCastExpression(E, "cc");
5436  break;
5437  case Expr::CXXAddrspaceCastExprClass:
5438  NotPrimaryExpr();
5439  mangleCastExpression(E, "ac");
5440  break;
5441 
5442  case Expr::CXXOperatorCallExprClass: {
5443  NotPrimaryExpr();
5444  const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
5445  unsigned NumArgs = CE->getNumArgs();
5446  // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
5447  // (the enclosing MemberExpr covers the syntactic portion).
5448  if (CE->getOperator() != OO_Arrow)
5449  mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
5450  // Mangle the arguments.
5451  for (unsigned i = 0; i != NumArgs; ++i)
5452  mangleExpression(CE->getArg(i));
5453  break;
5454  }
5455 
5456  case Expr::ParenExprClass:
5457  E = cast<ParenExpr>(E)->getSubExpr();
5458  goto recurse;
5459 
5460  case Expr::ConceptSpecializationExprClass: {
5461  auto *CSE = cast<ConceptSpecializationExpr>(E);
5462  if (isCompatibleWith(LangOptions::ClangABI::Ver17)) {
5463  // Clang 17 and before mangled concept-ids as if they resolved to an
5464  // entity, meaning that references to enclosing template arguments don't
5465  // work.
5466  Out << "L_Z";
5467  mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
5468  Out << 'E';
5469  break;
5470  }
5471  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5472  NotPrimaryExpr();
5473  mangleUnresolvedName(
5474  CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
5475  CSE->getConceptNameInfo().getName(),
5476  CSE->getTemplateArgsAsWritten()->getTemplateArgs(),
5477  CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());
5478  break;
5479  }
5480 
5481  case Expr::RequiresExprClass: {
5482  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5483  auto *RE = cast<RequiresExpr>(E);
5484  // This is a primary-expression in the C++ grammar, but does not have an
5485  // <expr-primary> mangling (starting with 'L').
5486  NotPrimaryExpr();
5487  if (RE->getLParenLoc().isValid()) {
5488  Out << "rQ";
5489  FunctionTypeDepthState saved = FunctionTypeDepth.push();
5490  if (RE->getLocalParameters().empty()) {
5491  Out << 'v';
5492  } else {
5493  for (ParmVarDecl *Param : RE->getLocalParameters()) {
5494  mangleType(Context.getASTContext().getSignatureParameterType(
5495  Param->getType()));
5496  }
5497  }
5498  Out << '_';
5499 
5500  // The rest of the mangling is in the immediate scope of the parameters.
5501  FunctionTypeDepth.enterResultType();
5502  for (const concepts::Requirement *Req : RE->getRequirements())
5503  mangleRequirement(RE->getExprLoc(), Req);
5504  FunctionTypeDepth.pop(saved);
5505  Out << 'E';
5506  } else {
5507  Out << "rq";
5508  for (const concepts::Requirement *Req : RE->getRequirements())
5509  mangleRequirement(RE->getExprLoc(), Req);
5510  Out << 'E';
5511  }
5512  break;
5513  }
5514 
5515  case Expr::DeclRefExprClass:
5516  // MangleDeclRefExpr helper handles primary-vs-nonprimary
5517  MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
5518  break;
5519 
5520  case Expr::SubstNonTypeTemplateParmPackExprClass:
5521  NotPrimaryExpr();
5522  // FIXME: not clear how to mangle this!
5523  // template <unsigned N...> class A {
5524  // template <class U...> void foo(U (&x)[N]...);
5525  // };
5526  Out << "_SUBSTPACK_";
5527  break;
5528 
5529  case Expr::FunctionParmPackExprClass: {
5530  NotPrimaryExpr();
5531  // FIXME: not clear how to mangle this!
5532  const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
5533  Out << "v110_SUBSTPACK";
5534  MangleDeclRefExpr(FPPE->getParameterPack());
5535  break;
5536  }
5537 
5538  case Expr::DependentScopeDeclRefExprClass: {
5539  NotPrimaryExpr();
5540  const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
5541  mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
5542  DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
5543  Arity);
5544  break;
5545  }
5546 
5547  case Expr::CXXBindTemporaryExprClass:
5548  E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
5549  goto recurse;
5550 
5551  case Expr::ExprWithCleanupsClass:
5552  E = cast<ExprWithCleanups>(E)->getSubExpr();
5553  goto recurse;
5554 
5555  case Expr::FloatingLiteralClass: {
5556  // <expr-primary>
5557  const FloatingLiteral *FL = cast<FloatingLiteral>(E);
5558  mangleFloatLiteral(FL->getType(), FL->getValue());
5559  break;
5560  }
5561 
5562  case Expr::FixedPointLiteralClass:
5563  // Currently unimplemented -- might be <expr-primary> in future?
5564  mangleFixedPointLiteral();
5565  break;
5566 
5567  case Expr::CharacterLiteralClass:
5568  // <expr-primary>
5569  Out << 'L';
5570  mangleType(E->getType());
5571  Out << cast<CharacterLiteral>(E)->getValue();
5572  Out << 'E';
5573  break;
5574 
5575  // FIXME. __objc_yes/__objc_no are mangled same as true/false
5576  case Expr::ObjCBoolLiteralExprClass:
5577  // <expr-primary>
5578  Out << "Lb";
5579  Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5580  Out << 'E';
5581  break;
5582 
5583  case Expr::CXXBoolLiteralExprClass:
5584  // <expr-primary>
5585  Out << "Lb";
5586  Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5587  Out << 'E';
5588  break;
5589 
5590  case Expr::IntegerLiteralClass: {
5591  // <expr-primary>
5592  llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
5593  if (E->getType()->isSignedIntegerType())
5594  Value.setIsSigned(true);
5595  mangleIntegerLiteral(E->getType(), Value);
5596  break;
5597  }
5598 
5599  case Expr::ImaginaryLiteralClass: {
5600  // <expr-primary>
5601  const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
5602  // Mangle as if a complex literal.
5603  // Proposal from David Vandevoorde, 2010.06.30.
5604  Out << 'L';
5605  mangleType(E->getType());
5606  if (const FloatingLiteral *Imag =
5607  dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
5608  // Mangle a floating-point zero of the appropriate type.
5609  mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
5610  Out << '_';
5611  mangleFloat(Imag->getValue());
5612  } else {
5613  Out << "0_";
5614  llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
5615  if (IE->getSubExpr()->getType()->isSignedIntegerType())
5616  Value.setIsSigned(true);
5617  mangleNumber(Value);
5618  }
5619  Out << 'E';
5620  break;
5621  }
5622 
5623  case Expr::StringLiteralClass: {
5624  // <expr-primary>
5625  // Revised proposal from David Vandervoorde, 2010.07.15.
5626  Out << 'L';
5627  assert(isa<ConstantArrayType>(E->getType()));
5628  mangleType(E->getType());
5629  Out << 'E';
5630  break;
5631  }
5632 
5633  case Expr::GNUNullExprClass:
5634  // <expr-primary>
5635  // Mangle as if an integer literal 0.
5636  mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
5637  break;
5638 
5639  case Expr::CXXNullPtrLiteralExprClass: {
5640  // <expr-primary>
5641  Out << "LDnE";
5642  break;
5643  }
5644 
5645  case Expr::LambdaExprClass: {
5646  // A lambda-expression can't appear in the signature of an
5647  // externally-visible declaration, so there's no standard mangling for
5648  // this, but mangling as a literal of the closure type seems reasonable.
5649  Out << "L";
5650  mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
5651  Out << "E";
5652  break;
5653  }
5654 
5655  case Expr::PackExpansionExprClass:
5656  NotPrimaryExpr();
5657  Out << "sp";
5658  mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
5659  break;
5660 
5661  case Expr::SizeOfPackExprClass: {
5662  NotPrimaryExpr();
5663  auto *SPE = cast<SizeOfPackExpr>(E);
5664  if (SPE->isPartiallySubstituted()) {
5665  Out << "sP";
5666  for (const auto &A : SPE->getPartialArguments())
5667  mangleTemplateArg(A, false);
5668  Out << "E";
5669  break;
5670  }
5671 
5672  Out << "sZ";
5673  const NamedDecl *Pack = SPE->getPack();
5674  if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
5675  mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
5676  else if (const NonTypeTemplateParmDecl *NTTP
5677  = dyn_cast<NonTypeTemplateParmDecl>(Pack))
5678  mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
5679  else if (const TemplateTemplateParmDecl *TempTP
5680  = dyn_cast<TemplateTemplateParmDecl>(Pack))
5681  mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
5682  else
5683  mangleFunctionParam(cast<ParmVarDecl>(Pack));
5684  break;
5685  }
5686 
5687  case Expr::MaterializeTemporaryExprClass:
5688  E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5689  goto recurse;
5690 
5691  case Expr::CXXFoldExprClass: {
5692  NotPrimaryExpr();
5693  auto *FE = cast<CXXFoldExpr>(E);
5694  if (FE->isLeftFold())
5695  Out << (FE->getInit() ? "fL" : "fl");
5696  else
5697  Out << (FE->getInit() ? "fR" : "fr");
5698 
5699  if (FE->getOperator() == BO_PtrMemD)
5700  Out << "ds";
5701  else
5702  mangleOperatorName(
5703  BinaryOperator::getOverloadedOperator(FE->getOperator()),
5704  /*Arity=*/2);
5705 
5706  if (FE->getLHS())
5707  mangleExpression(FE->getLHS());
5708  if (FE->getRHS())
5709  mangleExpression(FE->getRHS());
5710  break;
5711  }
5712 
5713  case Expr::CXXThisExprClass:
5714  NotPrimaryExpr();
5715  Out << "fpT";
5716  break;
5717 
5718  case Expr::CoawaitExprClass:
5719  // FIXME: Propose a non-vendor mangling.
5720  NotPrimaryExpr();
5721  Out << "v18co_await";
5722  mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5723  break;
5724 
5725  case Expr::DependentCoawaitExprClass:
5726  // FIXME: Propose a non-vendor mangling.
5727  NotPrimaryExpr();
5728  Out << "v18co_await";
5729  mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
5730  break;
5731 
5732  case Expr::CoyieldExprClass:
5733  // FIXME: Propose a non-vendor mangling.
5734  NotPrimaryExpr();
5735  Out << "v18co_yield";
5736  mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5737  break;
5738  case Expr::SYCLUniqueStableNameExprClass: {
5739  const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
5740  NotPrimaryExpr();
5741 
5742  Out << "u33__builtin_sycl_unique_stable_name";
5743  mangleType(USN->getTypeSourceInfo()->getType());
5744 
5745  Out << "E";
5746  break;
5747  }
5748  case Expr::SYCLUniqueStableIdExprClass: {
5749  const auto *USID = cast<SYCLUniqueStableIdExpr>(E);
5750  NotPrimaryExpr();
5751 
5752  Out << "cl31__builtin_sycl_unique_stable_id";
5753  mangleExpression(USID->getExpr());
5754  Out << "E";
5755  break;
5756  }
5757  }
5758 
5759  if (AsTemplateArg && !IsPrimaryExpr)
5760  Out << 'E';
5761 }
5762 
5763 /// Mangle an expression which refers to a parameter variable.
5764 ///
5765 /// <expression> ::= <function-param>
5766 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
5767 /// <function-param> ::= fp <top-level CV-qualifiers>
5768 /// <parameter-2 non-negative number> _ # L == 0, I > 0
5769 /// <function-param> ::= fL <L-1 non-negative number>
5770 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
5771 /// <function-param> ::= fL <L-1 non-negative number>
5772 /// p <top-level CV-qualifiers>
5773 /// <I-1 non-negative number> _ # L > 0, I > 0
5774 ///
5775 /// L is the nesting depth of the parameter, defined as 1 if the
5776 /// parameter comes from the innermost function prototype scope
5777 /// enclosing the current context, 2 if from the next enclosing
5778 /// function prototype scope, and so on, with one special case: if
5779 /// we've processed the full parameter clause for the innermost
5780 /// function type, then L is one less. This definition conveniently
5781 /// makes it irrelevant whether a function's result type was written
5782 /// trailing or leading, but is otherwise overly complicated; the
5783 /// numbering was first designed without considering references to
5784 /// parameter in locations other than return types, and then the
5785 /// mangling had to be generalized without changing the existing
5786 /// manglings.
5787 ///
5788 /// I is the zero-based index of the parameter within its parameter
5789 /// declaration clause. Note that the original ABI document describes
5790 /// this using 1-based ordinals.
5791 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
5792  unsigned parmDepth = parm->getFunctionScopeDepth();
5793  unsigned parmIndex = parm->getFunctionScopeIndex();
5794 
5795  // Compute 'L'.
5796  // parmDepth does not include the declaring function prototype.
5797  // FunctionTypeDepth does account for that.
5798  assert(parmDepth < FunctionTypeDepth.getDepth());
5799  unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
5800  if (FunctionTypeDepth.isInResultType())
5801  nestingDepth--;
5802 
5803  if (nestingDepth == 0) {
5804  Out << "fp";
5805  } else {
5806  Out << "fL" << (nestingDepth - 1) << 'p';
5807  }
5808 
5809  // Top-level qualifiers. We don't have to worry about arrays here,
5810  // because parameters declared as arrays should already have been
5811  // transformed to have pointer type. FIXME: apparently these don't
5812  // get mangled if used as an rvalue of a known non-class type?
5813  assert(!parm->getType()->isArrayType()
5814  && "parameter's type is still an array type?");
5815 
5816  if (const DependentAddressSpaceType *DAST =
5817  dyn_cast<DependentAddressSpaceType>(parm->getType())) {
5818  mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
5819  } else {
5820  mangleQualifiers(parm->getType().getQualifiers());
5821  }
5822 
5823  // Parameter index.
5824  if (parmIndex != 0) {
5825  Out << (parmIndex - 1);
5826  }
5827  Out << '_';
5828 }
5829 
5830 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
5831  const CXXRecordDecl *InheritedFrom) {
5832  // <ctor-dtor-name> ::= C1 # complete object constructor
5833  // ::= C2 # base object constructor
5834  // ::= CI1 <type> # complete inheriting constructor
5835  // ::= CI2 <type> # base inheriting constructor
5836  //
5837  // In addition, C5 is a comdat name with C1 and C2 in it.
5838  Out << 'C';
5839  if (InheritedFrom)
5840  Out << 'I';
5841  switch (T) {
5842  case Ctor_Complete:
5843  Out << '1';
5844  break;
5845  case Ctor_Base:
5846  Out << '2';
5847  break;
5848  case Ctor_Comdat:
5849  Out << '5';
5850  break;
5851  case Ctor_DefaultClosure:
5852  case Ctor_CopyingClosure:
5853  llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
5854  }
5855  if (InheritedFrom)
5856  mangleName(InheritedFrom);
5857 }
5858 
5859 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
5860  // <ctor-dtor-name> ::= D0 # deleting destructor
5861  // ::= D1 # complete object destructor
5862  // ::= D2 # base object destructor
5863  //
5864  // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
5865  switch (T) {
5866  case Dtor_Deleting:
5867  Out << "D0";
5868  break;
5869  case Dtor_Complete:
5870  Out << "D1";
5871  break;
5872  case Dtor_Base:
5873  Out << "D2";
5874  break;
5875  case Dtor_Comdat:
5876  Out << "D5";
5877  break;
5878  }
5879 }
5880 
5881 // Helper to provide ancillary information on a template used to mangle its
5882 // arguments.
5884  const CXXNameMangler &Mangler;
5885  TemplateDecl *ResolvedTemplate = nullptr;
5886  bool SeenPackExpansionIntoNonPack = false;
5887  const NamedDecl *UnresolvedExpandedPack = nullptr;
5888 
5889  TemplateArgManglingInfo(const CXXNameMangler &Mangler, TemplateName TN)
5890  : Mangler(Mangler) {
5891  if (TemplateDecl *TD = TN.getAsTemplateDecl())
5892  ResolvedTemplate = TD;
5893  }
5894 
5895  /// Information about how to mangle a template argument.
5896  struct Info {
5897  /// Do we need to mangle the template argument with an exactly correct type?
5899  /// If we need to prefix the mangling with a mangling of the template
5900  /// parameter, the corresponding parameter.
5902  };
5903 
5904  /// Determine whether the resolved template might be overloaded on its
5905  /// template parameter list. If so, the mangling needs to include enough
5906  /// information to reconstruct the template parameter list.
5908  // Function templates are generally overloadable. As a special case, a
5909  // member function template of a generic lambda is not overloadable.
5910  if (auto *FTD = dyn_cast_or_null<FunctionTemplateDecl>(ResolvedTemplate)) {
5911  auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
5912  if (!RD || !RD->isGenericLambda())
5913  return true;
5914  }
5915 
5916  // All other templates are not overloadable. Partial specializations would
5917  // be, but we never mangle them.
5918  return false;
5919  }
5920 
5921  /// Determine whether we need to prefix this <template-arg> mangling with a
5922  /// <template-param-decl>. This happens if the natural template parameter for
5923  /// the argument mangling is not the same as the actual template parameter.
5925  const TemplateArgument &Arg) {
5926  // For a template type parameter, the natural parameter is 'typename T'.
5927  // The actual parameter might be constrained.
5928  if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5929  return TTP->hasTypeConstraint();
5930 
5931  if (Arg.getKind() == TemplateArgument::Pack) {
5932  // For an empty pack, the natural parameter is `typename...`.
5933  if (Arg.pack_size() == 0)
5934  return true;
5935 
5936  // For any other pack, we use the first argument to determine the natural
5937  // template parameter.
5938  return needToMangleTemplateParam(Param, *Arg.pack_begin());
5939  }
5940 
5941  // For a non-type template parameter, the natural parameter is `T V` (for a
5942  // prvalue argument) or `T &V` (for a glvalue argument), where `T` is the
5943  // type of the argument, which we require to exactly match. If the actual
5944  // parameter has a deduced or instantiation-dependent type, it is not
5945  // equivalent to the natural parameter.
5946  if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
5947  return NTTP->getType()->isInstantiationDependentType() ||
5948  NTTP->getType()->getContainedDeducedType();
5949 
5950  // For a template template parameter, the template-head might differ from
5951  // that of the template.
5952  auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5953  TemplateName ArgTemplateName = Arg.getAsTemplateOrTemplatePattern();
5954  const TemplateDecl *ArgTemplate = ArgTemplateName.getAsTemplateDecl();
5955  if (!ArgTemplate)
5956  return true;
5957 
5958  // Mangle the template parameter list of the parameter and argument to see
5959  // if they are the same. We can't use Profile for this, because it can't
5960  // model the depth difference between parameter and argument and might not
5961  // necessarily have the same definition of "identical" that we use here --
5962  // that is, same mangling.
5963  auto MangleTemplateParamListToString =
5964  [&](SmallVectorImpl<char> &Buffer, const TemplateParameterList *Params,
5965  unsigned DepthOffset) {
5966  llvm::raw_svector_ostream Stream(Buffer);
5967  CXXNameMangler(Mangler.Context, Stream,
5968  WithTemplateDepthOffset{DepthOffset})
5969  .mangleTemplateParameterList(Params);
5970  };
5971  llvm::SmallString<128> ParamTemplateHead, ArgTemplateHead;
5972  MangleTemplateParamListToString(ParamTemplateHead,
5973  TTP->getTemplateParameters(), 0);
5974  // Add the depth of the parameter's template parameter list to all
5975  // parameters appearing in the argument to make the indexes line up
5976  // properly.
5977  MangleTemplateParamListToString(ArgTemplateHead,
5978  ArgTemplate->getTemplateParameters(),
5979  TTP->getTemplateParameters()->getDepth());
5980  return ParamTemplateHead != ArgTemplateHead;
5981  }
5982 
5983  /// Determine information about how this template argument should be mangled.
5984  /// This should be called exactly once for each parameter / argument pair, in
5985  /// order.
5986  Info getArgInfo(unsigned ParamIdx, const TemplateArgument &Arg) {
5987  // We need correct types when the template-name is unresolved or when it
5988  // names a template that is able to be overloaded.
5989  if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
5990  return {true, nullptr};
5991 
5992  // Move to the next parameter.
5993  const NamedDecl *Param = UnresolvedExpandedPack;
5994  if (!Param) {
5995  assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
5996  "no parameter for argument");
5997  Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
5998 
5999  // If we reach a parameter pack whose argument isn't in pack form, that
6000  // means Sema couldn't or didn't figure out which arguments belonged to
6001  // it, because it contains a pack expansion or because Sema bailed out of
6002  // computing parameter / argument correspondence before this point. Track
6003  // the pack as the corresponding parameter for all further template
6004  // arguments until we hit a pack expansion, at which point we don't know
6005  // the correspondence between parameters and arguments at all.
6006  if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
6007  UnresolvedExpandedPack = Param;
6008  }
6009  }
6010 
6011  // If we encounter a pack argument that is expanded into a non-pack
6012  // parameter, we can no longer track parameter / argument correspondence,
6013  // and need to use exact types from this point onwards.
6014  if (Arg.isPackExpansion() &&
6015  (!Param->isParameterPack() || UnresolvedExpandedPack)) {
6016  SeenPackExpansionIntoNonPack = true;
6017  return {true, nullptr};
6018  }
6019 
6020  // We need exact types for arguments of a template that might be overloaded
6021  // on template parameter type.
6022  if (isOverloadable())
6023  return {true, needToMangleTemplateParam(Param, Arg) ? Param : nullptr};
6024 
6025  // Otherwise, we only need a correct type if the parameter has a deduced
6026  // type.
6027  //
6028  // Note: for an expanded parameter pack, getType() returns the type prior
6029  // to expansion. We could ask for the expanded type with getExpansionType(),
6030  // but it doesn't matter because substitution and expansion don't affect
6031  // whether a deduced type appears in the type.
6032  auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
6033  bool NeedExactType = NTTP && NTTP->getType()->getContainedDeducedType();
6034  return {NeedExactType, nullptr};
6035  }
6036 
6037  /// Determine if we should mangle a requires-clause after the template
6038  /// argument list. If so, returns the expression to mangle.
6040  if (!isOverloadable())
6041  return nullptr;
6042  return ResolvedTemplate->getTemplateParameters()->getRequiresClause();
6043  }
6044 };
6045 
6046 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6047  const TemplateArgumentLoc *TemplateArgs,
6048  unsigned NumTemplateArgs) {
6049  // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6050  Out << 'I';
6051  TemplateArgManglingInfo Info(*this, TN);
6052  for (unsigned i = 0; i != NumTemplateArgs; ++i) {
6053  mangleTemplateArg(Info, i, TemplateArgs[i].getArgument());
6054  }
6055  mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
6056  Out << 'E';
6057 }
6058 
6059 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6060  const TemplateArgumentList &AL) {
6061  // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6062  Out << 'I';
6063  TemplateArgManglingInfo Info(*this, TN);
6064  for (unsigned i = 0, e = AL.size(); i != e; ++i) {
6065  mangleTemplateArg(Info, i, AL[i]);
6066  }
6067  mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
6068  Out << 'E';
6069 }
6070 
6071 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6073  // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6074  Out << 'I';
6075  TemplateArgManglingInfo Info(*this, TN);
6076  for (unsigned i = 0; i != Args.size(); ++i) {
6077  mangleTemplateArg(Info, i, Args[i]);
6078  }
6079  mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
6080  Out << 'E';
6081 }
6082 
6083 void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo &Info,
6084  unsigned Index, TemplateArgument A) {
6085  TemplateArgManglingInfo::Info ArgInfo = Info.getArgInfo(Index, A);
6086 
6087  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6088  if (ArgInfo.TemplateParameterToMangle &&
6089  !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
6090  // The template parameter is mangled if the mangling would otherwise be
6091  // ambiguous.
6092  //
6093  // <template-arg> ::= <template-param-decl> <template-arg>
6094  //
6095  // Clang 17 and before did not do this.
6096  mangleTemplateParamDecl(ArgInfo.TemplateParameterToMangle);
6097  }
6098 
6099  mangleTemplateArg(A, ArgInfo.NeedExactType);
6100 }
6101 
6102 void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
6103  // <template-arg> ::= <type> # type or template
6104  // ::= X <expression> E # expression
6105  // ::= <expr-primary> # simple expressions
6106  // ::= J <template-arg>* E # argument pack
6107  if (!A.isInstantiationDependent() || A.isDependent())
6108  A = Context.getASTContext().getCanonicalTemplateArgument(A);
6109 
6110  switch (A.getKind()) {
6112  llvm_unreachable("Cannot mangle NULL template argument");
6113 
6115  mangleType(A.getAsType());
6116  break;
6118  // This is mangled as <type>.
6119  mangleType(A.getAsTemplate());
6120  break;
6122  // <type> ::= Dp <type> # pack expansion (C++0x)
6123  Out << "Dp";
6124  mangleType(A.getAsTemplateOrTemplatePattern());
6125  break;
6127  mangleTemplateArgExpr(A.getAsExpr());
6128  break;
6130  mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
6131  break;
6133  // <expr-primary> ::= L <mangled-name> E # external name
6134  ValueDecl *D = A.getAsDecl();
6135 
6136  // Template parameter objects are modeled by reproducing a source form
6137  // produced as if by aggregate initialization.
6138  if (A.getParamTypeForDecl()->isRecordType()) {
6139  auto *TPO = cast<TemplateParamObjectDecl>(D);
6140  mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
6141  TPO->getValue(), /*TopLevel=*/true,
6142  NeedExactType);
6143  break;
6144  }
6145 
6146  ASTContext &Ctx = Context.getASTContext();
6147  APValue Value;
6148  if (D->isCXXInstanceMember())
6149  // Simple pointer-to-member with no conversion.
6150  Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
6151  else if (D->getType()->isArrayType() &&
6152  Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),
6153  A.getParamTypeForDecl()) &&
6154  !isCompatibleWith(LangOptions::ClangABI::Ver11))
6155  // Build a value corresponding to this implicit array-to-pointer decay.
6158  /*OnePastTheEnd=*/false);
6159  else
6160  // Regular pointer or reference to a declaration.
6163  /*OnePastTheEnd=*/false);
6164  mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
6165  NeedExactType);
6166  break;
6167  }
6169  mangleNullPointer(A.getNullPtrType());
6170  break;
6171  }
6173  mangleValueInTemplateArg(A.getStructuralValueType(),
6175  /*TopLevel=*/true, NeedExactType);
6176  break;
6177  case TemplateArgument::Pack: {
6178  // <template-arg> ::= J <template-arg>* E
6179  Out << 'J';
6180  for (const auto &P : A.pack_elements())
6181  mangleTemplateArg(P, NeedExactType);
6182  Out << 'E';
6183  }
6184  }
6185 }
6186 
6187 void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
6188  if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6189  mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
6190  return;
6191  }
6192 
6193  // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
6194  // correctly in cases where the template argument was
6195  // constructed from an expression rather than an already-evaluated
6196  // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
6197  // 'Li0E'.
6198  //
6199  // We did special-case DeclRefExpr to attempt to DTRT for that one
6200  // expression-kind, but while doing so, unfortunately handled ParmVarDecl
6201  // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
6202  // the proper 'Xfp_E'.
6203  E = E->IgnoreParenImpCasts();
6204  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6205  const ValueDecl *D = DRE->getDecl();
6206  if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
6207  Out << 'L';
6208  mangle(D);
6209  Out << 'E';
6210  return;
6211  }
6212  }
6213  Out << 'X';
6214  mangleExpression(E);
6215  Out << 'E';
6216 }
6217 
6218 /// Determine whether a given value is equivalent to zero-initialization for
6219 /// the purpose of discarding a trailing portion of a 'tl' mangling.
6220 ///
6221 /// Note that this is not in general equivalent to determining whether the
6222 /// value has an all-zeroes bit pattern.
6223 static bool isZeroInitialized(QualType T, const APValue &V) {
6224  // FIXME: mangleValueInTemplateArg has quadratic time complexity in
6225  // pathological cases due to using this, but it's a little awkward
6226  // to do this in linear time in general.
6227  switch (V.getKind()) {
6228  case APValue::None:
6231  return false;
6232 
6233  case APValue::Struct: {
6234  const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6235  assert(RD && "unexpected type for record value");
6236  unsigned I = 0;
6237  for (const CXXBaseSpecifier &BS : RD->bases()) {
6238  if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
6239  return false;
6240  ++I;
6241  }
6242  I = 0;
6243  for (const FieldDecl *FD : RD->fields()) {
6244  if (!FD->isUnnamedBitField() &&
6245  !isZeroInitialized(FD->getType(), V.getStructField(I)))
6246  return false;
6247  ++I;
6248  }
6249  return true;
6250  }
6251 
6252  case APValue::Union: {
6253  const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6254  assert(RD && "unexpected type for union value");
6255  // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
6256  for (const FieldDecl *FD : RD->fields()) {
6257  if (!FD->isUnnamedBitField())
6258  return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
6259  isZeroInitialized(FD->getType(), V.getUnionValue());
6260  }
6261  // If there are no fields (other than unnamed bitfields), the value is
6262  // necessarily zero-initialized.
6263  return true;
6264  }
6265 
6266  case APValue::Array: {
6268  for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
6269  if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
6270  return false;
6271  return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
6272  }
6273 
6274  case APValue::Vector: {
6275  const VectorType *VT = T->castAs<VectorType>();
6276  for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
6277  if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
6278  return false;
6279  return true;
6280  }
6281 
6282  case APValue::Int:
6283  return !V.getInt();
6284 
6285  case APValue::Float:
6286  return V.getFloat().isPosZero();
6287 
6288  case APValue::FixedPoint:
6289  return !V.getFixedPoint().getValue();
6290 
6291  case APValue::ComplexFloat:
6292  return V.getComplexFloatReal().isPosZero() &&
6293  V.getComplexFloatImag().isPosZero();
6294 
6295  case APValue::ComplexInt:
6296  return !V.getComplexIntReal() && !V.getComplexIntImag();
6297 
6298  case APValue::LValue:
6299  return V.isNullPointer();
6300 
6302  return !V.getMemberPointerDecl();
6303  }
6304 
6305  llvm_unreachable("Unhandled APValue::ValueKind enum");
6306 }
6307 
6308 static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
6309  QualType T = LV.getLValueBase().getType();
6311  if (const ArrayType *AT = Ctx.getAsArrayType(T))
6312  T = AT->getElementType();
6313  else if (const FieldDecl *FD =
6314  dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
6315  T = FD->getType();
6316  else
6317  T = Ctx.getRecordType(
6318  cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
6319  }
6320  return T;
6321 }
6322 
6324  DiagnosticsEngine &Diags,
6325  const FieldDecl *FD) {
6326  // According to:
6327  // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
6328  // For the purposes of mangling, the name of an anonymous union is considered
6329  // to be the name of the first named data member found by a pre-order,
6330  // depth-first, declaration-order walk of the data members of the anonymous
6331  // union.
6332 
6333  if (FD->getIdentifier())
6334  return FD->getIdentifier();
6335 
6336  // The only cases where the identifer of a FieldDecl would be blank is if the
6337  // field represents an anonymous record type or if it is an unnamed bitfield.
6338  // There is no type to descend into in the case of a bitfield, so we can just
6339  // return nullptr in that case.
6340  if (FD->isBitField())
6341  return nullptr;
6342  const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
6343 
6344  // Consider only the fields in declaration order, searched depth-first. We
6345  // don't care about the active member of the union, as all we are doing is
6346  // looking for a valid name. We also don't check bases, due to guidance from
6347  // the Itanium ABI folks.
6348  for (const FieldDecl *RDField : RD->fields()) {
6349  if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
6350  return II;
6351  }
6352 
6353  // According to the Itanium ABI: If there is no such data member (i.e., if all
6354  // of the data members in the union are unnamed), then there is no way for a
6355  // program to refer to the anonymous union, and there is therefore no need to
6356  // mangle its name. However, we should diagnose this anyway.
6357  unsigned DiagID = Diags.getCustomDiagID(
6358  DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
6359  Diags.Report(UnionLoc, DiagID);
6360 
6361  return nullptr;
6362 }
6363 
6364 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
6365  bool TopLevel,
6366  bool NeedExactType) {
6367  // Ignore all top-level cv-qualifiers, to match GCC.
6368  Qualifiers Quals;
6369  T = getASTContext().getUnqualifiedArrayType(T, Quals);
6370 
6371  // A top-level expression that's not a primary expression is wrapped in X...E.
6372  bool IsPrimaryExpr = true;
6373  auto NotPrimaryExpr = [&] {
6374  if (TopLevel && IsPrimaryExpr)
6375  Out << 'X';
6376  IsPrimaryExpr = false;
6377  };
6378 
6379  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
6380  switch (V.getKind()) {
6381  case APValue::None:
6383  Out << 'L';
6384  mangleType(T);
6385  Out << 'E';
6386  break;
6387 
6389  llvm_unreachable("unexpected value kind in template argument");
6390 
6391  case APValue::Struct: {
6392  const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6393  assert(RD && "unexpected type for record value");
6394 
6395  // Drop trailing zero-initialized elements.
6397  while (
6398  !Fields.empty() &&
6399  (Fields.back()->isUnnamedBitField() ||
6400  isZeroInitialized(Fields.back()->getType(),
6401  V.getStructField(Fields.back()->getFieldIndex())))) {
6402  Fields.pop_back();
6403  }
6405  if (Fields.empty()) {
6406  while (!Bases.empty() &&
6407  isZeroInitialized(Bases.back().getType(),
6408  V.getStructBase(Bases.size() - 1)))
6409  Bases = Bases.drop_back();
6410  }
6411 
6412  // <expression> ::= tl <type> <braced-expression>* E
6413  NotPrimaryExpr();
6414  Out << "tl";
6415  mangleType(T);
6416  for (unsigned I = 0, N = Bases.size(); I != N; ++I)
6417  mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
6418  for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
6419  if (Fields[I]->isUnnamedBitField())
6420  continue;
6421  mangleValueInTemplateArg(Fields[I]->getType(),
6422  V.getStructField(Fields[I]->getFieldIndex()),
6423  false);
6424  }
6425  Out << 'E';
6426  break;
6427  }
6428 
6429  case APValue::Union: {
6430  assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
6431  const FieldDecl *FD = V.getUnionField();
6432 
6433  if (!FD) {
6434  Out << 'L';
6435  mangleType(T);
6436  Out << 'E';
6437  break;
6438  }
6439 
6440  // <braced-expression> ::= di <field source-name> <braced-expression>
6441  NotPrimaryExpr();
6442  Out << "tl";
6443  mangleType(T);
6444  if (!isZeroInitialized(T, V)) {
6445  Out << "di";
6447  T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
6448  if (II)
6449  mangleSourceName(II);
6450  mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
6451  }
6452  Out << 'E';
6453  break;
6454  }
6455 
6456  case APValue::Array: {
6458 
6459  NotPrimaryExpr();
6460  Out << "tl";
6461  mangleType(T);
6462 
6463  // Drop trailing zero-initialized elements.
6464  unsigned N = V.getArraySize();
6465  if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
6466  N = V.getArrayInitializedElts();
6467  while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
6468  --N;
6469  }
6470 
6471  for (unsigned I = 0; I != N; ++I) {
6472  const APValue &Elem = I < V.getArrayInitializedElts()
6473  ? V.getArrayInitializedElt(I)
6474  : V.getArrayFiller();
6475  mangleValueInTemplateArg(ElemT, Elem, false);
6476  }
6477  Out << 'E';
6478  break;
6479  }
6480 
6481  case APValue::Vector: {
6482  const VectorType *VT = T->castAs<VectorType>();
6483 
6484  NotPrimaryExpr();
6485  Out << "tl";
6486  mangleType(T);
6487  unsigned N = V.getVectorLength();
6488  while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
6489  --N;
6490  for (unsigned I = 0; I != N; ++I)
6491  mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
6492  Out << 'E';
6493  break;
6494  }
6495 
6496  case APValue::Int:
6497  mangleIntegerLiteral(T, V.getInt());
6498  break;
6499 
6500  case APValue::Float:
6501  mangleFloatLiteral(T, V.getFloat());
6502  break;
6503 
6504  case APValue::FixedPoint:
6505  mangleFixedPointLiteral();
6506  break;
6507 
6508  case APValue::ComplexFloat: {
6509  const ComplexType *CT = T->castAs<ComplexType>();
6510  NotPrimaryExpr();
6511  Out << "tl";
6512  mangleType(T);
6513  if (!V.getComplexFloatReal().isPosZero() ||
6514  !V.getComplexFloatImag().isPosZero())
6515  mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
6516  if (!V.getComplexFloatImag().isPosZero())
6517  mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
6518  Out << 'E';
6519  break;
6520  }
6521 
6522  case APValue::ComplexInt: {
6523  const ComplexType *CT = T->castAs<ComplexType>();
6524  NotPrimaryExpr();
6525  Out << "tl";
6526  mangleType(T);
6527  if (V.getComplexIntReal().getBoolValue() ||
6528  V.getComplexIntImag().getBoolValue())
6529  mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
6530  if (V.getComplexIntImag().getBoolValue())
6531  mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
6532  Out << 'E';
6533  break;
6534  }
6535 
6536  case APValue::LValue: {
6537  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6538  assert((T->isPointerOrReferenceType()) &&
6539  "unexpected type for LValue template arg");
6540 
6541  if (V.isNullPointer()) {
6542  mangleNullPointer(T);
6543  break;
6544  }
6545 
6546  APValue::LValueBase B = V.getLValueBase();
6547  if (!B) {
6548  // Non-standard mangling for integer cast to a pointer; this can only
6549  // occur as an extension.
6550  CharUnits Offset = V.getLValueOffset();
6551  if (Offset.isZero()) {
6552  // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
6553  // a cast, because L <type> 0 E means something else.
6554  NotPrimaryExpr();
6555  Out << "rc";
6556  mangleType(T);
6557  Out << "Li0E";
6558  if (TopLevel)
6559  Out << 'E';
6560  } else {
6561  Out << "L";
6562  mangleType(T);
6563  Out << Offset.getQuantity() << 'E';
6564  }
6565  break;
6566  }
6567 
6568  ASTContext &Ctx = Context.getASTContext();
6569 
6570  enum { Base, Offset, Path } Kind;
6571  if (!V.hasLValuePath()) {
6572  // Mangle as (T*)((char*)&base + N).
6573  if (T->isReferenceType()) {
6574  NotPrimaryExpr();
6575  Out << "decvP";
6576  mangleType(T->getPointeeType());
6577  } else {
6578  NotPrimaryExpr();
6579  Out << "cv";
6580  mangleType(T);
6581  }
6582  Out << "plcvPcad";
6583  Kind = Offset;
6584  } else {
6585  // Clang 11 and before mangled an array subject to array-to-pointer decay
6586  // as if it were the declaration itself.
6587  bool IsArrayToPointerDecayMangledAsDecl = false;
6588  if (TopLevel && Ctx.getLangOpts().getClangABICompat() <=
6590  QualType BType = B.getType();
6591  IsArrayToPointerDecayMangledAsDecl =
6592  BType->isArrayType() && V.getLValuePath().size() == 1 &&
6593  V.getLValuePath()[0].getAsArrayIndex() == 0 &&
6594  Ctx.hasSimilarType(T, Ctx.getDecayedType(BType));
6595  }
6596 
6597  if ((!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) &&
6598  !IsArrayToPointerDecayMangledAsDecl) {
6599  NotPrimaryExpr();
6600  // A final conversion to the template parameter's type is usually
6601  // folded into the 'so' mangling, but we can't do that for 'void*'
6602  // parameters without introducing collisions.
6603  if (NeedExactType && T->isVoidPointerType()) {
6604  Out << "cv";
6605  mangleType(T);
6606  }
6607  if (T->isPointerType())
6608  Out << "ad";
6609  Out << "so";
6610  mangleType(T->isVoidPointerType()
6611  ? getLValueType(Ctx, V).getUnqualifiedType()
6612  : T->getPointeeType());
6613  Kind = Path;
6614  } else {
6615  if (NeedExactType &&
6616  !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
6617  !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6618  NotPrimaryExpr();
6619  Out << "cv";
6620  mangleType(T);
6621  }
6622  if (T->isPointerType()) {
6623  NotPrimaryExpr();
6624  Out << "ad";
6625  }
6626  Kind = Base;
6627  }
6628  }
6629 
6630  QualType TypeSoFar = B.getType();
6631  if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
6632  Out << 'L';
6633  mangle(VD);
6634  Out << 'E';
6635  } else if (auto *E = B.dyn_cast<const Expr*>()) {
6636  NotPrimaryExpr();
6637  mangleExpression(E);
6638  } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
6639  NotPrimaryExpr();
6640  Out << "ti";
6641  mangleType(QualType(TI.getType(), 0));
6642  } else {
6643  // We should never see dynamic allocations here.
6644  llvm_unreachable("unexpected lvalue base kind in template argument");
6645  }
6646 
6647  switch (Kind) {
6648  case Base:
6649  break;
6650 
6651  case Offset:
6652  Out << 'L';
6653  mangleType(Ctx.getPointerDiffType());
6654  mangleNumber(V.getLValueOffset().getQuantity());
6655  Out << 'E';
6656  break;
6657 
6658  case Path:
6659  // <expression> ::= so <referent type> <expr> [<offset number>]
6660  // <union-selector>* [p] E
6661  if (!V.getLValueOffset().isZero())
6662  mangleNumber(V.getLValueOffset().getQuantity());
6663 
6664  // We model a past-the-end array pointer as array indexing with index N,
6665  // not with the "past the end" flag. Compensate for that.
6666  bool OnePastTheEnd = V.isLValueOnePastTheEnd();
6667 
6668  for (APValue::LValuePathEntry E : V.getLValuePath()) {
6669  if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
6670  if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
6671  OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
6672  TypeSoFar = AT->getElementType();
6673  } else {
6674  const Decl *D = E.getAsBaseOrMember().getPointer();
6675  if (auto *FD = dyn_cast<FieldDecl>(D)) {
6676  // <union-selector> ::= _ <number>
6677  if (FD->getParent()->isUnion()) {
6678  Out << '_';
6679  if (FD->getFieldIndex())
6680  Out << (FD->getFieldIndex() - 1);
6681  }
6682  TypeSoFar = FD->getType();
6683  } else {
6684  TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));
6685  }
6686  }
6687  }
6688 
6689  if (OnePastTheEnd)
6690  Out << 'p';
6691  Out << 'E';
6692  break;
6693  }
6694 
6695  break;
6696  }
6697 
6699  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6700  if (!V.getMemberPointerDecl()) {
6701  mangleNullPointer(T);
6702  break;
6703  }
6704 
6705  ASTContext &Ctx = Context.getASTContext();
6706 
6707  NotPrimaryExpr();
6708  if (!V.getMemberPointerPath().empty()) {
6709  Out << "mc";
6710  mangleType(T);
6711  } else if (NeedExactType &&
6712  !Ctx.hasSameType(
6714  V.getMemberPointerDecl()->getType()) &&
6715  !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6716  Out << "cv";
6717  mangleType(T);
6718  }
6719  Out << "adL";
6720  mangle(V.getMemberPointerDecl());
6721  Out << 'E';
6722  if (!V.getMemberPointerPath().empty()) {
6723  CharUnits Offset =
6724  Context.getASTContext().getMemberPointerPathAdjustment(V);
6725  if (!Offset.isZero())
6726  mangleNumber(Offset.getQuantity());
6727  Out << 'E';
6728  }
6729  break;
6730  }
6731 
6732  if (TopLevel && !IsPrimaryExpr)
6733  Out << 'E';
6734 }
6735 
6736 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
6737  // <template-param> ::= T_ # first template parameter
6738  // ::= T <parameter-2 non-negative number> _
6739  // ::= TL <L-1 non-negative number> __
6740  // ::= TL <L-1 non-negative number> _
6741  // <parameter-2 non-negative number> _
6742  //
6743  // The latter two manglings are from a proposal here:
6744  // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
6745  Out << 'T';
6746  Depth += TemplateDepthOffset;
6747  if (Depth != 0)
6748  Out << 'L' << (Depth - 1) << '_';
6749  if (Index != 0)
6750  Out << (Index - 1);
6751  Out << '_';
6752 }
6753 
6754 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
6755  if (SeqID == 0) {
6756  // Nothing.
6757  } else if (SeqID == 1) {
6758  Out << '0';
6759  } else {
6760  SeqID--;
6761 
6762  // <seq-id> is encoded in base-36, using digits and upper case letters.
6763  char Buffer[7]; // log(2**32) / log(36) ~= 7
6764  MutableArrayRef<char> BufferRef(Buffer);
6765  MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
6766 
6767  for (; SeqID != 0; SeqID /= 36) {
6768  unsigned C = SeqID % 36;
6769  *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
6770  }
6771 
6772  Out.write(I.base(), I - BufferRef.rbegin());
6773  }
6774  Out << '_';
6775 }
6776 
6777 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
6778  bool result = mangleSubstitution(tname);
6779  assert(result && "no existing substitution for template name");
6780  (void) result;
6781 }
6782 
6783 // <substitution> ::= S <seq-id> _
6784 // ::= S_
6785 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
6786  // Try one of the standard substitutions first.
6787  if (mangleStandardSubstitution(ND))
6788  return true;
6789 
6790  ND = cast<NamedDecl>(ND->getCanonicalDecl());
6791  return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
6792 }
6793 
6794 bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {
6795  assert(NNS->getKind() == NestedNameSpecifier::Identifier &&
6796  "mangleSubstitution(NestedNameSpecifier *) is only used for "
6797  "identifier nested name specifiers.");
6798  NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
6799  return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS));
6800 }
6801 
6802 /// Determine whether the given type has any qualifiers that are relevant for
6803 /// substitutions.
6805  Qualifiers Qs = T.getQualifiers();
6806  return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
6807 }
6808 
6809 bool CXXNameMangler::mangleSubstitution(QualType T) {
6811  if (const RecordType *RT = T->getAs<RecordType>())
6812  return mangleSubstitution(RT->getDecl());
6813  }
6814 
6815  uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
6816 
6817  return mangleSubstitution(TypePtr);
6818 }
6819 
6820 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
6821  if (TemplateDecl *TD = Template.getAsTemplateDecl())
6822  return mangleSubstitution(TD);
6823 
6824  Template = Context.getASTContext().getCanonicalTemplateName(Template);
6825  return mangleSubstitution(
6826  reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
6827 }
6828 
6829 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
6830  llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
6831  if (I == Substitutions.end())
6832  return false;
6833 
6834  unsigned SeqID = I->second;
6835  Out << 'S';
6836  mangleSeqID(SeqID);
6837 
6838  return true;
6839 }
6840 
6841 /// Returns whether S is a template specialization of std::Name with a single
6842 /// argument of type A.
6843 bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,
6844  QualType A) {
6845  if (S.isNull())
6846  return false;
6847 
6848  const RecordType *RT = S->getAs<RecordType>();
6849  if (!RT)
6850  return false;
6851 
6853  dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6854  if (!SD || !SD->getIdentifier()->isStr(Name))
6855  return false;
6856 
6857  if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6858  return false;
6859 
6860  const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6861  if (TemplateArgs.size() != 1)
6862  return false;
6863 
6864  if (TemplateArgs[0].getAsType() != A)
6865  return false;
6866 
6868  return false;
6869 
6870  return true;
6871 }
6872 
6873 /// Returns whether SD is a template specialization std::Name<char,
6874 /// std::char_traits<char> [, std::allocator<char>]>
6875 /// HasAllocator controls whether the 3rd template argument is needed.
6876 bool CXXNameMangler::isStdCharSpecialization(
6877  const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,
6878  bool HasAllocator) {
6879  if (!SD->getIdentifier()->isStr(Name))
6880  return false;
6881 
6882  const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6883  if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
6884  return false;
6885 
6886  QualType A = TemplateArgs[0].getAsType();
6887  if (A.isNull())
6888  return false;
6889  // Plain 'char' is named Char_S or Char_U depending on the target ABI.
6890  if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&
6891  !A->isSpecificBuiltinType(BuiltinType::Char_U))
6892  return false;
6893 
6894  if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))
6895  return false;
6896 
6897  if (HasAllocator &&
6898  !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))
6899  return false;
6900 
6902  return false;
6903 
6904  return true;
6905 }
6906 
6907 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
6908  // <substitution> ::= St # ::std::
6909  if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
6910  if (isStd(NS)) {
6911  Out << "St";
6912  return true;
6913  }
6914  return false;
6915  }
6916 
6917  if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
6918  if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))
6919  return false;
6920 
6921  if (TD->getOwningModuleForLinkage())
6922  return false;
6923 
6924  // <substitution> ::= Sa # ::std::allocator
6925  if (TD->getIdentifier()->isStr("allocator")) {
6926  Out << "Sa";
6927  return true;
6928  }
6929 
6930  // <<substitution> ::= Sb # ::std::basic_string
6931  if (TD->getIdentifier()->isStr("basic_string")) {
6932  Out << "Sb";
6933  return true;
6934  }
6935  return false;
6936  }
6937 
6938  if (const ClassTemplateSpecializationDecl *SD =
6939  dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
6940  if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6941  return false;
6942 
6944  return false;
6945 
6946  // <substitution> ::= Ss # ::std::basic_string<char,
6947  // ::std::char_traits<char>,
6948  // ::std::allocator<char> >
6949  if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {
6950  Out << "Ss";
6951  return true;
6952  }
6953 
6954  // <substitution> ::= Si # ::std::basic_istream<char,
6955  // ::std::char_traits<char> >
6956  if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {
6957  Out << "Si";
6958  return true;
6959  }
6960 
6961  // <substitution> ::= So # ::std::basic_ostream<char,
6962  // ::std::char_traits<char> >
6963  if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {
6964  Out << "So";
6965  return true;
6966  }
6967 
6968  // <substitution> ::= Sd # ::std::basic_iostream<char,
6969  // ::std::char_traits<char> >
6970  if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {
6971  Out << "Sd";
6972  return true;
6973  }
6974  return false;
6975  }
6976 
6977  return false;
6978 }
6979 
6980 void CXXNameMangler::addSubstitution(QualType T) {
6982  if (const RecordType *RT = T->getAs<RecordType>()) {
6983  addSubstitution(RT->getDecl());
6984  return;
6985  }
6986  }
6987 
6988  uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
6989  addSubstitution(TypePtr);
6990 }
6991 
6992 void CXXNameMangler::addSubstitution(TemplateName Template) {
6993  if (TemplateDecl *TD = Template.getAsTemplateDecl())
6994  return addSubstitution(TD);
6995 
6996  Template = Context.getASTContext().getCanonicalTemplateName(Template);
6997  addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
6998 }
6999 
7000 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
7001  assert(!Substitutions.count(Ptr) && "Substitution already exists!");
7002  Substitutions[Ptr] = SeqID++;
7003 }
7004 
7005 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
7006  assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
7007  if (Other->SeqID > SeqID) {
7008  Substitutions.swap(Other->Substitutions);
7009  SeqID = Other->SeqID;
7010  }
7011 }
7012 
7014 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
7015  // When derived abi tags are disabled there is no need to make any list.
7016  if (DisableDerivedAbiTags)
7017  return AbiTagList();
7018 
7019  llvm::raw_null_ostream NullOutStream;
7020  CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
7021  TrackReturnTypeTags.disableDerivedAbiTags();
7022 
7023  const FunctionProtoType *Proto =
7024  cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
7025  FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
7026  TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
7027  TrackReturnTypeTags.mangleType(Proto->getReturnType());
7028  TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
7029  TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
7030 
7031  return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
7032 }
7033 
7035 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
7036  // When derived abi tags are disabled there is no need to make any list.
7037  if (DisableDerivedAbiTags)
7038  return AbiTagList();
7039 
7040  llvm::raw_null_ostream NullOutStream;
7041  CXXNameMangler TrackVariableType(*this, NullOutStream);
7042  TrackVariableType.disableDerivedAbiTags();
7043 
7044  TrackVariableType.mangleType(VD->getType());
7045 
7046  return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
7047 }
7048 
7049 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
7050  const VarDecl *VD) {
7051  llvm::raw_null_ostream NullOutStream;
7052  CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
7053  TrackAbiTags.mangle(VD);
7054  return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
7055 }
7056 
7057 //
7058 
7059 /// Mangles the name of the declaration D and emits that name to the given
7060 /// output stream.
7061 ///
7062 /// If the declaration D requires a mangled name, this routine will emit that
7063 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
7064 /// and this routine will return false. In this case, the caller should just
7065 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
7066 /// name.
7067 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
7068  raw_ostream &Out) {
7069  const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
7070  assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&
7071  "Invalid mangleName() call, argument is not a variable or function!");
7072 
7073  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
7074  getASTContext().getSourceManager(),
7075  "Mangling declaration");
7076 
7077  if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
7078  auto Type = GD.getCtorType();
7079  CXXNameMangler Mangler(*this, Out, CD, Type);
7080  return Mangler.mangle(GlobalDecl(CD, Type));
7081  }
7082 
7083  if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
7084  auto Type = GD.getDtorType();
7085  CXXNameMangler Mangler(*this, Out, DD, Type);
7086  return Mangler.mangle(GlobalDecl(DD, Type));
7087  }
7088 
7089  CXXNameMangler Mangler(*this, Out, D);
7090  Mangler.mangle(GD);
7091 }
7092 
7093 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
7094  raw_ostream &Out) {
7095  CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
7096  Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
7097 }
7098 
7099 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
7100  raw_ostream &Out) {
7101  CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
7102  Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
7103 }
7104 
7105 /// Mangles the pointer authentication override attribute for classes
7106 /// that have explicit overrides for the vtable authentication schema.
7107 ///
7108 /// The override is mangled as a parameterized vendor extension as follows
7109 ///
7110 /// <type> ::= U "__vtptrauth" I
7111 /// <key>
7112 /// <addressDiscriminated>
7113 /// <extraDiscriminator>
7114 /// E
7115 ///
7116 /// The extra discriminator encodes the explicit value derived from the
7117 /// override schema, e.g. if the override has specified type based
7118 /// discrimination the encoded value will be the discriminator derived from the
7119 /// type name.
7120 static void mangleOverrideDiscrimination(CXXNameMangler &Mangler,
7121  ASTContext &Context,
7122  const ThunkInfo &Thunk) {
7123  auto &LangOpts = Context.getLangOpts();
7124  const CXXRecordDecl *ThisRD = Thunk.ThisType->getPointeeCXXRecordDecl();
7125  const CXXRecordDecl *PtrauthClassRD =
7126  Context.baseForVTableAuthentication(ThisRD);
7127  unsigned TypedDiscriminator =
7129  Mangler.mangleVendorQualifier("__vtptrauth");
7130  auto &ManglerStream = Mangler.getStream();
7131  ManglerStream << "I";
7132  if (const auto *ExplicitAuth =
7133  PtrauthClassRD->getAttr<VTablePointerAuthenticationAttr>()) {
7134  ManglerStream << "Lj" << ExplicitAuth->getKey();
7135 
7136  if (ExplicitAuth->getAddressDiscrimination() ==
7137  VTablePointerAuthenticationAttr::DefaultAddressDiscrimination)
7138  ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;
7139  else
7140  ManglerStream << "Lb"
7141  << (ExplicitAuth->getAddressDiscrimination() ==
7142  VTablePointerAuthenticationAttr::AddressDiscrimination);
7143 
7144  switch (ExplicitAuth->getExtraDiscrimination()) {
7145  case VTablePointerAuthenticationAttr::DefaultExtraDiscrimination: {
7146  if (LangOpts.PointerAuthVTPtrTypeDiscrimination)
7147  ManglerStream << "Lj" << TypedDiscriminator;
7148  else
7149  ManglerStream << "Lj" << 0;
7150  break;
7151  }
7152  case VTablePointerAuthenticationAttr::TypeDiscrimination:
7153  ManglerStream << "Lj" << TypedDiscriminator;
7154  break;
7155  case VTablePointerAuthenticationAttr::CustomDiscrimination:
7156  ManglerStream << "Lj" << ExplicitAuth->getCustomDiscriminationValue();
7157  break;
7158  case VTablePointerAuthenticationAttr::NoExtraDiscrimination:
7159  ManglerStream << "Lj" << 0;
7160  break;
7161  }
7162  } else {
7163  ManglerStream << "Lj"
7164  << (unsigned)VTablePointerAuthenticationAttr::DefaultKey;
7165  ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;
7166  if (LangOpts.PointerAuthVTPtrTypeDiscrimination)
7167  ManglerStream << "Lj" << TypedDiscriminator;
7168  else
7169  ManglerStream << "Lj" << 0;
7170  }
7171  ManglerStream << "E";
7172 }
7173 
7174 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
7175  const ThunkInfo &Thunk,
7176  bool ElideOverrideInfo,
7177  raw_ostream &Out) {
7178  // <special-name> ::= T <call-offset> <base encoding>
7179  // # base is the nominal target function of thunk
7180  // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
7181  // # base is the nominal target function of thunk
7182  // # first call-offset is 'this' adjustment
7183  // # second call-offset is result adjustment
7184 
7185  assert(!isa<CXXDestructorDecl>(MD) &&
7186  "Use mangleCXXDtor for destructor decls!");
7187  CXXNameMangler Mangler(*this, Out);
7188  Mangler.getStream() << "_ZT";
7189  if (!Thunk.Return.isEmpty())
7190  Mangler.getStream() << 'c';
7191 
7192  // Mangle the 'this' pointer adjustment.
7193  Mangler.mangleCallOffset(Thunk.This.NonVirtual,
7195 
7196  // Mangle the return pointer adjustment if there is one.
7197  if (!Thunk.Return.isEmpty())
7198  Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
7200 
7201  Mangler.mangleFunctionEncoding(MD);
7202  if (!ElideOverrideInfo)
7203  mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);
7204 }
7205 
7206 void ItaniumMangleContextImpl::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
7207  CXXDtorType Type,
7208  const ThunkInfo &Thunk,
7209  bool ElideOverrideInfo,
7210  raw_ostream &Out) {
7211  // <special-name> ::= T <call-offset> <base encoding>
7212  // # base is the nominal target function of thunk
7213  CXXNameMangler Mangler(*this, Out, DD, Type);
7214  Mangler.getStream() << "_ZT";
7215 
7216  auto &ThisAdjustment = Thunk.This;
7217  // Mangle the 'this' pointer adjustment.
7218  Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
7220 
7221  Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
7222  if (!ElideOverrideInfo)
7223  mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);
7224 }
7225 
7226 /// Returns the mangled name for a guard variable for the passed in VarDecl.
7227 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
7228  raw_ostream &Out) {
7229  // <special-name> ::= GV <object name> # Guard variable for one-time
7230  // # initialization
7231  CXXNameMangler Mangler(*this, Out);
7232  // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
7233  // be a bug that is fixed in trunk.
7234  Mangler.getStream() << "_ZGV";
7235  Mangler.mangleName(D);
7236 }
7237 
7238 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
7239  raw_ostream &Out) {
7240  // These symbols are internal in the Itanium ABI, so the names don't matter.
7241  // Clang has traditionally used this symbol and allowed LLVM to adjust it to
7242  // avoid duplicate symbols.
7243  Out << "__cxx_global_var_init";
7244 }
7245 
7246 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
7247  raw_ostream &Out) {
7248  // Prefix the mangling of D with __dtor_.
7249  CXXNameMangler Mangler(*this, Out);
7250  Mangler.getStream() << "__dtor_";
7251  if (shouldMangleDeclName(D))
7252  Mangler.mangle(D);
7253  else
7254  Mangler.getStream() << D->getName();
7255 }
7256 
7257 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
7258  raw_ostream &Out) {
7259  // Clang generates these internal-linkage functions as part of its
7260  // implementation of the XL ABI.
7261  CXXNameMangler Mangler(*this, Out);
7262  Mangler.getStream() << "__finalize_";
7263  if (shouldMangleDeclName(D))
7264  Mangler.mangle(D);
7265  else
7266  Mangler.getStream() << D->getName();
7267 }
7268 
7269 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
7270  GlobalDecl EnclosingDecl, raw_ostream &Out) {
7271  CXXNameMangler Mangler(*this, Out);
7272  Mangler.getStream() << "__filt_";
7273  auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7274  if (shouldMangleDeclName(EnclosingFD))
7275  Mangler.mangle(EnclosingDecl);
7276  else
7277  Mangler.getStream() << EnclosingFD->getName();
7278 }
7279 
7280 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
7281  GlobalDecl EnclosingDecl, raw_ostream &Out) {
7282  CXXNameMangler Mangler(*this, Out);
7283  Mangler.getStream() << "__fin_";
7284  auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7285  if (shouldMangleDeclName(EnclosingFD))
7286  Mangler.mangle(EnclosingDecl);
7287  else
7288  Mangler.getStream() << EnclosingFD->getName();
7289 }
7290 
7291 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
7292  raw_ostream &Out) {
7293  // <special-name> ::= TH <object name>
7294  CXXNameMangler Mangler(*this, Out);
7295  Mangler.getStream() << "_ZTH";
7296  Mangler.mangleName(D);
7297 }
7298 
7299 void
7300 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
7301  raw_ostream &Out) {
7302  // <special-name> ::= TW <object name>
7303  CXXNameMangler Mangler(*this, Out);
7304  Mangler.getStream() << "_ZTW";
7305  Mangler.mangleName(D);
7306 }
7307 
7308 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
7309  unsigned ManglingNumber,
7310  raw_ostream &Out) {
7311  // We match the GCC mangling here.
7312  // <special-name> ::= GR <object name>
7313  CXXNameMangler Mangler(*this, Out);
7314  Mangler.getStream() << "_ZGR";
7315  Mangler.mangleName(D);
7316  assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
7317  Mangler.mangleSeqID(ManglingNumber - 1);
7318 }
7319 
7320 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
7321  raw_ostream &Out) {
7322  // <special-name> ::= TV <type> # virtual table
7323  CXXNameMangler Mangler(*this, Out);
7324  Mangler.getStream() << "_ZTV";
7325  Mangler.mangleNameOrStandardSubstitution(RD);
7326 }
7327 
7328 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
7329  raw_ostream &Out) {
7330  // <special-name> ::= TT <type> # VTT structure
7331  CXXNameMangler Mangler(*this, Out);
7332  Mangler.getStream() << "_ZTT";
7333  Mangler.mangleNameOrStandardSubstitution(RD);
7334 }
7335 
7336 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
7337  int64_t Offset,
7338  const CXXRecordDecl *Type,
7339  raw_ostream &Out) {
7340  // <special-name> ::= TC <type> <offset number> _ <base type>
7341  CXXNameMangler Mangler(*this, Out);
7342  Mangler.getStream() << "_ZTC";
7343  Mangler.mangleNameOrStandardSubstitution(RD);
7344  Mangler.getStream() << Offset;
7345  Mangler.getStream() << '_';
7346  Mangler.mangleNameOrStandardSubstitution(Type);
7347 }
7348 
7349 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
7350  // <special-name> ::= TI <type> # typeinfo structure
7351  assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
7352  CXXNameMangler Mangler(*this, Out);
7353  Mangler.getStream() << "_ZTI";
7354  Mangler.mangleType(Ty);
7355 }
7356 
7357 void ItaniumMangleContextImpl::mangleCXXRTTIName(
7358  QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7359  // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
7360  CXXNameMangler Mangler(*this, Out, NormalizeIntegers);
7361  Mangler.getStream() << "_ZTS";
7362  Mangler.mangleType(Ty);
7363 }
7364 
7365 void ItaniumMangleContextImpl::mangleCanonicalTypeName(
7366  QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7367  mangleCXXRTTIName(Ty, Out, NormalizeIntegers);
7368 }
7369 
7370 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
7371  llvm_unreachable("Can't mangle string literals");
7372 }
7373 
7374 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
7375  raw_ostream &Out) {
7376  CXXNameMangler Mangler(*this, Out);
7377  Mangler.mangleLambdaSig(Lambda);
7378 }
7379 
7380 void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
7381  raw_ostream &Out) {
7382  // <special-name> ::= GI <module-name> # module initializer function
7383  CXXNameMangler Mangler(*this, Out);
7384  Mangler.getStream() << "_ZGI";
7385  Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
7386  if (M->isModulePartition()) {
7387  // The partition needs including, as partitions can have them too.
7388  auto Partition = M->Name.find(':');
7389  Mangler.mangleModuleNamePrefix(
7390  StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
7391  /*IsPartition*/ true);
7392  }
7393 }
7394 
7396  DiagnosticsEngine &Diags,
7397  bool IsAux) {
7398  return new ItaniumMangleContextImpl(
7399  Context, Diags,
7400  [](ASTContext &, const NamedDecl *) -> std::optional<unsigned> {
7401  return std::nullopt;
7402  },
7403  IsAux);
7404 }
7405 
7408  DiscriminatorOverrideTy DiscriminatorOverride,
7409  bool IsAux) {
7410  return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,
7411  IsAux);
7412 }
Enums/classes describing ABI related information about constructors, destructors and thunks.
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3346
NodeId Parent
Definition: ASTDiff.cpp:191
int Depth
Definition: ASTDiff.cpp:190
StringRef P
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1659::IndirectLocalPathEntry::EntryKind Kind
Expr * E
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
llvm::APSInt APSInt
Definition: Compiler.cpp:22
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1171
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
unsigned Offset
Definition: Format.cpp:3003
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty, ASTContext &Ctx)
static bool hasMangledSubstitutionQualifiers(QualType T)
Determine whether the given type has any qualifiers that are relevant for substitutions.
static GlobalDecl getParentOfLocalEntity(const DeclContext *DC)
static StringRef mangleAArch64VectorBase(const BuiltinType *EltType)
static IdentifierInfo * getUnionInitName(SourceLocation UnionLoc, DiagnosticsEngine &Diags, const FieldDecl *FD)
static void mangleOverrideDiscrimination(CXXNameMangler &Mangler, ASTContext &Context, const ThunkInfo &Thunk)
Mangles the pointer authentication override attribute for classes that have explicit overrides for th...
static bool isZeroInitialized(QualType T, const APValue &V)
Determine whether a given value is equivalent to zero-initialization for the purpose of discarding a ...
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static bool isParenthesizedADLCallee(const CallExpr *call)
Look at the callee of the given call expression and determine if it's a parenthesized id-expression w...
static TemplateName asTemplateName(GlobalDecl GD)
static QualType getLValueType(ASTContext &Ctx, const APValue &LV)
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::Module class, which describes a module in the source code.
static StringRef getIdentifier(const Token &Tok)
uint32_t Id
Definition: SemaARM.cpp:1144
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the SourceManager interface.
Enums/classes describing THUNK related information about constructors, destructors and thunks.
Defines the clang::TypeLoc interface and its subclasses.
static const TemplateArgument & getArgument(const TemplateArgument &A)
QualType getType() const
Definition: APValue.cpp:63
A non-discriminated union of a base, field, or array index.
Definition: APValue.h:208
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition: APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
const LValueBase getLValueBase() const
Definition: APValue.cpp:974
ArrayRef< LValuePathEntry > getLValuePath() const
Definition: APValue.cpp:994
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition: APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
QualType getRecordType(const RecordDecl *Decl) const
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2649
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
bool addressSpaceMapManglingFor(LangAS AS) const
Definition: ASTContext.h:2925
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass)
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
unsigned getTargetAddressSpace(LangAS AS) const
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3746
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2726
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2755
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3576
Attr - This represents one attribute.
Definition: Attr.h:46
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6385
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3912
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2236
Opcode getOpcode() const
Definition: Expr.h:3956
Expr * getRHS() const
Definition: Expr.h:3963
Expr * getLHS() const
Definition: Expr.h:3961
A binding in a decomposition declaration.
Definition: DeclCXX.h:4111
A fixed int type of a specified bitwidth.
Definition: Type.h:7643
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4472
Pointer to a block type.
Definition: Type.h:3407
This class is used for builtin types like 'int'.
Definition: Type.h:3029
Kind getKind() const
Definition: Type.h:3081
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2497
Expr * getArgument()
Definition: ExprCXX.h:2538
bool isArrayForm() const
Definition: ExprCXX.h:2523
bool isGlobalDelete() const
Definition: ExprCXX.h:2522
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3682
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:3785
Expr * getBase() const
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:3776
unsigned getNumTemplateArgs() const
Retrieve the number of template arguments provided as part of this template-id.
Definition: ExprCXX.h:3880
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the member name.
Definition: ExprCXX.h:3793
DeclarationName getMember() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:3824
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments provided as part of this template-id.
Definition: ExprCXX.h:3871
bool isImplicitAccess() const
True if this is an implicit access, i.e.
Definition: ExprCXX.h:3768
NamedDecl * getFirstQualifierFoundInScope() const
Retrieve the first part of the nested-name-specifier that was found in the scope of the member access...
Definition: ExprCXX.h:3812
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2240
bool isArray() const
Definition: ExprCXX.h:2348
QualType getAllocatedType() const
Definition: ExprCXX.h:2318
arg_iterator placement_arg_end()
Definition: ExprCXX.h:2454
CXXNewInitializationStyle getInitializationStyle() const
The kind of initializer this new-expression has.
Definition: ExprCXX.h:2407
bool hasInitializer() const
Whether this new-expression has any initializer at all.
Definition: ExprCXX.h:2404
Expr * getInitializer()
The initializer of this new-expression.
Definition: ExprCXX.h:2413
arg_iterator placement_arg_begin()
Definition: ExprCXX.h:2451
bool isGlobalNew() const
Definition: ExprCXX.h:2401
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition: ExprCXX.h:111
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition: DeclCXX.cpp:1724
TemplateParameterList * getGenericLambdaTemplateParameterList() const
Retrieve the generic lambda's template parameter list.
Definition: DeclCXX.cpp:1701
base_class_iterator bases_end()
Definition: DeclCXX.h:629
base_class_range bases()
Definition: DeclCXX.h:620
TypeSourceInfo * getLambdaTypeInfo() const
Definition: DeclCXX.h:1866
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1023
unsigned getLambdaManglingNumber() const
If this is the closure type of a lambda expression, retrieve the number to be used for name mangling ...
Definition: DeclCXX.h:1771
base_class_iterator bases_begin()
Definition: DeclCXX.h:627
ArrayRef< NamedDecl * > getLambdaExplicitTemplateParameters() const
Retrieve the lambda template parameters that were specified explicitly.
Definition: DeclCXX.cpp:1710
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition: DeclCXX.cpp:1645
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1206
const Expr * getSubExpr() const
Definition: ExprCXX.h:1226
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition: ExprCXX.cpp:162
bool isTypeOperand() const
Definition: ExprCXX.h:881
Expr * getExprOperand() const
Definition: ExprCXX.h:892
Describes an explicit type conversion that uses functional notion but could not be resolved because o...
Definition: ExprCXX.h:3556
bool isListInitialization() const
Determine whether this expression models list-initialization.
Definition: ExprCXX.h:3611
Expr * getArg(unsigned I)
Definition: ExprCXX.h:3632
unsigned getNumArgs() const
Retrieve the number of arguments.
Definition: ExprCXX.h:3614
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
Expr * getExprOperand() const
Definition: ExprCXX.h:1107
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this __uuidof() expression after various required adjustments (removing...
Definition: ExprCXX.cpp:216
bool isTypeOperand() const
Definition: ExprCXX.h:1096
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2882
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3060
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3073
arg_range arguments()
Definition: Expr.h:3121
Expr * getCallee()
Definition: Expr.h:3032
Expr * getSubExpr()
Definition: Expr.h:3600
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3144
QualType getElementType() const
Definition: Type.h:3154
Declaration of a C++20 concept.
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4255
Expr * getLHS() const
Definition: Expr.h:4289
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4278
Expr * getRHS() const
Definition: Expr.h:4290
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3614
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4229
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isFileContext() const
Definition: DeclBase.h:2161
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool isNamespace() const
Definition: DeclBase.h:2179
bool isTranslationUnit() const
Definition: DeclBase.h:2166
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
AttrVec & getAttrs()
Definition: DeclBase.h:531
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
SourceLocation getLocation() const
Definition: DeclBase.h:446
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
void setImplicit(bool I=true)
Definition: DeclBase.h:601
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:415
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1624
bool hasAttr() const
Definition: DeclBase.h:584
Kind getKind() const
Definition: DeclBase.h:449
T * getAttr() const
Definition: DeclBase.h:580
DeclContext * getDeclContext()
Definition: DeclBase.h:455
The name of a declaration.
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:808
Represents the type decltype(expr) (C++11).
Definition: Type.h:5784
Represents a C++17 deduced template specialization type.
Definition: Type.h:6433
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3917
Expr * getAddrSpaceExpr() const
Definition: Type.h:3928
QualType getPointeeType() const
Definition: Type.h:3929
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6853
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3322
TemplateArgumentLoc const * getTemplateArgs() const
Definition: ExprCXX.h:3416
unsigned getNumTemplateArgs() const
Definition: ExprCXX.h:3423
DeclarationName getDeclName() const
Retrieve the name that this expression refers to.
Definition: ExprCXX.h:3361
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies this declaration.
Definition: ExprCXX.h:3374
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3859
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3957
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4288
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:491
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6905
NestedNameSpecifier * getQualifier() const
Definition: Type.h:6921
const IdentifierInfo * getIdentifier() const
Definition: Type.h:6922
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6924
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4083
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
bool isArrayDesignator() const
Definition: Designator.h:108
bool isArrayRangeDesignator() const
Definition: Designator.h:109
bool isFieldDesignator() const
Definition: Designator.h:107
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:193
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1553
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:879
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3275
llvm::APSInt getInitVal() const
Definition: Decl.h:3295
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6001
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3802
This represents one expression.
Definition: Expr.h:110
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3122
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3110
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3118
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4123
Represents a member of a struct/union/class.
Definition: Decl.h:3031
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3122
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4634
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3248
llvm::APFloat getValue() const
Definition: Expr.h:1652
Represents a function declaration or definition.
Definition: Decl.h:1933
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3526
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4152
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4168
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3682
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2670
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4678
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4647
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4674
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5012
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:5350
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5478
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5292
unsigned getNumParams() const
Definition: Type.h:5265
Qualifiers getMethodQuals() const
Definition: Type.h:5407
ArrayRef< QualType > exceptions() const
Definition: Type.h:5435
QualType getParamType(unsigned i) const
Definition: Type.h:5267
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5389
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5384
bool hasInstantiationDependentExceptionSpec() const
Return whether this function has an instantiation-dependent exception spec.
Definition: Type.cpp:3710
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5450
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:5415
Declaration of a template function.
Definition: DeclTemplate.h:957
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4429
CallingConv getCC() const
Definition: Type.h:4491
bool getProducesResult() const
Definition: Type.h:4478
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4318
ExtInfo getExtInfo() const
Definition: Type.h:4652
QualType getReturnType() const
Definition: Type.h:4640
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
CXXCtorType getCtorType() const
Definition: GlobalDecl.h:105
KernelReferenceKind getKernelReferenceKind() const
Definition: GlobalDecl.h:132
GlobalDecl getWithDecl(const Decl *D)
Definition: GlobalDecl.h:167
const Decl * getDecl() const
Definition: GlobalDecl.h:103
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:110
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
const Expr * getSubExpr() const
Definition: Expr.h:1729
Represents a C array with an unspecified size.
Definition: Type.h:3761
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3319
Describes an C or C++ initializer list.
Definition: Expr.h:5070
unsigned getNumInits() const
Definition: Expr.h:5100
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5116
InitListExpr * getSyntacticForm() const
Definition: Expr.h:5236
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6622
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
std::optional< unsigned >(*)(ASTContext &, const NamedDecl *) DiscriminatorOverrideTy
Definition: Mangle.h:190
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3482
ClangABI
Clang versions with different platform ABI conformance.
Definition: LangOptions.h:176
@ Ver6
Attempt to be ABI-compatible with code generated by Clang 6.0.x (SVN r321711).
@ Ver18
Attempt to be ABI-compatible with code generated by Clang 18.0.x.
@ Ver14
Attempt to be ABI-compatible with code generated by Clang 14.0.x.
@ Ver11
Attempt to be ABI-compatible with code generated by Clang 11.0.x (git 2e10b7a39b93).
@ Ver17
Attempt to be ABI-compatible with code generated by Clang 17.0.x.
@ Ver12
Attempt to be ABI-compatible with code generated by Clang 12.0.x (git 8e464dd76bef).
A global _GUID constant.
Definition: DeclCXX.h:4293
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition: Expr.h:2804
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3239
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3322
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3350
unsigned getNumTemplateArgs() const
Retrieve the number of template arguments provided as part of this template-id.
Definition: Expr.h:3404
Expr * getBase() const
Definition: Expr.h:3316
bool isArrow() const
Definition: Expr.h:3423
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments provided as part of this template-id.
Definition: Expr.h:3395
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3518
QualType getPointeeType() const
Definition: Type.h:3534
Describes a module or submodule.
Definition: Module.h:105
std::string Name
The name of this module.
Definition: Module.h:108
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition: Module.h:631
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:597
This represents a decl that may have a name.
Definition: Decl.h:249
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1916
bool isExternallyVisible() const
Definition: Decl.h:409
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3196
Represent a C++ namespace.
Definition: Decl.h:548
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:599
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:3013
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7353
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition: Type.h:7409
Represents a class type in Objective C.
Definition: Type.h:7155
decls_iterator decls_begin() const
Definition: ExprCXX.h:3075
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3086
TemplateArgumentLoc const * getTemplateArgs() const
Definition: ExprCXX.h:3136
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3098
unsigned getNumTemplateArgs() const
Definition: ExprCXX.h:3142
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3092
Represents a pack expansion of types.
Definition: Type.h:6970
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:254
Represents a parameter to a function.
Definition: Decl.h:1723
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1783
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1773
PipeType - OpenCL20.
Definition: Type.h:7609
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3197
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Definition: DeclBase.h:1287
A (possibly-)qualified type.
Definition: Type.h:941
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7849
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7800
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7781
The collection of all-type qualifiers we support.
Definition: Type.h:319
unsigned getCVRQualifiers() const
Definition: Type.h:475
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
void removeObjCLifetime()
Definition: Type.h:538
bool hasConst() const
Definition: Type.h:444
bool hasUnaligned() const
Definition: Type.h:498
bool hasAddressSpace() const
Definition: Type.h:557
bool hasRestrict() const
Definition: Type.h:464
void removeRestrict()
Definition: Type.h:466
bool hasVolatile() const
Definition: Type.h:454
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
LangAS getAddressSpace() const
Definition: Type.h:558
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3500
Represents a struct/union/class.
Definition: Decl.h:4146
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition: Decl.cpp:5043
const FieldDecl * findFirstNamedDataMember() const
Finds the first data member which has a name.
Definition: Decl.cpp:5190
field_range fields() const
Definition: Decl.h:4352
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4198
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5975
RecordDecl * getDecl() const
Definition: Type.h:5985
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:217
Encodes a location in the source.
@ NoStmtClass
Definition: Stmt.h:87
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
const char * getStmtClassName() const
Definition: Stmt.cpp:79
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:375
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6293
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3562
bool isUnion() const
Definition: Decl.h:3768
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3790
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual const char * getIbm128Mangling() const
Return the mangled code of __ibm128.
Definition: TargetInfo.h:810
virtual const char * getLongDoubleMangling() const
Return the mangled code of long double.
Definition: TargetInfo.h:804
virtual const char * getFloat128Mangling() const
Return the mangled code of __float128.
Definition: TargetInfo.h:807
virtual const char * getBFloat16Mangling() const
Return the mangled code of bfloat.
Definition: TargetInfo.h:815
A template argument list.
Definition: DeclTemplate.h:244
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:418
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:426
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:355
NameKind getKind() const
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:248
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:223
@ Template
A single template declaration.
Definition: TemplateName.h:220
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:235
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:239
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:244
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:231
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:227
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
A template parameter object.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6490
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6558
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6556
bool isTypeAlias() const
Determine if this template specialization type is for a type alias template that has been substituted...
Definition: Type.h:6549
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:260
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:250
Symbolic representation of typeid(T) for some type T.
Definition: APValue.h:44
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5707
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5757
A container of type source information.
Definition: Type.h:7731
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7742
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2767
ArrayRef< TypeSourceInfo * > getArgs() const
Retrieve the argument types.
Definition: ExprCXX.h:2823
TypeTrait getTrait() const
Determine which type trait this expression uses.
Definition: ExprCXX.h:2804
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBooleanType() const
Definition: Type.h:8475
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isDependentAddressSpaceType() const
Definition: Type.h:8151
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isArrayType() const
Definition: Type.h:8085
bool isPointerType() const
Definition: Type.h:8013
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8387
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2483
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8635
bool isReferenceType() const
Definition: Type.h:8031
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition: Type.cpp:1867
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition: Type.cpp:427
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2709
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8316
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8109
bool isOpenCLSpecificType() const
Definition: Type.h:8294
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2701
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8621
bool isPointerOrReferenceType() const
Definition: Type.h:8017
TypeClass getTypeClass() const
Definition: Type.h:2334
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8568
bool isRecordType() const
Definition: Type.h:8113
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3410
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2630
QualType getArgumentType() const
Definition: Expr.h:2673
bool isArgumentType() const
Definition: Expr.h:2672
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2662
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2240
Opcode getOpcode() const
Definition: Expr.h:2280
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1484
Expr * getSubExpr() const
Definition: Expr.h:2285
A unary type transform, which is a type constructed from another.
Definition: Type.h:5892
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3202
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3271
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3942
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4050
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4034
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:4015
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition: ExprCXX.cpp:1629
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5577
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:668
QualType getType() const
Definition: Decl.h:679
void print(llvm::raw_ostream &Out) const
Definition: Value.cpp:264
Represents a variable declaration or definition.
Definition: Decl.h:880
Represents a variable template specialization, which refers to a variable template with a given set o...
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3805
Represents a GCC generic vector type.
Definition: Type.h:4031
QualType getElementType() const
Definition: Type.h:4045
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:168
RequirementKind getKind() const
Definition: ExprConcepts.h:198
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
llvm::APFloat APFloat
Definition: Floating.h:23
llvm::APInt APInt
Definition: Integral.h:29
bool Sub(InterpState &S, CodePtr OpPC)
Definition: Interp.h:389
bool Init(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1745
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token.
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
CXXCtorType
C++ constructor types.
Definition: ABI.h:24
@ Ctor_Base
Base object ctor.
Definition: ABI.h:26
@ Ctor_DefaultClosure
Default closure variant of a ctor.
Definition: ABI.h:29
@ Ctor_CopyingClosure
Copying closure variant of a ctor.
Definition: ABI.h:28
@ Ctor_Complete
Complete object ctor.
Definition: ABI.h:25
@ Ctor_Comdat
The COMDAT used for ctors.
Definition: ABI.h:27
bool isa(CodeGen::Address addr)
Definition: Address.h:328
@ CPlusPlus
Definition: LangStandard.h:56
@ GNUAutoType
__auto_type (GNU extension)
llvm::StringRef getParameterABISpelling(ParameterABI kind)
RefQualifierKind
The kind of C++11 ref-qualifier associated with a function type.
Definition: Type.h:1776
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1778
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1781
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1784
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition: Linkage.h:63
@ CLanguageLinkage
Definition: Linkage.h:64
@ CXXLanguageLinkage
Definition: Linkage.h:65
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
@ Ordinary
This parameter uses ordinary ABI rules for its type.
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
CXXDtorType
C++ destructor types.
Definition: ABI.h:33
@ Dtor_Comdat
The COMDAT used for dtors.
Definition: ABI.h:37
@ Dtor_Base
Base object dtor.
Definition: ABI.h:36
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
@ Dtor_Deleting
Deleting dtor.
Definition: ABI.h:34
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_X86Pascal
Definition: Specifiers.h:284
@ CC_Swift
Definition: Specifiers.h:293
@ CC_IntelOclBicc
Definition: Specifiers.h:290
@ CC_OpenCLKernel
Definition: Specifiers.h:292
@ CC_PreserveMost
Definition: Specifiers.h:295
@ CC_Win64
Definition: Specifiers.h:285
@ CC_X86ThisCall
Definition: Specifiers.h:282
@ CC_AArch64VectorCall
Definition: Specifiers.h:297
@ CC_AAPCS
Definition: Specifiers.h:288
@ CC_PreserveNone
Definition: Specifiers.h:301
@ CC_C
Definition: Specifiers.h:279
@ CC_AMDGPUKernelCall
Definition: Specifiers.h:299
@ CC_M68kRTD
Definition: Specifiers.h:300
@ CC_SwiftAsync
Definition: Specifiers.h:294
@ CC_X86RegCall
Definition: Specifiers.h:287
@ CC_RISCVVectorCall
Definition: Specifiers.h:302
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_SpirFunction
Definition: Specifiers.h:291
@ CC_AArch64SVEPCS
Definition: Specifiers.h:298
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86_64SysV
Definition: Specifiers.h:286
@ CC_PreserveAll
Definition: Specifiers.h:296
@ CC_X86FastCall
Definition: Specifiers.h:281
@ CC_AAPCS_VFP
Definition: Specifiers.h:289
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Neon
is ARM Neon vector
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ NeonPoly
is ARM Neon polynomial vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
@ None
No keyword precedes the qualified type name.
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Union
The "union" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
@ Other
Other implicit parameter.
@ Braces
New-expression has a C++11 list-initializer.
@ EST_Dynamic
throw(T1, T2)
unsigned long uint64_t
long int64_t
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
#define false
Definition: stdbool.h:26
Information about how to mangle a template argument.
bool NeedExactType
Do we need to mangle the template argument with an exactly correct type?
const NamedDecl * TemplateParameterToMangle
If we need to prefix the mangling with a mangling of the template parameter, the corresponding parame...
bool isOverloadable()
Determine whether the resolved template might be overloaded on its template parameter list.
TemplateArgManglingInfo(const CXXNameMangler &Mangler, TemplateName TN)
bool needToMangleTemplateParam(const NamedDecl *Param, const TemplateArgument &Arg)
Determine whether we need to prefix this <template-arg> mangling with a <template-param-decl>.
const Expr * getTrailingRequiresClauseToMangle()
Determine if we should mangle a requires-clause after the template argument list.
Info getArgInfo(unsigned ParamIdx, const TemplateArgument &Arg)
Determine information about how this template argument should be mangled.
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
const Expr * RHS
The original right-hand side.
Definition: ExprCXX.h:310
BinaryOperatorKind Opcode
The original opcode, prior to rewriting.
Definition: ExprCXX.h:306
const Expr * LHS
The original left-hand side.
Definition: ExprCXX.h:308
bool isEmpty() const
Definition: Thunk.h:70
union clang::ReturnAdjustment::VirtualAdjustment Virtual
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition: Thunk.h:30
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:874
const Type * Ty
The locally-unqualified type.
Definition: Type.h:876
Qualifiers Quals
The local qualifiers.
Definition: Type.h:879
Iterator for iterating over Stmt * arrays that contain only T *.
Definition: Stmt.h:1316
A this pointer adjustment.
Definition: Thunk.h:92
union clang::ThisAdjustment::VirtualAdjustment Virtual
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition: Thunk.h:95
The this pointer adjustment as well as an optional return adjustment for a thunk.
Definition: Thunk.h:157
ThisAdjustment This
The this pointer adjustment.
Definition: Thunk.h:159
ReturnAdjustment Return
The return adjustment.
Definition: Thunk.h:162
const Type * ThisType
Definition: Thunk.h:173
int64_t VBaseOffsetOffset
The offset (in bytes), relative to the address point of the virtual base class offset.
Definition: Thunk.h:39
struct clang::ReturnAdjustment::VirtualAdjustment::@189 Itanium
struct clang::ThisAdjustment::VirtualAdjustment::@191 Itanium
int64_t VCallOffsetOffset
The offset (in bytes), relative to the address point, of the virtual call offset.
Definition: Thunk.h:104