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