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