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