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