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