1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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):
13 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
15 //===----------------------------------------------------------------------===//
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"
40 using namespace clang
;
44 static bool isLocalContainerContext(const DeclContext
*DC
) {
45 return isa
<FunctionDecl
>(DC
) || isa
<ObjCMethodDecl
>(DC
) || isa
<BlockDecl
>(DC
);
48 static const FunctionDecl
*getStructor(const FunctionDecl
*fn
) {
49 if (const FunctionTemplateDecl
*ftd
= fn
->getPrimaryTemplate())
50 return ftd
->getTemplatedDecl();
55 static const NamedDecl
*getStructor(const NamedDecl
*decl
) {
56 const FunctionDecl
*fn
= dyn_cast_or_null
<FunctionDecl
>(decl
);
57 return (fn
? getStructor(fn
) : decl
);
60 static bool isLambda(const NamedDecl
*ND
) {
61 const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(ND
);
65 return Record
->isLambda();
68 static const unsigned UnknownArity
= ~0U;
70 class 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;
77 bool NeedsUniqueInternalLinkageNames
= false;
80 explicit ItaniumMangleContextImpl(
81 ASTContext
&Context
, DiagnosticsEngine
&Diags
,
82 DiscriminatorOverrideTy DiscriminatorOverride
, bool IsAux
= false)
83 : ItaniumMangleContext(Context
, Diags
, IsAux
),
84 DiscriminatorOverride(DiscriminatorOverride
) {}
86 /// @name Mangler Entry Points
89 bool shouldMangleCXXName(const NamedDecl
*D
) override
;
90 bool shouldMangleStringLiteral(const StringLiteral
*) override
{
94 bool isUniqueInternalLinkageDecl(const NamedDecl
*ND
) override
;
95 void needsUniqueInternalLinkageNames() override
{
96 NeedsUniqueInternalLinkageNames
= true;
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
;
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
;
131 void mangleStringLiteral(const StringLiteral
*, raw_ostream
&) override
;
133 void mangleLambdaSig(const CXXRecordDecl
*Lambda
, raw_ostream
&) override
;
135 void mangleModuleInitializer(const Module
*Module
, raw_ostream
&) override
;
137 bool getNextDiscriminator(const NamedDecl
*ND
, unsigned &disc
) {
138 // Lambda closure types are already numbered.
142 // Anonymous tags are already numbered.
143 if (const TagDecl
*Tag
= dyn_cast
<TagDecl
>(ND
)) {
144 if (Tag
->getName().empty() && !Tag
->getTypedefNameForAnonDecl())
148 // Use the canonical number for externally visible decls.
149 if (ND
->isExternallyVisible()) {
150 unsigned discriminator
= getASTContext().getManglingNumber(ND
, isAux());
151 if (discriminator
== 1)
153 disc
= discriminator
- 2;
157 // Make up a reasonable number for internal decls.
158 unsigned &discriminator
= Uniquifier
[ND
];
159 if (!discriminator
) {
160 const DeclContext
*DC
= getEffectiveDeclContext(ND
);
161 discriminator
= ++Discriminator
[std::make_pair(DC
, ND
->getIdentifier())];
163 if (discriminator
== 1)
165 disc
= discriminator
-2;
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();
177 const ParmVarDecl
*Parm
= dyn_cast_or_null
<ParmVarDecl
>(LambdaContextDecl
);
178 const FunctionDecl
*Func
=
179 Parm
? dyn_cast
<FunctionDecl
>(Parm
->getDeclContext()) : nullptr;
182 unsigned DefaultArgNo
=
183 Func
->getNumParams() - Parm
->getFunctionScopeIndex();
184 Name
+= llvm::utostr(DefaultArgNo
);
188 if (LambdaManglingNumber
)
189 LambdaId
= LambdaManglingNumber
;
191 LambdaId
= getAnonymousStructIdForDebugInfo(Lambda
);
193 Name
+= llvm::utostr(LambdaId
);
198 DiscriminatorOverrideTy
getDiscriminatorOverride() const override
{
199 return DiscriminatorOverride
;
202 NamespaceDecl
*getStdNamespace();
204 const DeclContext
*getEffectiveDeclContext(const Decl
*D
);
205 const DeclContext
*getEffectiveParentContext(const DeclContext
*DC
) {
206 return getEffectiveDeclContext(cast
<Decl
>(DC
));
209 bool isInternalLinkageDecl(const NamedDecl
*ND
);
214 /// Manage the mangling of a single name.
215 class CXXNameMangler
{
216 ItaniumMangleContextImpl
&Context
;
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;
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;
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;
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;
240 /// The next substitution sequence number.
243 class FunctionTypeDepthState
{
246 enum { InResultTypeMask
= 1 };
249 FunctionTypeDepthState() = default;
251 /// The number of function types we're inside.
252 unsigned getDepth() const {
256 /// True if we're in the return type of the innermost function type.
257 bool isInResultType() const {
258 return Bits
& InResultTypeMask
;
261 FunctionTypeDepthState
push() {
262 FunctionTypeDepthState tmp
= *this;
263 Bits
= (Bits
& ~InResultTypeMask
) + 2;
267 void enterResultType() {
268 Bits
|= InResultTypeMask
;
271 void leaveResultType() {
272 Bits
&= ~InResultTypeMask
;
275 void pop(FunctionTypeDepthState saved
) {
276 assert(getDepth() == saved
.getDepth() + 1);
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
;
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
291 class AbiTagState final
{
293 explicit AbiTagState(AbiTagState
*&Head
) : LinkHead(Head
) {
299 AbiTagState(const AbiTagState
&) = delete;
300 AbiTagState
&operator=(const AbiTagState
&) = delete;
302 ~AbiTagState() { pop(); }
304 void write(raw_ostream
&Out
, const NamedDecl
*ND
,
305 const AbiTagList
*AdditionalAbiTags
) {
306 ND
= cast
<NamedDecl
>(ND
->getCanonicalDecl());
307 if (!isa
<FunctionDecl
>(ND
) && !isa
<VarDecl
>(ND
)) {
309 !AdditionalAbiTags
&&
310 "only function and variables need a list of additional abi tags");
311 if (const auto *NS
= dyn_cast
<NamespaceDecl
>(ND
)) {
312 if (const auto *AbiTag
= NS
->getAttr
<AbiTagAttr
>()) {
313 UsedAbiTags
.insert(UsedAbiTags
.end(), AbiTag
->tags().begin(),
314 AbiTag
->tags().end());
316 // Don't emit abi tags for namespaces.
322 if (const auto *AbiTag
= ND
->getAttr
<AbiTagAttr
>()) {
323 UsedAbiTags
.insert(UsedAbiTags
.end(), AbiTag
->tags().begin(),
324 AbiTag
->tags().end());
325 TagList
.insert(TagList
.end(), AbiTag
->tags().begin(),
326 AbiTag
->tags().end());
329 if (AdditionalAbiTags
) {
330 UsedAbiTags
.insert(UsedAbiTags
.end(), AdditionalAbiTags
->begin(),
331 AdditionalAbiTags
->end());
332 TagList
.insert(TagList
.end(), AdditionalAbiTags
->begin(),
333 AdditionalAbiTags
->end());
337 TagList
.erase(std::unique(TagList
.begin(), TagList
.end()), TagList
.end());
339 writeSortedUniqueAbiTags(Out
, TagList
);
342 const AbiTagList
&getUsedAbiTags() const { return UsedAbiTags
; }
343 void setUsedAbiTags(const AbiTagList
&AbiTags
) {
344 UsedAbiTags
= AbiTags
;
347 const AbiTagList
&getEmittedAbiTags() const {
348 return EmittedAbiTags
;
351 const AbiTagList
&getSortedUniqueUsedAbiTags() {
352 llvm::sort(UsedAbiTags
);
353 UsedAbiTags
.erase(std::unique(UsedAbiTags
.begin(), UsedAbiTags
.end()),
359 //! All abi tags used implicitly or explicitly.
360 AbiTagList UsedAbiTags
;
361 //! All explicit abi tags (i.e. not from namespace).
362 AbiTagList EmittedAbiTags
;
364 AbiTagState
*&LinkHead
;
365 AbiTagState
*Parent
= nullptr;
368 assert(LinkHead
== this &&
369 "abi tag link head must point to us on destruction");
371 Parent
->UsedAbiTags
.insert(Parent
->UsedAbiTags
.end(),
372 UsedAbiTags
.begin(), UsedAbiTags
.end());
373 Parent
->EmittedAbiTags
.insert(Parent
->EmittedAbiTags
.end(),
374 EmittedAbiTags
.begin(),
375 EmittedAbiTags
.end());
380 void writeSortedUniqueAbiTags(raw_ostream
&Out
, const AbiTagList
&AbiTags
) {
381 for (const auto &Tag
: AbiTags
) {
382 EmittedAbiTags
.push_back(Tag
);
390 AbiTagState
*AbiTags
= nullptr;
391 AbiTagState AbiTagsRoot
;
393 llvm::DenseMap
<uintptr_t, unsigned> Substitutions
;
394 llvm::DenseMap
<StringRef
, unsigned> ModuleSubstitutions
;
396 ASTContext
&getASTContext() const { return Context
.getASTContext(); }
398 bool isCompatibleWith(LangOptions::ClangABI Ver
) {
399 return Context
.getASTContext().getLangOpts().getClangABICompat() <= Ver
;
402 bool isStd(const NamespaceDecl
*NS
);
403 bool isStdNamespace(const DeclContext
*DC
);
405 const RecordDecl
*GetLocalClassDecl(const Decl
*D
);
406 bool isSpecializedAs(QualType S
, llvm::StringRef Name
, QualType A
);
407 bool isStdCharSpecialization(const ClassTemplateSpecializationDecl
*SD
,
408 llvm::StringRef Name
, bool HasAllocator
);
411 CXXNameMangler(ItaniumMangleContextImpl
&C
, raw_ostream
&Out_
,
412 const NamedDecl
*D
= nullptr, bool NullOut_
= false)
413 : Context(C
), Out(Out_
), NullOut(NullOut_
), Structor(getStructor(D
)),
414 AbiTagsRoot(AbiTags
) {
415 // These can't be mangled without a ctor type or dtor type.
416 assert(!D
|| (!isa
<CXXDestructorDecl
>(D
) &&
417 !isa
<CXXConstructorDecl
>(D
)));
419 CXXNameMangler(ItaniumMangleContextImpl
&C
, raw_ostream
&Out_
,
420 const CXXConstructorDecl
*D
, CXXCtorType Type
)
421 : Context(C
), Out(Out_
), Structor(getStructor(D
)), StructorType(Type
),
422 AbiTagsRoot(AbiTags
) {}
423 CXXNameMangler(ItaniumMangleContextImpl
&C
, raw_ostream
&Out_
,
424 const CXXDestructorDecl
*D
, CXXDtorType Type
)
425 : Context(C
), Out(Out_
), Structor(getStructor(D
)), StructorType(Type
),
426 AbiTagsRoot(AbiTags
) {}
428 CXXNameMangler(ItaniumMangleContextImpl
&C
, raw_ostream
&Out_
,
429 bool NormalizeIntegers_
)
430 : Context(C
), Out(Out_
), NormalizeIntegers(NormalizeIntegers_
),
431 NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags
) {}
432 CXXNameMangler(CXXNameMangler
&Outer
, raw_ostream
&Out_
)
433 : Context(Outer
.Context
), Out(Out_
), Structor(Outer
.Structor
),
434 StructorType(Outer
.StructorType
), SeqID(Outer
.SeqID
),
435 FunctionTypeDepth(Outer
.FunctionTypeDepth
), AbiTagsRoot(AbiTags
),
436 Substitutions(Outer
.Substitutions
),
437 ModuleSubstitutions(Outer
.ModuleSubstitutions
) {}
439 CXXNameMangler(CXXNameMangler
&Outer
, llvm::raw_null_ostream
&Out_
)
440 : CXXNameMangler(Outer
, (raw_ostream
&)Out_
) {
444 struct WithTemplateDepthOffset
{ unsigned Offset
; };
445 CXXNameMangler(ItaniumMangleContextImpl
&C
, raw_ostream
&Out
,
446 WithTemplateDepthOffset Offset
)
447 : CXXNameMangler(C
, Out
) {
448 TemplateDepthOffset
= Offset
.Offset
;
451 raw_ostream
&getStream() { return Out
; }
453 void disableDerivedAbiTags() { DisableDerivedAbiTags
= true; }
454 static bool shouldHaveAbiTags(ItaniumMangleContextImpl
&C
, const VarDecl
*VD
);
456 void mangle(GlobalDecl GD
);
457 void mangleCallOffset(int64_t NonVirtual
, int64_t Virtual
);
458 void mangleNumber(const llvm::APSInt
&I
);
459 void mangleNumber(int64_t Number
);
460 void mangleFloat(const llvm::APFloat
&F
);
461 void mangleFunctionEncoding(GlobalDecl GD
);
462 void mangleSeqID(unsigned SeqID
);
463 void mangleName(GlobalDecl GD
);
464 void mangleType(QualType T
);
465 void mangleCXXRecordDecl(const CXXRecordDecl
*Record
);
466 void mangleLambdaSig(const CXXRecordDecl
*Lambda
);
467 void mangleModuleNamePrefix(StringRef Name
, bool IsPartition
= false);
468 void mangleVendorQualifier(StringRef Name
);
469 void mangleVendorType(StringRef Name
);
473 bool mangleSubstitution(const NamedDecl
*ND
);
474 bool mangleSubstitution(NestedNameSpecifier
*NNS
);
475 bool mangleSubstitution(QualType T
);
476 bool mangleSubstitution(TemplateName Template
);
477 bool mangleSubstitution(uintptr_t Ptr
);
479 void mangleExistingSubstitution(TemplateName name
);
481 bool mangleStandardSubstitution(const NamedDecl
*ND
);
483 void addSubstitution(const NamedDecl
*ND
) {
484 ND
= cast
<NamedDecl
>(ND
->getCanonicalDecl());
486 addSubstitution(reinterpret_cast<uintptr_t>(ND
));
488 void addSubstitution(NestedNameSpecifier
*NNS
) {
489 NNS
= Context
.getASTContext().getCanonicalNestedNameSpecifier(NNS
);
491 addSubstitution(reinterpret_cast<uintptr_t>(NNS
));
493 void addSubstitution(QualType T
);
494 void addSubstitution(TemplateName Template
);
495 void addSubstitution(uintptr_t Ptr
);
496 // Destructive copy substitutions from other mangler.
497 void extendSubstitutions(CXXNameMangler
* Other
);
499 void mangleUnresolvedPrefix(NestedNameSpecifier
*qualifier
,
500 bool recursive
= false);
501 void mangleUnresolvedName(NestedNameSpecifier
*qualifier
,
502 DeclarationName name
,
503 const TemplateArgumentLoc
*TemplateArgs
,
504 unsigned NumTemplateArgs
,
505 unsigned KnownArity
= UnknownArity
);
507 void mangleFunctionEncodingBareType(const FunctionDecl
*FD
);
509 void mangleNameWithAbiTags(GlobalDecl GD
,
510 const AbiTagList
*AdditionalAbiTags
);
511 void mangleModuleName(const NamedDecl
*ND
);
512 void mangleTemplateName(const TemplateDecl
*TD
,
513 ArrayRef
<TemplateArgument
> Args
);
514 void mangleUnqualifiedName(GlobalDecl GD
, const DeclContext
*DC
,
515 const AbiTagList
*AdditionalAbiTags
) {
516 mangleUnqualifiedName(GD
, cast
<NamedDecl
>(GD
.getDecl())->getDeclName(), DC
,
517 UnknownArity
, AdditionalAbiTags
);
519 void mangleUnqualifiedName(GlobalDecl GD
, DeclarationName Name
,
520 const DeclContext
*DC
, unsigned KnownArity
,
521 const AbiTagList
*AdditionalAbiTags
);
522 void mangleUnscopedName(GlobalDecl GD
, const DeclContext
*DC
,
523 const AbiTagList
*AdditionalAbiTags
);
524 void mangleUnscopedTemplateName(GlobalDecl GD
, const DeclContext
*DC
,
525 const AbiTagList
*AdditionalAbiTags
);
526 void mangleSourceName(const IdentifierInfo
*II
);
527 void mangleRegCallName(const IdentifierInfo
*II
);
528 void mangleDeviceStubName(const IdentifierInfo
*II
);
529 void mangleSourceNameWithAbiTags(
530 const NamedDecl
*ND
, const AbiTagList
*AdditionalAbiTags
= nullptr);
531 void mangleLocalName(GlobalDecl GD
,
532 const AbiTagList
*AdditionalAbiTags
);
533 void mangleBlockForPrefix(const BlockDecl
*Block
);
534 void mangleUnqualifiedBlock(const BlockDecl
*Block
);
535 void mangleTemplateParamDecl(const NamedDecl
*Decl
);
536 void mangleTemplateParameterList(const TemplateParameterList
*Params
);
537 void mangleTypeConstraint(const ConceptDecl
*Concept
,
538 ArrayRef
<TemplateArgument
> Arguments
);
539 void mangleTypeConstraint(const TypeConstraint
*Constraint
);
540 void mangleRequiresClause(const Expr
*RequiresClause
);
541 void mangleLambda(const CXXRecordDecl
*Lambda
);
542 void mangleNestedName(GlobalDecl GD
, const DeclContext
*DC
,
543 const AbiTagList
*AdditionalAbiTags
,
544 bool NoFunction
=false);
545 void mangleNestedName(const TemplateDecl
*TD
,
546 ArrayRef
<TemplateArgument
> Args
);
547 void mangleNestedNameWithClosurePrefix(GlobalDecl GD
,
548 const NamedDecl
*PrefixND
,
549 const AbiTagList
*AdditionalAbiTags
);
550 void manglePrefix(NestedNameSpecifier
*qualifier
);
551 void manglePrefix(const DeclContext
*DC
, bool NoFunction
=false);
552 void manglePrefix(QualType type
);
553 void mangleTemplatePrefix(GlobalDecl GD
, bool NoFunction
=false);
554 void mangleTemplatePrefix(TemplateName Template
);
555 const NamedDecl
*getClosurePrefix(const Decl
*ND
);
556 void mangleClosurePrefix(const NamedDecl
*ND
, bool NoFunction
= false);
557 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType
,
558 StringRef Prefix
= "");
559 void mangleOperatorName(DeclarationName Name
, unsigned Arity
);
560 void mangleOperatorName(OverloadedOperatorKind OO
, unsigned Arity
);
561 void mangleQualifiers(Qualifiers Quals
, const DependentAddressSpaceType
*DAST
= nullptr);
562 void mangleRefQualifier(RefQualifierKind RefQualifier
);
564 void mangleObjCMethodName(const ObjCMethodDecl
*MD
);
566 // Declare manglers for every type class.
567 #define ABSTRACT_TYPE(CLASS, PARENT)
568 #define NON_CANONICAL_TYPE(CLASS, PARENT)
569 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
570 #include "clang/AST/TypeNodes.inc"
572 void mangleType(const TagType
*);
573 void mangleType(TemplateName
);
574 static StringRef
getCallingConvQualifierName(CallingConv CC
);
575 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info
);
576 void mangleExtFunctionInfo(const FunctionType
*T
);
577 void mangleBareFunctionType(const FunctionProtoType
*T
, bool MangleReturnType
,
578 const FunctionDecl
*FD
= nullptr);
579 void mangleNeonVectorType(const VectorType
*T
);
580 void mangleNeonVectorType(const DependentVectorType
*T
);
581 void mangleAArch64NeonVectorType(const VectorType
*T
);
582 void mangleAArch64NeonVectorType(const DependentVectorType
*T
);
583 void mangleAArch64FixedSveVectorType(const VectorType
*T
);
584 void mangleAArch64FixedSveVectorType(const DependentVectorType
*T
);
585 void mangleRISCVFixedRVVVectorType(const VectorType
*T
);
586 void mangleRISCVFixedRVVVectorType(const DependentVectorType
*T
);
588 void mangleIntegerLiteral(QualType T
, const llvm::APSInt
&Value
);
589 void mangleFloatLiteral(QualType T
, const llvm::APFloat
&V
);
590 void mangleFixedPointLiteral();
591 void mangleNullPointer(QualType T
);
593 void mangleMemberExprBase(const Expr
*base
, bool isArrow
);
594 void mangleMemberExpr(const Expr
*base
, bool isArrow
,
595 NestedNameSpecifier
*qualifier
,
596 NamedDecl
*firstQualifierLookup
,
597 DeclarationName name
,
598 const TemplateArgumentLoc
*TemplateArgs
,
599 unsigned NumTemplateArgs
,
600 unsigned knownArity
);
601 void mangleCastExpression(const Expr
*E
, StringRef CastEncoding
);
602 void mangleInitListElements(const InitListExpr
*InitList
);
603 void mangleRequirement(SourceLocation RequiresExprLoc
,
604 const concepts::Requirement
*Req
);
605 void mangleExpression(const Expr
*E
, unsigned Arity
= UnknownArity
,
606 bool AsTemplateArg
= false);
607 void mangleCXXCtorType(CXXCtorType T
, const CXXRecordDecl
*InheritedFrom
);
608 void mangleCXXDtorType(CXXDtorType T
);
610 struct TemplateArgManglingInfo
;
611 void mangleTemplateArgs(TemplateName TN
,
612 const TemplateArgumentLoc
*TemplateArgs
,
613 unsigned NumTemplateArgs
);
614 void mangleTemplateArgs(TemplateName TN
, ArrayRef
<TemplateArgument
> Args
);
615 void mangleTemplateArgs(TemplateName TN
, const TemplateArgumentList
&AL
);
616 void mangleTemplateArg(TemplateArgManglingInfo
&Info
, unsigned Index
,
618 void mangleTemplateArg(TemplateArgument A
, bool NeedExactType
);
619 void mangleTemplateArgExpr(const Expr
*E
);
620 void mangleValueInTemplateArg(QualType T
, const APValue
&V
, bool TopLevel
,
621 bool NeedExactType
= false);
623 void mangleTemplateParameter(unsigned Depth
, unsigned Index
);
625 void mangleFunctionParam(const ParmVarDecl
*parm
);
627 void writeAbiTags(const NamedDecl
*ND
,
628 const AbiTagList
*AdditionalAbiTags
);
630 // Returns sorted unique list of ABI tags.
631 AbiTagList
makeFunctionReturnTypeTags(const FunctionDecl
*FD
);
632 // Returns sorted unique list of ABI tags.
633 AbiTagList
makeVariableTypeTags(const VarDecl
*VD
);
638 NamespaceDecl
*ItaniumMangleContextImpl::getStdNamespace() {
640 StdNamespace
= NamespaceDecl::Create(
641 getASTContext(), getASTContext().getTranslationUnitDecl(),
642 /*Inline=*/false, SourceLocation(), SourceLocation(),
643 &getASTContext().Idents
.get("std"),
644 /*PrevDecl=*/nullptr, /*Nested=*/false);
645 StdNamespace
->setImplicit();
650 /// Retrieve the declaration context that should be used when mangling the given
653 ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl
*D
) {
654 // The ABI assumes that lambda closure types that occur within
655 // default arguments live in the context of the function. However, due to
656 // the way in which Clang parses and creates function declarations, this is
657 // not the case: the lambda closure type ends up living in the context
658 // where the function itself resides, because the function declaration itself
659 // had not yet been created. Fix the context here.
660 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
)) {
662 if (ParmVarDecl
*ContextParam
=
663 dyn_cast_or_null
<ParmVarDecl
>(RD
->getLambdaContextDecl()))
664 return ContextParam
->getDeclContext();
667 // Perform the same check for block literals.
668 if (const BlockDecl
*BD
= dyn_cast
<BlockDecl
>(D
)) {
669 if (ParmVarDecl
*ContextParam
=
670 dyn_cast_or_null
<ParmVarDecl
>(BD
->getBlockManglingContextDecl()))
671 return ContextParam
->getDeclContext();
674 // On ARM and AArch64, the va_list tag is always mangled as if in the std
675 // namespace. We do not represent va_list as actually being in the std
676 // namespace in C because this would result in incorrect debug info in C,
677 // among other things. It is important for both languages to have the same
678 // mangling in order for -fsanitize=cfi-icall to work.
679 if (D
== getASTContext().getVaListTagDecl()) {
680 const llvm::Triple
&T
= getASTContext().getTargetInfo().getTriple();
681 if (T
.isARM() || T
.isThumb() || T
.isAArch64())
682 return getStdNamespace();
685 const DeclContext
*DC
= D
->getDeclContext();
686 if (isa
<CapturedDecl
>(DC
) || isa
<OMPDeclareReductionDecl
>(DC
) ||
687 isa
<OMPDeclareMapperDecl
>(DC
)) {
688 return getEffectiveDeclContext(cast
<Decl
>(DC
));
691 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
693 return getASTContext().getTranslationUnitDecl();
695 if (const auto *FD
= getASTContext().getLangOpts().getClangABICompat() >
696 LangOptions::ClangABI::Ver19
698 : dyn_cast
<FunctionDecl
>(D
)) {
700 return getASTContext().getTranslationUnitDecl();
701 // Member-like constrained friends are mangled as if they were members of
702 // the enclosing class.
703 if (FD
->isMemberLikeConstrainedFriend() &&
704 getASTContext().getLangOpts().getClangABICompat() >
705 LangOptions::ClangABI::Ver17
)
706 return D
->getLexicalDeclContext()->getRedeclContext();
709 return DC
->getRedeclContext();
712 bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl
*ND
) {
713 if (ND
&& ND
->getFormalLinkage() == Linkage::Internal
&&
714 !ND
->isExternallyVisible() &&
715 getEffectiveDeclContext(ND
)->isFileContext() &&
716 !ND
->isInAnonymousNamespace())
721 // Check if this Function Decl needs a unique internal linkage name.
722 bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
723 const NamedDecl
*ND
) {
724 if (!NeedsUniqueInternalLinkageNames
|| !ND
)
727 const auto *FD
= dyn_cast
<FunctionDecl
>(ND
);
731 // For C functions without prototypes, return false as their
732 // names should not be mangled.
733 if (!FD
->getType()->getAs
<FunctionProtoType
>())
736 if (isInternalLinkageDecl(ND
))
742 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl
*D
) {
743 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
744 LanguageLinkage L
= FD
->getLanguageLinkage();
745 // Overloadable functions need mangling.
746 if (FD
->hasAttr
<OverloadableAttr
>())
749 // "main" is not mangled.
753 // The Windows ABI expects that we would never mangle "typical"
754 // user-defined entry points regardless of visibility or freestanding-ness.
756 // N.B. This is distinct from asking about "main". "main" has a lot of
757 // special rules associated with it in the standard while these
758 // user-defined entry points are outside of the purview of the standard.
759 // For example, there can be only one definition for "main" in a standards
760 // compliant program; however nothing forbids the existence of wmain and
761 // WinMain in the same translation unit.
762 if (FD
->isMSVCRTEntryPoint())
765 // C++ functions and those whose names are not a simple identifier need
767 if (!FD
->getDeclName().isIdentifier() || L
== CXXLanguageLinkage
)
770 // C functions are not mangled.
771 if (L
== CLanguageLinkage
)
775 // Otherwise, no mangling is done outside C++ mode.
776 if (!getASTContext().getLangOpts().CPlusPlus
)
779 if (const auto *VD
= dyn_cast
<VarDecl
>(D
)) {
780 // Decompositions are mangled.
781 if (isa
<DecompositionDecl
>(VD
))
784 // C variables are not mangled.
788 // Variables at global scope are not mangled unless they have internal
789 // linkage or are specializations or are attached to a named module.
790 const DeclContext
*DC
= getEffectiveDeclContext(D
);
791 // Check for extern variable declared locally.
792 if (DC
->isFunctionOrMethod() && D
->hasLinkage())
793 while (!DC
->isFileContext())
794 DC
= getEffectiveParentContext(DC
);
795 if (DC
->isTranslationUnit() && D
->getFormalLinkage() != Linkage::Internal
&&
796 !CXXNameMangler::shouldHaveAbiTags(*this, VD
) &&
797 !isa
<VarTemplateSpecializationDecl
>(VD
) &&
798 !VD
->getOwningModuleForLinkage())
805 void CXXNameMangler::writeAbiTags(const NamedDecl
*ND
,
806 const AbiTagList
*AdditionalAbiTags
) {
807 assert(AbiTags
&& "require AbiTagState");
808 AbiTags
->write(Out
, ND
, DisableDerivedAbiTags
? nullptr : AdditionalAbiTags
);
811 void CXXNameMangler::mangleSourceNameWithAbiTags(
812 const NamedDecl
*ND
, const AbiTagList
*AdditionalAbiTags
) {
813 mangleSourceName(ND
->getIdentifier());
814 writeAbiTags(ND
, AdditionalAbiTags
);
817 void CXXNameMangler::mangle(GlobalDecl GD
) {
818 // <mangled-name> ::= _Z <encoding>
820 // ::= <special-name>
822 if (isa
<FunctionDecl
>(GD
.getDecl()))
823 mangleFunctionEncoding(GD
);
824 else if (isa
<VarDecl
, FieldDecl
, MSGuidDecl
, TemplateParamObjectDecl
,
825 BindingDecl
>(GD
.getDecl()))
827 else if (const IndirectFieldDecl
*IFD
=
828 dyn_cast
<IndirectFieldDecl
>(GD
.getDecl()))
829 mangleName(IFD
->getAnonField());
831 llvm_unreachable("unexpected kind of global decl");
834 void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD
) {
835 const FunctionDecl
*FD
= cast
<FunctionDecl
>(GD
.getDecl());
836 // <encoding> ::= <function name> <bare-function-type>
838 // Don't mangle in the type if this isn't a decl we should typically mangle.
839 if (!Context
.shouldMangleDeclName(FD
)) {
844 AbiTagList ReturnTypeAbiTags
= makeFunctionReturnTypeTags(FD
);
845 if (ReturnTypeAbiTags
.empty()) {
846 // There are no tags for return type, the simplest case. Enter the function
847 // parameter scope before mangling the name, because a template using
848 // constrained `auto` can have references to its parameters within its
849 // template argument list:
851 // template<typename T> void f(T x, C<decltype(x)> auto)
852 // ... is mangled as ...
853 // template<typename T, C<decltype(param 1)> U> void f(T, U)
854 FunctionTypeDepthState Saved
= FunctionTypeDepth
.push();
856 FunctionTypeDepth
.pop(Saved
);
857 mangleFunctionEncodingBareType(FD
);
861 // Mangle function name and encoding to temporary buffer.
862 // We have to output name and encoding to the same mangler to get the same
863 // substitution as it will be in final mangling.
864 SmallString
<256> FunctionEncodingBuf
;
865 llvm::raw_svector_ostream
FunctionEncodingStream(FunctionEncodingBuf
);
866 CXXNameMangler
FunctionEncodingMangler(*this, FunctionEncodingStream
);
867 // Output name of the function.
868 FunctionEncodingMangler
.disableDerivedAbiTags();
870 FunctionTypeDepthState Saved
= FunctionTypeDepth
.push();
871 FunctionEncodingMangler
.mangleNameWithAbiTags(FD
, nullptr);
872 FunctionTypeDepth
.pop(Saved
);
874 // Remember length of the function name in the buffer.
875 size_t EncodingPositionStart
= FunctionEncodingStream
.str().size();
876 FunctionEncodingMangler
.mangleFunctionEncodingBareType(FD
);
878 // Get tags from return type that are not present in function name or
880 const AbiTagList
&UsedAbiTags
=
881 FunctionEncodingMangler
.AbiTagsRoot
.getSortedUniqueUsedAbiTags();
882 AbiTagList
AdditionalAbiTags(ReturnTypeAbiTags
.size());
883 AdditionalAbiTags
.erase(
884 std::set_difference(ReturnTypeAbiTags
.begin(), ReturnTypeAbiTags
.end(),
885 UsedAbiTags
.begin(), UsedAbiTags
.end(),
886 AdditionalAbiTags
.begin()),
887 AdditionalAbiTags
.end());
889 // Output name with implicit tags and function encoding from temporary buffer.
890 Saved
= FunctionTypeDepth
.push();
891 mangleNameWithAbiTags(FD
, &AdditionalAbiTags
);
892 FunctionTypeDepth
.pop(Saved
);
893 Out
<< FunctionEncodingStream
.str().substr(EncodingPositionStart
);
895 // Function encoding could create new substitutions so we have to add
896 // temp mangled substitutions to main mangler.
897 extendSubstitutions(&FunctionEncodingMangler
);
900 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl
*FD
) {
901 if (FD
->hasAttr
<EnableIfAttr
>()) {
902 FunctionTypeDepthState Saved
= FunctionTypeDepth
.push();
903 Out
<< "Ua9enable_ifI";
904 for (AttrVec::const_iterator I
= FD
->getAttrs().begin(),
905 E
= FD
->getAttrs().end();
907 EnableIfAttr
*EIA
= dyn_cast
<EnableIfAttr
>(*I
);
910 if (isCompatibleWith(LangOptions::ClangABI::Ver11
)) {
911 // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
912 // even though <template-arg> should not include an X/E around
915 mangleExpression(EIA
->getCond());
918 mangleTemplateArgExpr(EIA
->getCond());
922 FunctionTypeDepth
.pop(Saved
);
925 // When mangling an inheriting constructor, the bare function type used is
926 // that of the inherited constructor.
927 if (auto *CD
= dyn_cast
<CXXConstructorDecl
>(FD
))
928 if (auto Inherited
= CD
->getInheritedConstructor())
929 FD
= Inherited
.getConstructor();
931 // Whether the mangling of a function type includes the return type depends on
932 // the context and the nature of the function. The rules for deciding whether
933 // the return type is included are:
935 // 1. Template functions (names or types) have return types encoded, with
936 // the exceptions listed below.
937 // 2. Function types not appearing as part of a function name mangling,
938 // e.g. parameters, pointer types, etc., have return type encoded, with the
939 // exceptions listed below.
940 // 3. Non-template function names do not have return types encoded.
942 // The exceptions mentioned in (1) and (2) above, for which the return type is
943 // never included, are
946 // 3. Conversion operator functions, e.g. operator int.
947 bool MangleReturnType
= false;
948 if (FunctionTemplateDecl
*PrimaryTemplate
= FD
->getPrimaryTemplate()) {
949 if (!(isa
<CXXConstructorDecl
>(FD
) || isa
<CXXDestructorDecl
>(FD
) ||
950 isa
<CXXConversionDecl
>(FD
)))
951 MangleReturnType
= true;
953 // Mangle the type of the primary template.
954 FD
= PrimaryTemplate
->getTemplatedDecl();
957 mangleBareFunctionType(FD
->getType()->castAs
<FunctionProtoType
>(),
958 MangleReturnType
, FD
);
961 /// Return whether a given namespace is the 'std' namespace.
962 bool CXXNameMangler::isStd(const NamespaceDecl
*NS
) {
963 if (!Context
.getEffectiveParentContext(NS
)->isTranslationUnit())
966 const IdentifierInfo
*II
= NS
->getFirstDecl()->getIdentifier();
967 return II
&& II
->isStr("std");
970 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
972 bool CXXNameMangler::isStdNamespace(const DeclContext
*DC
) {
973 if (!DC
->isNamespace())
976 return isStd(cast
<NamespaceDecl
>(DC
));
979 static const GlobalDecl
980 isTemplate(GlobalDecl GD
, const TemplateArgumentList
*&TemplateArgs
) {
981 const NamedDecl
*ND
= cast
<NamedDecl
>(GD
.getDecl());
982 // Check if we have a function template.
983 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(ND
)) {
984 if (const TemplateDecl
*TD
= FD
->getPrimaryTemplate()) {
985 TemplateArgs
= FD
->getTemplateSpecializationArgs();
986 return GD
.getWithDecl(TD
);
990 // Check if we have a class template.
991 if (const ClassTemplateSpecializationDecl
*Spec
=
992 dyn_cast
<ClassTemplateSpecializationDecl
>(ND
)) {
993 TemplateArgs
= &Spec
->getTemplateArgs();
994 return GD
.getWithDecl(Spec
->getSpecializedTemplate());
997 // Check if we have a variable template.
998 if (const VarTemplateSpecializationDecl
*Spec
=
999 dyn_cast
<VarTemplateSpecializationDecl
>(ND
)) {
1000 TemplateArgs
= &Spec
->getTemplateArgs();
1001 return GD
.getWithDecl(Spec
->getSpecializedTemplate());
1004 return GlobalDecl();
1007 static TemplateName
asTemplateName(GlobalDecl GD
) {
1008 const TemplateDecl
*TD
= dyn_cast_or_null
<TemplateDecl
>(GD
.getDecl());
1009 return TemplateName(const_cast<TemplateDecl
*>(TD
));
1012 void CXXNameMangler::mangleName(GlobalDecl GD
) {
1013 const NamedDecl
*ND
= cast
<NamedDecl
>(GD
.getDecl());
1014 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(ND
)) {
1015 // Variables should have implicit tags from its type.
1016 AbiTagList VariableTypeAbiTags
= makeVariableTypeTags(VD
);
1017 if (VariableTypeAbiTags
.empty()) {
1018 // Simple case no variable type tags.
1019 mangleNameWithAbiTags(VD
, nullptr);
1023 // Mangle variable name to null stream to collect tags.
1024 llvm::raw_null_ostream NullOutStream
;
1025 CXXNameMangler
VariableNameMangler(*this, NullOutStream
);
1026 VariableNameMangler
.disableDerivedAbiTags();
1027 VariableNameMangler
.mangleNameWithAbiTags(VD
, nullptr);
1029 // Get tags from variable type that are not present in its name.
1030 const AbiTagList
&UsedAbiTags
=
1031 VariableNameMangler
.AbiTagsRoot
.getSortedUniqueUsedAbiTags();
1032 AbiTagList
AdditionalAbiTags(VariableTypeAbiTags
.size());
1033 AdditionalAbiTags
.erase(
1034 std::set_difference(VariableTypeAbiTags
.begin(),
1035 VariableTypeAbiTags
.end(), UsedAbiTags
.begin(),
1036 UsedAbiTags
.end(), AdditionalAbiTags
.begin()),
1037 AdditionalAbiTags
.end());
1039 // Output name with implicit tags.
1040 mangleNameWithAbiTags(VD
, &AdditionalAbiTags
);
1042 mangleNameWithAbiTags(GD
, nullptr);
1046 const RecordDecl
*CXXNameMangler::GetLocalClassDecl(const Decl
*D
) {
1047 const DeclContext
*DC
= Context
.getEffectiveDeclContext(D
);
1048 while (!DC
->isNamespace() && !DC
->isTranslationUnit()) {
1049 if (isLocalContainerContext(DC
))
1050 return dyn_cast
<RecordDecl
>(D
);
1052 DC
= Context
.getEffectiveDeclContext(D
);
1057 void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD
,
1058 const AbiTagList
*AdditionalAbiTags
) {
1059 const NamedDecl
*ND
= cast
<NamedDecl
>(GD
.getDecl());
1060 // <name> ::= [<module-name>] <nested-name>
1061 // ::= [<module-name>] <unscoped-name>
1062 // ::= [<module-name>] <unscoped-template-name> <template-args>
1065 const DeclContext
*DC
= Context
.getEffectiveDeclContext(ND
);
1066 bool IsLambda
= isLambda(ND
);
1068 // If this is an extern variable declared locally, the relevant DeclContext
1069 // is that of the containing namespace, or the translation unit.
1070 // FIXME: This is a hack; extern variables declared locally should have
1071 // a proper semantic declaration context!
1072 if (isLocalContainerContext(DC
) && ND
->hasLinkage() && !IsLambda
)
1073 while (!DC
->isNamespace() && !DC
->isTranslationUnit())
1074 DC
= Context
.getEffectiveParentContext(DC
);
1075 else if (GetLocalClassDecl(ND
) &&
1076 (!IsLambda
|| isCompatibleWith(LangOptions::ClangABI::Ver18
))) {
1077 mangleLocalName(GD
, AdditionalAbiTags
);
1081 assert(!isa
<LinkageSpecDecl
>(DC
) && "context cannot be LinkageSpecDecl");
1083 // Closures can require a nested-name mangling even if they're semantically
1084 // in the global namespace.
1085 if (const NamedDecl
*PrefixND
= getClosurePrefix(ND
)) {
1086 mangleNestedNameWithClosurePrefix(GD
, PrefixND
, AdditionalAbiTags
);
1090 if (isLocalContainerContext(DC
)) {
1091 mangleLocalName(GD
, AdditionalAbiTags
);
1095 if (DC
->isTranslationUnit() || isStdNamespace(DC
)) {
1096 // Check if we have a template.
1097 const TemplateArgumentList
*TemplateArgs
= nullptr;
1098 if (GlobalDecl TD
= isTemplate(GD
, TemplateArgs
)) {
1099 mangleUnscopedTemplateName(TD
, DC
, AdditionalAbiTags
);
1100 mangleTemplateArgs(asTemplateName(TD
), *TemplateArgs
);
1104 mangleUnscopedName(GD
, DC
, AdditionalAbiTags
);
1108 mangleNestedName(GD
, DC
, AdditionalAbiTags
);
1111 void CXXNameMangler::mangleModuleName(const NamedDecl
*ND
) {
1112 if (ND
->isExternallyVisible())
1113 if (Module
*M
= ND
->getOwningModuleForLinkage())
1114 mangleModuleNamePrefix(M
->getPrimaryModuleInterfaceName());
1117 // <module-name> ::= <module-subname>
1118 // ::= <module-name> <module-subname>
1119 // ::= <substitution>
1120 // <module-subname> ::= W <source-name>
1121 // ::= W P <source-name>
1122 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name
, bool IsPartition
) {
1123 // <substitution> ::= S <seq-id> _
1124 auto It
= ModuleSubstitutions
.find(Name
);
1125 if (It
!= ModuleSubstitutions
.end()) {
1127 mangleSeqID(It
->second
);
1131 // FIXME: Preserve hierarchy in module names rather than flattening
1132 // them to strings; use Module*s as substitution keys.
1133 auto Parts
= Name
.rsplit('.');
1134 if (Parts
.second
.empty())
1135 Parts
.second
= Parts
.first
;
1137 mangleModuleNamePrefix(Parts
.first
, IsPartition
);
1138 IsPartition
= false;
1144 Out
<< Parts
.second
.size() << Parts
.second
;
1145 ModuleSubstitutions
.insert({Name
, SeqID
++});
1148 void CXXNameMangler::mangleTemplateName(const TemplateDecl
*TD
,
1149 ArrayRef
<TemplateArgument
> Args
) {
1150 const DeclContext
*DC
= Context
.getEffectiveDeclContext(TD
);
1152 if (DC
->isTranslationUnit() || isStdNamespace(DC
)) {
1153 mangleUnscopedTemplateName(TD
, DC
, nullptr);
1154 mangleTemplateArgs(asTemplateName(TD
), Args
);
1156 mangleNestedName(TD
, Args
);
1160 void CXXNameMangler::mangleUnscopedName(GlobalDecl GD
, const DeclContext
*DC
,
1161 const AbiTagList
*AdditionalAbiTags
) {
1162 // <unscoped-name> ::= <unqualified-name>
1163 // ::= St <unqualified-name> # ::std::
1165 assert(!isa
<LinkageSpecDecl
>(DC
) && "unskipped LinkageSpecDecl");
1166 if (isStdNamespace(DC
)) {
1167 if (getASTContext().getTargetInfo().getTriple().isOSSolaris()) {
1168 const NamedDecl
*ND
= cast
<NamedDecl
>(GD
.getDecl());
1169 if (const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(ND
)) {
1170 // Issue #33114: Need non-standard mangling of std::tm etc. for
1171 // Solaris ABI compatibility.
1173 // <substitution> ::= tm # ::std::tm, same for the others
1174 if (const IdentifierInfo
*II
= RD
->getIdentifier()) {
1175 StringRef type
= II
->getName();
1176 if (llvm::is_contained({"div_t", "ldiv_t", "lconv", "tm"}, type
)) {
1177 Out
<< type
.size() << type
;
1186 mangleUnqualifiedName(GD
, DC
, AdditionalAbiTags
);
1189 void CXXNameMangler::mangleUnscopedTemplateName(
1190 GlobalDecl GD
, const DeclContext
*DC
, const AbiTagList
*AdditionalAbiTags
) {
1191 const TemplateDecl
*ND
= cast
<TemplateDecl
>(GD
.getDecl());
1192 // <unscoped-template-name> ::= <unscoped-name>
1193 // ::= <substitution>
1194 if (mangleSubstitution(ND
))
1197 // <template-template-param> ::= <template-param>
1198 if (const auto *TTP
= dyn_cast
<TemplateTemplateParmDecl
>(ND
)) {
1199 assert(!AdditionalAbiTags
&&
1200 "template template param cannot have abi tags");
1201 mangleTemplateParameter(TTP
->getDepth(), TTP
->getIndex());
1202 } else if (isa
<BuiltinTemplateDecl
>(ND
) || isa
<ConceptDecl
>(ND
)) {
1203 mangleUnscopedName(GD
, DC
, AdditionalAbiTags
);
1205 mangleUnscopedName(GD
.getWithDecl(ND
->getTemplatedDecl()), DC
,
1209 addSubstitution(ND
);
1212 void CXXNameMangler::mangleFloat(const llvm::APFloat
&f
) {
1214 // Floating-point literals are encoded using a fixed-length
1215 // lowercase hexadecimal string corresponding to the internal
1216 // representation (IEEE on Itanium), high-order bytes first,
1217 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1219 // The 'without leading zeroes' thing seems to be an editorial
1220 // mistake; see the discussion on cxx-abi-dev beginning on
1223 // Our requirements here are just barely weird enough to justify
1224 // using a custom algorithm instead of post-processing APInt::toString().
1226 llvm::APInt valueBits
= f
.bitcastToAPInt();
1227 unsigned numCharacters
= (valueBits
.getBitWidth() + 3) / 4;
1228 assert(numCharacters
!= 0);
1230 // Allocate a buffer of the right number of characters.
1231 SmallVector
<char, 20> buffer(numCharacters
);
1233 // Fill the buffer left-to-right.
1234 for (unsigned stringIndex
= 0; stringIndex
!= numCharacters
; ++stringIndex
) {
1235 // The bit-index of the next hex digit.
1236 unsigned digitBitIndex
= 4 * (numCharacters
- stringIndex
- 1);
1238 // Project out 4 bits starting at 'digitIndex'.
1239 uint64_t hexDigit
= valueBits
.getRawData()[digitBitIndex
/ 64];
1240 hexDigit
>>= (digitBitIndex
% 64);
1243 // Map that over to a lowercase hex digit.
1244 static const char charForHex
[16] = {
1245 '0', '1', '2', '3', '4', '5', '6', '7',
1246 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1248 buffer
[stringIndex
] = charForHex
[hexDigit
];
1251 Out
.write(buffer
.data(), numCharacters
);
1254 void CXXNameMangler::mangleFloatLiteral(QualType T
, const llvm::APFloat
&V
) {
1261 void CXXNameMangler::mangleFixedPointLiteral() {
1262 DiagnosticsEngine
&Diags
= Context
.getDiags();
1263 unsigned DiagID
= Diags
.getCustomDiagID(
1264 DiagnosticsEngine::Error
, "cannot mangle fixed point literals yet");
1265 Diags
.Report(DiagID
);
1268 void CXXNameMangler::mangleNullPointer(QualType T
) {
1269 // <expr-primary> ::= L <type> 0 E
1275 void CXXNameMangler::mangleNumber(const llvm::APSInt
&Value
) {
1276 if (Value
.isSigned() && Value
.isNegative()) {
1278 Value
.abs().print(Out
, /*signed*/ false);
1280 Value
.print(Out
, /*signed*/ false);
1284 void CXXNameMangler::mangleNumber(int64_t Number
) {
1285 // <number> ::= [n] <non-negative decimal integer>
1294 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual
, int64_t Virtual
) {
1295 // <call-offset> ::= h <nv-offset> _
1296 // ::= v <v-offset> _
1297 // <nv-offset> ::= <offset number> # non-virtual base override
1298 // <v-offset> ::= <offset number> _ <virtual offset number>
1299 // # virtual base override, with vcall offset
1302 mangleNumber(NonVirtual
);
1308 mangleNumber(NonVirtual
);
1310 mangleNumber(Virtual
);
1314 void CXXNameMangler::manglePrefix(QualType type
) {
1315 if (const auto *TST
= type
->getAs
<TemplateSpecializationType
>()) {
1316 if (!mangleSubstitution(QualType(TST
, 0))) {
1317 mangleTemplatePrefix(TST
->getTemplateName());
1319 // FIXME: GCC does not appear to mangle the template arguments when
1320 // the template in question is a dependent template name. Should we
1321 // emulate that badness?
1322 mangleTemplateArgs(TST
->getTemplateName(), TST
->template_arguments());
1323 addSubstitution(QualType(TST
, 0));
1325 } else if (const auto *DTST
=
1326 type
->getAs
<DependentTemplateSpecializationType
>()) {
1327 if (!mangleSubstitution(QualType(DTST
, 0))) {
1328 TemplateName Template
= getASTContext().getDependentTemplateName(
1329 DTST
->getQualifier(), DTST
->getIdentifier());
1330 mangleTemplatePrefix(Template
);
1332 // FIXME: GCC does not appear to mangle the template arguments when
1333 // the template in question is a dependent template name. Should we
1334 // emulate that badness?
1335 mangleTemplateArgs(Template
, DTST
->template_arguments());
1336 addSubstitution(QualType(DTST
, 0));
1339 // We use the QualType mangle type variant here because it handles
1345 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1347 /// \param recursive - true if this is being called recursively,
1348 /// i.e. if there is more prefix "to the right".
1349 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier
*qualifier
,
1353 // <unresolved-name> ::= [gs] <base-unresolved-name>
1355 // T::x / decltype(p)::x
1356 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1358 // T::N::x /decltype(p)::N::x
1359 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1360 // <base-unresolved-name>
1362 // A::x, N::y, A<T>::z; "gs" means leading "::"
1363 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1364 // <base-unresolved-name>
1366 switch (qualifier
->getKind()) {
1367 case NestedNameSpecifier::Global
:
1370 // We want an 'sr' unless this is the entire NNS.
1374 // We never want an 'E' here.
1377 case NestedNameSpecifier::Super
:
1378 llvm_unreachable("Can't mangle __super specifier");
1380 case NestedNameSpecifier::Namespace
:
1381 if (qualifier
->getPrefix())
1382 mangleUnresolvedPrefix(qualifier
->getPrefix(),
1383 /*recursive*/ true);
1386 mangleSourceNameWithAbiTags(qualifier
->getAsNamespace());
1388 case NestedNameSpecifier::NamespaceAlias
:
1389 if (qualifier
->getPrefix())
1390 mangleUnresolvedPrefix(qualifier
->getPrefix(),
1391 /*recursive*/ true);
1394 mangleSourceNameWithAbiTags(qualifier
->getAsNamespaceAlias());
1397 case NestedNameSpecifier::TypeSpec
:
1398 case NestedNameSpecifier::TypeSpecWithTemplate
: {
1399 const Type
*type
= qualifier
->getAsType();
1401 // We only want to use an unresolved-type encoding if this is one of:
1403 // - a template type parameter
1404 // - a template template parameter with arguments
1405 // In all of these cases, we should have no prefix.
1406 if (qualifier
->getPrefix()) {
1407 mangleUnresolvedPrefix(qualifier
->getPrefix(),
1408 /*recursive*/ true);
1410 // Otherwise, all the cases want this.
1414 if (mangleUnresolvedTypeOrSimpleId(QualType(type
, 0), recursive
? "N" : ""))
1420 case NestedNameSpecifier::Identifier
:
1421 // Member expressions can have these without prefixes.
1422 if (qualifier
->getPrefix())
1423 mangleUnresolvedPrefix(qualifier
->getPrefix(),
1424 /*recursive*/ true);
1428 mangleSourceName(qualifier
->getAsIdentifier());
1429 // An Identifier has no type information, so we can't emit abi tags for it.
1433 // If this was the innermost part of the NNS, and we fell out to
1434 // here, append an 'E'.
1439 /// Mangle an unresolved-name, which is generally used for names which
1440 /// weren't resolved to specific entities.
1441 void CXXNameMangler::mangleUnresolvedName(
1442 NestedNameSpecifier
*qualifier
, DeclarationName name
,
1443 const TemplateArgumentLoc
*TemplateArgs
, unsigned NumTemplateArgs
,
1444 unsigned knownArity
) {
1445 if (qualifier
) mangleUnresolvedPrefix(qualifier
);
1446 switch (name
.getNameKind()) {
1447 // <base-unresolved-name> ::= <simple-id>
1448 case DeclarationName::Identifier
:
1449 mangleSourceName(name
.getAsIdentifierInfo());
1451 // <base-unresolved-name> ::= dn <destructor-name>
1452 case DeclarationName::CXXDestructorName
:
1454 mangleUnresolvedTypeOrSimpleId(name
.getCXXNameType());
1456 // <base-unresolved-name> ::= on <operator-name>
1457 case DeclarationName::CXXConversionFunctionName
:
1458 case DeclarationName::CXXLiteralOperatorName
:
1459 case DeclarationName::CXXOperatorName
:
1461 mangleOperatorName(name
, knownArity
);
1463 case DeclarationName::CXXConstructorName
:
1464 llvm_unreachable("Can't mangle a constructor name!");
1465 case DeclarationName::CXXUsingDirective
:
1466 llvm_unreachable("Can't mangle a using directive name!");
1467 case DeclarationName::CXXDeductionGuideName
:
1468 llvm_unreachable("Can't mangle a deduction guide name!");
1469 case DeclarationName::ObjCMultiArgSelector
:
1470 case DeclarationName::ObjCOneArgSelector
:
1471 case DeclarationName::ObjCZeroArgSelector
:
1472 llvm_unreachable("Can't mangle Objective-C selector names here!");
1475 // The <simple-id> and on <operator-name> productions end in an optional
1478 mangleTemplateArgs(TemplateName(), TemplateArgs
, NumTemplateArgs
);
1481 void CXXNameMangler::mangleUnqualifiedName(
1482 GlobalDecl GD
, DeclarationName Name
, const DeclContext
*DC
,
1483 unsigned KnownArity
, const AbiTagList
*AdditionalAbiTags
) {
1484 const NamedDecl
*ND
= cast_or_null
<NamedDecl
>(GD
.getDecl());
1485 // <unqualified-name> ::= [<module-name>] [F] <operator-name>
1486 // ::= <ctor-dtor-name>
1487 // ::= [<module-name>] [F] <source-name>
1488 // ::= [<module-name>] DC <source-name>* E
1490 if (ND
&& DC
&& DC
->isFileContext())
1491 mangleModuleName(ND
);
1493 // A member-like constrained friend is mangled with a leading 'F'.
1494 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
1495 auto *FD
= dyn_cast
<FunctionDecl
>(ND
);
1496 auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(ND
);
1497 if ((FD
&& FD
->isMemberLikeConstrainedFriend()) ||
1498 (FTD
&& FTD
->getTemplatedDecl()->isMemberLikeConstrainedFriend())) {
1499 if (!isCompatibleWith(LangOptions::ClangABI::Ver17
))
1503 unsigned Arity
= KnownArity
;
1504 switch (Name
.getNameKind()) {
1505 case DeclarationName::Identifier
: {
1506 const IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
1508 // We mangle decomposition declarations as the names of their bindings.
1509 if (auto *DD
= dyn_cast
<DecompositionDecl
>(ND
)) {
1510 // FIXME: Non-standard mangling for decomposition declarations:
1512 // <unqualified-name> ::= DC <source-name>* E
1514 // Proposed on cxx-abi-dev on 2016-08-12
1516 for (auto *BD
: DD
->bindings())
1517 mangleSourceName(BD
->getDeclName().getAsIdentifierInfo());
1519 writeAbiTags(ND
, AdditionalAbiTags
);
1523 if (auto *GD
= dyn_cast
<MSGuidDecl
>(ND
)) {
1524 // We follow MSVC in mangling GUID declarations as if they were variables
1525 // with a particular reserved name. Continue the pretense here.
1526 SmallString
<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID
;
1527 llvm::raw_svector_ostream
GUIDOS(GUID
);
1528 Context
.mangleMSGuidDecl(GD
, GUIDOS
);
1529 Out
<< GUID
.size() << GUID
;
1533 if (auto *TPO
= dyn_cast
<TemplateParamObjectDecl
>(ND
)) {
1534 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1536 mangleValueInTemplateArg(TPO
->getType().getUnqualifiedType(),
1537 TPO
->getValue(), /*TopLevel=*/true);
1542 // Match GCC's naming convention for internal linkage symbols, for
1543 // symbols that are not actually visible outside of this TU. GCC
1544 // distinguishes between internal and external linkage symbols in
1545 // its mangling, to support cases like this that were valid C++ prior
1548 // void test() { extern void foo(); }
1549 // static void foo();
1551 // Don't bother with the L marker for names in anonymous namespaces; the
1552 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1553 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1554 // implying internal linkage.
1555 if (Context
.isInternalLinkageDecl(ND
))
1558 bool IsRegCall
= FD
&&
1559 FD
->getType()->castAs
<FunctionType
>()->getCallConv() ==
1560 clang::CC_X86RegCall
;
1562 FD
&& FD
->hasAttr
<CUDAGlobalAttr
>() &&
1563 GD
.getKernelReferenceKind() == KernelReferenceKind::Stub
;
1565 mangleDeviceStubName(II
);
1567 mangleRegCallName(II
);
1569 mangleSourceName(II
);
1571 writeAbiTags(ND
, AdditionalAbiTags
);
1575 // Otherwise, an anonymous entity. We must have a declaration.
1576 assert(ND
&& "mangling empty name without declaration");
1578 if (const NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(ND
)) {
1579 if (NS
->isAnonymousNamespace()) {
1580 // This is how gcc mangles these names.
1581 Out
<< "12_GLOBAL__N_1";
1586 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(ND
)) {
1587 // We must have an anonymous union or struct declaration.
1588 const RecordDecl
*RD
= VD
->getType()->castAs
<RecordType
>()->getDecl();
1590 // Itanium C++ ABI 5.1.2:
1592 // For the purposes of mangling, the name of an anonymous union is
1593 // considered to be the name of the first named data member found by a
1594 // pre-order, depth-first, declaration-order walk of the data members of
1595 // the anonymous union. If there is no such data member (i.e., if all of
1596 // the data members in the union are unnamed), then there is no way for
1597 // a program to refer to the anonymous union, and there is therefore no
1598 // need to mangle its name.
1599 assert(RD
->isAnonymousStructOrUnion()
1600 && "Expected anonymous struct or union!");
1601 const FieldDecl
*FD
= RD
->findFirstNamedDataMember();
1603 // It's actually possible for various reasons for us to get here
1604 // with an empty anonymous struct / union. Fortunately, it
1605 // doesn't really matter what name we generate.
1607 assert(FD
->getIdentifier() && "Data member name isn't an identifier!");
1609 mangleSourceName(FD
->getIdentifier());
1610 // Not emitting abi tags: internal name anyway.
1614 // Class extensions have no name as a category, and it's possible
1615 // for them to be the semantic parent of certain declarations
1616 // (primarily, tag decls defined within declarations). Such
1617 // declarations will always have internal linkage, so the name
1618 // doesn't really matter, but we shouldn't crash on them. For
1619 // safety, just handle all ObjC containers here.
1620 if (isa
<ObjCContainerDecl
>(ND
))
1623 // We must have an anonymous struct.
1624 const TagDecl
*TD
= cast
<TagDecl
>(ND
);
1625 if (const TypedefNameDecl
*D
= TD
->getTypedefNameForAnonDecl()) {
1626 assert(TD
->getDeclContext() == D
->getDeclContext() &&
1627 "Typedef should not be in another decl context!");
1628 assert(D
->getDeclName().getAsIdentifierInfo() &&
1629 "Typedef was not named!");
1630 mangleSourceName(D
->getDeclName().getAsIdentifierInfo());
1631 assert(!AdditionalAbiTags
&& "Type cannot have additional abi tags");
1632 // Explicit abi tags are still possible; take from underlying type, not
1634 writeAbiTags(TD
, nullptr);
1638 // <unnamed-type-name> ::= <closure-type-name>
1640 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1641 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1642 // # Parameter types or 'v' for 'void'.
1643 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(TD
)) {
1644 std::optional
<unsigned> DeviceNumber
=
1645 Context
.getDiscriminatorOverride()(Context
.getASTContext(), Record
);
1647 // If we have a device-number via the discriminator, use that to mangle
1648 // the lambda, otherwise use the typical lambda-mangling-number. In either
1649 // case, a '0' should be mangled as a normal unnamed class instead of as a
1651 if (Record
->isLambda() &&
1652 ((DeviceNumber
&& *DeviceNumber
> 0) ||
1653 (!DeviceNumber
&& Record
->getLambdaManglingNumber() > 0))) {
1654 assert(!AdditionalAbiTags
&&
1655 "Lambda type cannot have additional abi tags");
1656 mangleLambda(Record
);
1661 if (TD
->isExternallyVisible()) {
1662 unsigned UnnamedMangle
=
1663 getASTContext().getManglingNumber(TD
, Context
.isAux());
1665 if (UnnamedMangle
> 1)
1666 Out
<< UnnamedMangle
- 2;
1668 writeAbiTags(TD
, AdditionalAbiTags
);
1672 // Get a unique id for the anonymous struct. If it is not a real output
1673 // ID doesn't matter so use fake one.
1674 unsigned AnonStructId
=
1676 : Context
.getAnonymousStructId(TD
, dyn_cast
<FunctionDecl
>(DC
));
1678 // Mangle it as a source name in the form
1680 // where n is the length of the string.
1683 Str
+= llvm::utostr(AnonStructId
);
1690 case DeclarationName::ObjCZeroArgSelector
:
1691 case DeclarationName::ObjCOneArgSelector
:
1692 case DeclarationName::ObjCMultiArgSelector
:
1693 llvm_unreachable("Can't mangle Objective-C selector names here!");
1695 case DeclarationName::CXXConstructorName
: {
1696 const CXXRecordDecl
*InheritedFrom
= nullptr;
1697 TemplateName InheritedTemplateName
;
1698 const TemplateArgumentList
*InheritedTemplateArgs
= nullptr;
1699 if (auto Inherited
=
1700 cast
<CXXConstructorDecl
>(ND
)->getInheritedConstructor()) {
1701 InheritedFrom
= Inherited
.getConstructor()->getParent();
1702 InheritedTemplateName
=
1703 TemplateName(Inherited
.getConstructor()->getPrimaryTemplate());
1704 InheritedTemplateArgs
=
1705 Inherited
.getConstructor()->getTemplateSpecializationArgs();
1709 // If the named decl is the C++ constructor we're mangling, use the type
1711 mangleCXXCtorType(static_cast<CXXCtorType
>(StructorType
), InheritedFrom
);
1713 // Otherwise, use the complete constructor name. This is relevant if a
1714 // class with a constructor is declared within a constructor.
1715 mangleCXXCtorType(Ctor_Complete
, InheritedFrom
);
1717 // FIXME: The template arguments are part of the enclosing prefix or
1718 // nested-name, but it's more convenient to mangle them here.
1719 if (InheritedTemplateArgs
)
1720 mangleTemplateArgs(InheritedTemplateName
, *InheritedTemplateArgs
);
1722 writeAbiTags(ND
, AdditionalAbiTags
);
1726 case DeclarationName::CXXDestructorName
:
1728 // If the named decl is the C++ destructor we're mangling, use the type we
1730 mangleCXXDtorType(static_cast<CXXDtorType
>(StructorType
));
1732 // Otherwise, use the complete destructor name. This is relevant if a
1733 // class with a destructor is declared within a destructor.
1734 mangleCXXDtorType(Dtor_Complete
);
1736 writeAbiTags(ND
, AdditionalAbiTags
);
1739 case DeclarationName::CXXOperatorName
:
1740 if (ND
&& Arity
== UnknownArity
) {
1741 Arity
= cast
<FunctionDecl
>(ND
)->getNumParams();
1743 // If we have a member function, we need to include the 'this' pointer.
1744 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(ND
))
1745 if (MD
->isImplicitObjectMemberFunction())
1749 case DeclarationName::CXXConversionFunctionName
:
1750 case DeclarationName::CXXLiteralOperatorName
:
1751 mangleOperatorName(Name
, Arity
);
1752 writeAbiTags(ND
, AdditionalAbiTags
);
1755 case DeclarationName::CXXDeductionGuideName
:
1756 llvm_unreachable("Can't mangle a deduction guide name!");
1758 case DeclarationName::CXXUsingDirective
:
1759 llvm_unreachable("Can't mangle a using directive name!");
1763 void CXXNameMangler::mangleRegCallName(const IdentifierInfo
*II
) {
1764 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1765 // <number> ::= [n] <non-negative decimal integer>
1766 // <identifier> ::= <unqualified source code identifier>
1767 if (getASTContext().getLangOpts().RegCall4
)
1768 Out
<< II
->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"
1771 Out
<< II
->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1775 void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo
*II
) {
1776 // <source-name> ::= <positive length number> __device_stub__ <identifier>
1777 // <number> ::= [n] <non-negative decimal integer>
1778 // <identifier> ::= <unqualified source code identifier>
1779 Out
<< II
->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1783 void CXXNameMangler::mangleSourceName(const IdentifierInfo
*II
) {
1784 // <source-name> ::= <positive length number> <identifier>
1785 // <number> ::= [n] <non-negative decimal integer>
1786 // <identifier> ::= <unqualified source code identifier>
1787 Out
<< II
->getLength() << II
->getName();
1790 void CXXNameMangler::mangleNestedName(GlobalDecl GD
,
1791 const DeclContext
*DC
,
1792 const AbiTagList
*AdditionalAbiTags
,
1794 const NamedDecl
*ND
= cast
<NamedDecl
>(GD
.getDecl());
1796 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1797 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1798 // <template-args> E
1801 if (const CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(ND
)) {
1802 Qualifiers MethodQuals
= Method
->getMethodQualifiers();
1803 // We do not consider restrict a distinguishing attribute for overloading
1804 // purposes so we must not mangle it.
1805 if (Method
->isExplicitObjectMemberFunction())
1807 MethodQuals
.removeRestrict();
1808 mangleQualifiers(MethodQuals
);
1809 mangleRefQualifier(Method
->getRefQualifier());
1812 // Check if we have a template.
1813 const TemplateArgumentList
*TemplateArgs
= nullptr;
1814 if (GlobalDecl TD
= isTemplate(GD
, TemplateArgs
)) {
1815 mangleTemplatePrefix(TD
, NoFunction
);
1816 mangleTemplateArgs(asTemplateName(TD
), *TemplateArgs
);
1818 manglePrefix(DC
, NoFunction
);
1819 mangleUnqualifiedName(GD
, DC
, AdditionalAbiTags
);
1824 void CXXNameMangler::mangleNestedName(const TemplateDecl
*TD
,
1825 ArrayRef
<TemplateArgument
> Args
) {
1826 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1830 mangleTemplatePrefix(TD
);
1831 mangleTemplateArgs(asTemplateName(TD
), Args
);
1836 void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1837 GlobalDecl GD
, const NamedDecl
*PrefixND
,
1838 const AbiTagList
*AdditionalAbiTags
) {
1839 // A <closure-prefix> represents a variable or field, not a regular
1840 // DeclContext, so needs special handling. In this case we're mangling a
1841 // limited form of <nested-name>:
1843 // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1847 mangleClosurePrefix(PrefixND
);
1848 mangleUnqualifiedName(GD
, nullptr, AdditionalAbiTags
);
1853 static GlobalDecl
getParentOfLocalEntity(const DeclContext
*DC
) {
1855 // The Itanium spec says:
1856 // For entities in constructors and destructors, the mangling of the
1857 // complete object constructor or destructor is used as the base function
1858 // name, i.e. the C1 or D1 version.
1859 if (auto *CD
= dyn_cast
<CXXConstructorDecl
>(DC
))
1860 GD
= GlobalDecl(CD
, Ctor_Complete
);
1861 else if (auto *DD
= dyn_cast
<CXXDestructorDecl
>(DC
))
1862 GD
= GlobalDecl(DD
, Dtor_Complete
);
1864 GD
= GlobalDecl(cast
<FunctionDecl
>(DC
));
1868 void CXXNameMangler::mangleLocalName(GlobalDecl GD
,
1869 const AbiTagList
*AdditionalAbiTags
) {
1870 const Decl
*D
= GD
.getDecl();
1871 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1872 // := Z <function encoding> E s [<discriminator>]
1873 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1875 // <discriminator> := _ <non-negative number>
1876 assert(isa
<NamedDecl
>(D
) || isa
<BlockDecl
>(D
));
1877 const RecordDecl
*RD
= GetLocalClassDecl(D
);
1878 const DeclContext
*DC
= Context
.getEffectiveDeclContext(RD
? RD
: D
);
1883 AbiTagState
LocalAbiTags(AbiTags
);
1885 if (const ObjCMethodDecl
*MD
= dyn_cast
<ObjCMethodDecl
>(DC
))
1886 mangleObjCMethodName(MD
);
1887 else if (const BlockDecl
*BD
= dyn_cast
<BlockDecl
>(DC
))
1888 mangleBlockForPrefix(BD
);
1890 mangleFunctionEncoding(getParentOfLocalEntity(DC
));
1892 // Implicit ABI tags (from namespace) are not available in the following
1893 // entity; reset to actually emitted tags, which are available.
1894 LocalAbiTags
.setUsedAbiTags(LocalAbiTags
.getEmittedAbiTags());
1899 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1900 // be a bug that is fixed in trunk.
1903 // The parameter number is omitted for the last parameter, 0 for the
1904 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1905 // <entity name> will of course contain a <closure-type-name>: Its
1906 // numbering will be local to the particular argument in which it appears
1907 // -- other default arguments do not affect its encoding.
1908 const CXXRecordDecl
*CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
);
1909 if (CXXRD
&& CXXRD
->isLambda()) {
1910 if (const ParmVarDecl
*Parm
1911 = dyn_cast_or_null
<ParmVarDecl
>(CXXRD
->getLambdaContextDecl())) {
1912 if (const FunctionDecl
*Func
1913 = dyn_cast
<FunctionDecl
>(Parm
->getDeclContext())) {
1915 unsigned Num
= Func
->getNumParams() - Parm
->getFunctionScopeIndex();
1917 mangleNumber(Num
- 2);
1923 // Mangle the name relative to the closest enclosing function.
1924 // equality ok because RD derived from ND above
1926 mangleUnqualifiedName(RD
, DC
, AdditionalAbiTags
);
1927 } else if (const BlockDecl
*BD
= dyn_cast
<BlockDecl
>(D
)) {
1928 if (const NamedDecl
*PrefixND
= getClosurePrefix(BD
))
1929 mangleClosurePrefix(PrefixND
, true /*NoFunction*/);
1931 manglePrefix(Context
.getEffectiveDeclContext(BD
), true /*NoFunction*/);
1932 assert(!AdditionalAbiTags
&& "Block cannot have additional abi tags");
1933 mangleUnqualifiedBlock(BD
);
1935 const NamedDecl
*ND
= cast
<NamedDecl
>(D
);
1936 mangleNestedName(GD
, Context
.getEffectiveDeclContext(ND
),
1937 AdditionalAbiTags
, true /*NoFunction*/);
1939 } else if (const BlockDecl
*BD
= dyn_cast
<BlockDecl
>(D
)) {
1940 // Mangle a block in a default parameter; see above explanation for
1942 if (const ParmVarDecl
*Parm
1943 = dyn_cast_or_null
<ParmVarDecl
>(BD
->getBlockManglingContextDecl())) {
1944 if (const FunctionDecl
*Func
1945 = dyn_cast
<FunctionDecl
>(Parm
->getDeclContext())) {
1947 unsigned Num
= Func
->getNumParams() - Parm
->getFunctionScopeIndex();
1949 mangleNumber(Num
- 2);
1954 assert(!AdditionalAbiTags
&& "Block cannot have additional abi tags");
1955 mangleUnqualifiedBlock(BD
);
1957 mangleUnqualifiedName(GD
, DC
, AdditionalAbiTags
);
1960 if (const NamedDecl
*ND
= dyn_cast
<NamedDecl
>(RD
? RD
: D
)) {
1962 if (Context
.getNextDiscriminator(ND
, disc
)) {
1966 Out
<< "__" << disc
<< '_';
1971 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl
*Block
) {
1972 if (GetLocalClassDecl(Block
)) {
1973 mangleLocalName(Block
, /* AdditionalAbiTags */ nullptr);
1976 const DeclContext
*DC
= Context
.getEffectiveDeclContext(Block
);
1977 if (isLocalContainerContext(DC
)) {
1978 mangleLocalName(Block
, /* AdditionalAbiTags */ nullptr);
1981 if (const NamedDecl
*PrefixND
= getClosurePrefix(Block
))
1982 mangleClosurePrefix(PrefixND
);
1985 mangleUnqualifiedBlock(Block
);
1988 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl
*Block
) {
1989 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1990 // <data-member-prefix> now, with no substitutions and no <template-args>.
1991 if (Decl
*Context
= Block
->getBlockManglingContextDecl()) {
1992 if (isCompatibleWith(LangOptions::ClangABI::Ver12
) &&
1993 (isa
<VarDecl
>(Context
) || isa
<FieldDecl
>(Context
)) &&
1994 Context
->getDeclContext()->isRecord()) {
1995 const auto *ND
= cast
<NamedDecl
>(Context
);
1996 if (ND
->getIdentifier()) {
1997 mangleSourceNameWithAbiTags(ND
);
2003 // If we have a block mangling number, use it.
2004 unsigned Number
= Block
->getBlockManglingNumber();
2005 // Otherwise, just make up a number. It doesn't matter what it is because
2006 // the symbol in question isn't externally visible.
2008 Number
= Context
.getBlockId(Block
, false);
2010 // Stored mangling numbers are 1-based.
2019 // <template-param-decl>
2020 // ::= Ty # template type parameter
2021 // ::= Tk <concept name> [<template-args>] # constrained type parameter
2022 // ::= Tn <type> # template non-type parameter
2023 // ::= Tt <template-param-decl>* E [Q <requires-clause expr>]
2024 // # template template parameter
2025 // ::= Tp <template-param-decl> # template parameter pack
2026 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl
*Decl
) {
2027 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
2028 if (auto *Ty
= dyn_cast
<TemplateTypeParmDecl
>(Decl
)) {
2029 if (Ty
->isParameterPack())
2031 const TypeConstraint
*Constraint
= Ty
->getTypeConstraint();
2032 if (Constraint
&& !isCompatibleWith(LangOptions::ClangABI::Ver17
)) {
2033 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2035 mangleTypeConstraint(Constraint
);
2039 } else if (auto *Tn
= dyn_cast
<NonTypeTemplateParmDecl
>(Decl
)) {
2040 if (Tn
->isExpandedParameterPack()) {
2041 for (unsigned I
= 0, N
= Tn
->getNumExpansionTypes(); I
!= N
; ++I
) {
2043 mangleType(Tn
->getExpansionType(I
));
2046 QualType T
= Tn
->getType();
2047 if (Tn
->isParameterPack()) {
2049 if (auto *PackExpansion
= T
->getAs
<PackExpansionType
>())
2050 T
= PackExpansion
->getPattern();
2055 } else if (auto *Tt
= dyn_cast
<TemplateTemplateParmDecl
>(Decl
)) {
2056 if (Tt
->isExpandedParameterPack()) {
2057 for (unsigned I
= 0, N
= Tt
->getNumExpansionTemplateParameters(); I
!= N
;
2059 mangleTemplateParameterList(Tt
->getExpansionTemplateParameters(I
));
2061 if (Tt
->isParameterPack())
2063 mangleTemplateParameterList(Tt
->getTemplateParameters());
2068 void CXXNameMangler::mangleTemplateParameterList(
2069 const TemplateParameterList
*Params
) {
2071 for (auto *Param
: *Params
)
2072 mangleTemplateParamDecl(Param
);
2073 mangleRequiresClause(Params
->getRequiresClause());
2077 void CXXNameMangler::mangleTypeConstraint(
2078 const ConceptDecl
*Concept
, ArrayRef
<TemplateArgument
> Arguments
) {
2079 const DeclContext
*DC
= Context
.getEffectiveDeclContext(Concept
);
2080 if (!Arguments
.empty())
2081 mangleTemplateName(Concept
, Arguments
);
2082 else if (DC
->isTranslationUnit() || isStdNamespace(DC
))
2083 mangleUnscopedName(Concept
, DC
, nullptr);
2085 mangleNestedName(Concept
, DC
, nullptr);
2088 void CXXNameMangler::mangleTypeConstraint(const TypeConstraint
*Constraint
) {
2089 llvm::SmallVector
<TemplateArgument
, 8> Args
;
2090 if (Constraint
->getTemplateArgsAsWritten()) {
2091 for (const TemplateArgumentLoc
&ArgLoc
:
2092 Constraint
->getTemplateArgsAsWritten()->arguments())
2093 Args
.push_back(ArgLoc
.getArgument());
2095 return mangleTypeConstraint(Constraint
->getNamedConcept(), Args
);
2098 void CXXNameMangler::mangleRequiresClause(const Expr
*RequiresClause
) {
2099 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2100 if (RequiresClause
&& !isCompatibleWith(LangOptions::ClangABI::Ver17
)) {
2102 mangleExpression(RequiresClause
);
2106 void CXXNameMangler::mangleLambda(const CXXRecordDecl
*Lambda
) {
2107 // When trying to be ABI-compatibility with clang 12 and before, mangle a
2108 // <data-member-prefix> now, with no substitutions.
2109 if (Decl
*Context
= Lambda
->getLambdaContextDecl()) {
2110 if (isCompatibleWith(LangOptions::ClangABI::Ver12
) &&
2111 (isa
<VarDecl
>(Context
) || isa
<FieldDecl
>(Context
)) &&
2112 !isa
<ParmVarDecl
>(Context
)) {
2113 if (const IdentifierInfo
*Name
2114 = cast
<NamedDecl
>(Context
)->getIdentifier()) {
2115 mangleSourceName(Name
);
2116 const TemplateArgumentList
*TemplateArgs
= nullptr;
2117 if (GlobalDecl TD
= isTemplate(cast
<NamedDecl
>(Context
), TemplateArgs
))
2118 mangleTemplateArgs(asTemplateName(TD
), *TemplateArgs
);
2125 mangleLambdaSig(Lambda
);
2128 // The number is omitted for the first closure type with a given
2129 // <lambda-sig> in a given context; it is n-2 for the nth closure type
2130 // (in lexical order) with that same <lambda-sig> and context.
2132 // The AST keeps track of the number for us.
2134 // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2135 // and host-side compilations, an extra device mangle context may be created
2136 // if the host-side CXX ABI has different numbering for lambda. In such case,
2137 // if the mangle context is that device-side one, use the device-side lambda
2138 // mangling number for this lambda.
2139 std::optional
<unsigned> DeviceNumber
=
2140 Context
.getDiscriminatorOverride()(Context
.getASTContext(), Lambda
);
2142 DeviceNumber
? *DeviceNumber
: Lambda
->getLambdaManglingNumber();
2144 assert(Number
> 0 && "Lambda should be mangled as an unnamed class");
2146 mangleNumber(Number
- 2);
2150 void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl
*Lambda
) {
2151 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.
2152 for (auto *D
: Lambda
->getLambdaExplicitTemplateParameters())
2153 mangleTemplateParamDecl(D
);
2155 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2156 if (auto *TPL
= Lambda
->getGenericLambdaTemplateParameterList())
2157 mangleRequiresClause(TPL
->getRequiresClause());
2160 Lambda
->getLambdaTypeInfo()->getType()->castAs
<FunctionProtoType
>();
2161 mangleBareFunctionType(Proto
, /*MangleReturnType=*/false,
2162 Lambda
->getLambdaStaticInvoker());
2165 void CXXNameMangler::manglePrefix(NestedNameSpecifier
*qualifier
) {
2166 switch (qualifier
->getKind()) {
2167 case NestedNameSpecifier::Global
:
2171 case NestedNameSpecifier::Super
:
2172 llvm_unreachable("Can't mangle __super specifier");
2174 case NestedNameSpecifier::Namespace
:
2175 mangleName(qualifier
->getAsNamespace());
2178 case NestedNameSpecifier::NamespaceAlias
:
2179 mangleName(qualifier
->getAsNamespaceAlias()->getNamespace());
2182 case NestedNameSpecifier::TypeSpec
:
2183 case NestedNameSpecifier::TypeSpecWithTemplate
:
2184 manglePrefix(QualType(qualifier
->getAsType(), 0));
2187 case NestedNameSpecifier::Identifier
:
2188 // Clang 14 and before did not consider this substitutable.
2189 bool Clang14Compat
= isCompatibleWith(LangOptions::ClangABI::Ver14
);
2190 if (!Clang14Compat
&& mangleSubstitution(qualifier
))
2193 // Member expressions can have these without prefixes, but that
2194 // should end up in mangleUnresolvedPrefix instead.
2195 assert(qualifier
->getPrefix());
2196 manglePrefix(qualifier
->getPrefix());
2198 mangleSourceName(qualifier
->getAsIdentifier());
2201 addSubstitution(qualifier
);
2205 llvm_unreachable("unexpected nested name specifier");
2208 void CXXNameMangler::manglePrefix(const DeclContext
*DC
, bool NoFunction
) {
2209 // <prefix> ::= <prefix> <unqualified-name>
2210 // ::= <template-prefix> <template-args>
2211 // ::= <closure-prefix>
2212 // ::= <template-param>
2214 // ::= <substitution>
2216 assert(!isa
<LinkageSpecDecl
>(DC
) && "prefix cannot be LinkageSpecDecl");
2218 if (DC
->isTranslationUnit())
2221 if (NoFunction
&& isLocalContainerContext(DC
))
2224 const NamedDecl
*ND
= cast
<NamedDecl
>(DC
);
2225 if (mangleSubstitution(ND
))
2228 // Check if we have a template-prefix or a closure-prefix.
2229 const TemplateArgumentList
*TemplateArgs
= nullptr;
2230 if (GlobalDecl TD
= isTemplate(ND
, TemplateArgs
)) {
2231 mangleTemplatePrefix(TD
);
2232 mangleTemplateArgs(asTemplateName(TD
), *TemplateArgs
);
2233 } else if (const NamedDecl
*PrefixND
= getClosurePrefix(ND
)) {
2234 mangleClosurePrefix(PrefixND
, NoFunction
);
2235 mangleUnqualifiedName(ND
, nullptr, nullptr);
2237 const DeclContext
*DC
= Context
.getEffectiveDeclContext(ND
);
2238 manglePrefix(DC
, NoFunction
);
2239 mangleUnqualifiedName(ND
, DC
, nullptr);
2242 addSubstitution(ND
);
2245 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template
) {
2246 // <template-prefix> ::= <prefix> <template unqualified-name>
2247 // ::= <template-param>
2248 // ::= <substitution>
2249 if (TemplateDecl
*TD
= Template
.getAsTemplateDecl())
2250 return mangleTemplatePrefix(TD
);
2252 DependentTemplateName
*Dependent
= Template
.getAsDependentTemplateName();
2253 assert(Dependent
&& "unexpected template name kind");
2255 // Clang 11 and before mangled the substitution for a dependent template name
2256 // after already having emitted (a substitution for) the prefix.
2257 bool Clang11Compat
= isCompatibleWith(LangOptions::ClangABI::Ver11
);
2258 if (!Clang11Compat
&& mangleSubstitution(Template
))
2261 if (NestedNameSpecifier
*Qualifier
= Dependent
->getQualifier())
2262 manglePrefix(Qualifier
);
2264 if (Clang11Compat
&& mangleSubstitution(Template
))
2267 if (const IdentifierInfo
*Id
= Dependent
->getIdentifier())
2268 mangleSourceName(Id
);
2270 mangleOperatorName(Dependent
->getOperator(), UnknownArity
);
2272 addSubstitution(Template
);
2275 void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD
,
2277 const TemplateDecl
*ND
= cast
<TemplateDecl
>(GD
.getDecl());
2278 // <template-prefix> ::= <prefix> <template unqualified-name>
2279 // ::= <template-param>
2280 // ::= <substitution>
2281 // <template-template-param> ::= <template-param>
2284 if (mangleSubstitution(ND
))
2287 // <template-template-param> ::= <template-param>
2288 if (const auto *TTP
= dyn_cast
<TemplateTemplateParmDecl
>(ND
)) {
2289 mangleTemplateParameter(TTP
->getDepth(), TTP
->getIndex());
2291 const DeclContext
*DC
= Context
.getEffectiveDeclContext(ND
);
2292 manglePrefix(DC
, NoFunction
);
2293 if (isa
<BuiltinTemplateDecl
>(ND
) || isa
<ConceptDecl
>(ND
))
2294 mangleUnqualifiedName(GD
, DC
, nullptr);
2296 mangleUnqualifiedName(GD
.getWithDecl(ND
->getTemplatedDecl()), DC
,
2300 addSubstitution(ND
);
2303 const NamedDecl
*CXXNameMangler::getClosurePrefix(const Decl
*ND
) {
2304 if (isCompatibleWith(LangOptions::ClangABI::Ver12
))
2307 const NamedDecl
*Context
= nullptr;
2308 if (auto *Block
= dyn_cast
<BlockDecl
>(ND
)) {
2309 Context
= dyn_cast_or_null
<NamedDecl
>(Block
->getBlockManglingContextDecl());
2310 } else if (auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
)) {
2312 Context
= dyn_cast_or_null
<NamedDecl
>(RD
->getLambdaContextDecl());
2317 // Only lambdas within the initializer of a non-local variable or non-static
2318 // data member get a <closure-prefix>.
2319 if ((isa
<VarDecl
>(Context
) && cast
<VarDecl
>(Context
)->hasGlobalStorage()) ||
2320 isa
<FieldDecl
>(Context
))
2326 void CXXNameMangler::mangleClosurePrefix(const NamedDecl
*ND
, bool NoFunction
) {
2327 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2328 // ::= <template-prefix> <template-args> M
2329 if (mangleSubstitution(ND
))
2332 const TemplateArgumentList
*TemplateArgs
= nullptr;
2333 if (GlobalDecl TD
= isTemplate(ND
, TemplateArgs
)) {
2334 mangleTemplatePrefix(TD
, NoFunction
);
2335 mangleTemplateArgs(asTemplateName(TD
), *TemplateArgs
);
2337 const auto *DC
= Context
.getEffectiveDeclContext(ND
);
2338 manglePrefix(DC
, NoFunction
);
2339 mangleUnqualifiedName(ND
, DC
, nullptr);
2344 addSubstitution(ND
);
2347 /// Mangles a template name under the production <type>. Required for
2348 /// template template arguments.
2349 /// <type> ::= <class-enum-type>
2350 /// ::= <template-param>
2351 /// ::= <substitution>
2352 void CXXNameMangler::mangleType(TemplateName TN
) {
2353 if (mangleSubstitution(TN
))
2356 TemplateDecl
*TD
= nullptr;
2358 switch (TN
.getKind()) {
2359 case TemplateName::QualifiedTemplate
:
2360 case TemplateName::UsingTemplate
:
2361 case TemplateName::Template
:
2362 TD
= TN
.getAsTemplateDecl();
2366 if (auto *TTP
= dyn_cast
<TemplateTemplateParmDecl
>(TD
))
2367 mangleTemplateParameter(TTP
->getDepth(), TTP
->getIndex());
2372 case TemplateName::OverloadedTemplate
:
2373 case TemplateName::AssumedTemplate
:
2374 llvm_unreachable("can't mangle an overloaded template name as a <type>");
2376 case TemplateName::DependentTemplate
: {
2377 const DependentTemplateName
*Dependent
= TN
.getAsDependentTemplateName();
2378 assert(Dependent
->isIdentifier());
2380 // <class-enum-type> ::= <name>
2381 // <name> ::= <nested-name>
2382 mangleUnresolvedPrefix(Dependent
->getQualifier());
2383 mangleSourceName(Dependent
->getIdentifier());
2387 case TemplateName::SubstTemplateTemplateParm
: {
2388 // Substituted template parameters are mangled as the substituted
2389 // template. This will check for the substitution twice, which is
2390 // fine, but we have to return early so that we don't try to *add*
2391 // the substitution twice.
2392 SubstTemplateTemplateParmStorage
*subst
2393 = TN
.getAsSubstTemplateTemplateParm();
2394 mangleType(subst
->getReplacement());
2398 case TemplateName::SubstTemplateTemplateParmPack
: {
2399 // FIXME: not clear how to mangle this!
2400 // template <template <class> class T...> class A {
2401 // template <template <class> class U...> void foo(B<T,U> x...);
2403 Out
<< "_SUBSTPACK_";
2406 case TemplateName::DeducedTemplate
:
2407 llvm_unreachable("Unexpected DeducedTemplate");
2410 addSubstitution(TN
);
2413 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty
,
2415 // Only certain other types are valid as prefixes; enumerate them.
2416 switch (Ty
->getTypeClass()) {
2419 case Type::Adjusted
:
2421 case Type::ArrayParameter
:
2423 case Type::BlockPointer
:
2424 case Type::LValueReference
:
2425 case Type::RValueReference
:
2426 case Type::MemberPointer
:
2427 case Type::ConstantArray
:
2428 case Type::IncompleteArray
:
2429 case Type::VariableArray
:
2430 case Type::DependentSizedArray
:
2431 case Type::DependentAddressSpace
:
2432 case Type::DependentVector
:
2433 case Type::DependentSizedExtVector
:
2435 case Type::ExtVector
:
2436 case Type::ConstantMatrix
:
2437 case Type::DependentSizedMatrix
:
2438 case Type::FunctionProto
:
2439 case Type::FunctionNoProto
:
2441 case Type::Attributed
:
2442 case Type::BTFTagAttributed
:
2443 case Type::HLSLAttributedResource
:
2445 case Type::DeducedTemplateSpecialization
:
2446 case Type::PackExpansion
:
2447 case Type::ObjCObject
:
2448 case Type::ObjCInterface
:
2449 case Type::ObjCObjectPointer
:
2450 case Type::ObjCTypeParam
:
2453 case Type::MacroQualified
:
2455 case Type::DependentBitInt
:
2456 case Type::CountAttributed
:
2457 llvm_unreachable("type is illegal as a nested name specifier");
2459 case Type::SubstTemplateTypeParmPack
:
2460 // FIXME: not clear how to mangle this!
2461 // template <class T...> class A {
2462 // template <class U...> void foo(decltype(T::foo(U())) x...);
2464 Out
<< "_SUBSTPACK_";
2467 // <unresolved-type> ::= <template-param>
2469 // ::= <template-template-param> <template-args>
2470 // (this last is not official yet)
2471 case Type::TypeOfExpr
:
2473 case Type::Decltype
:
2474 case Type::PackIndexing
:
2475 case Type::TemplateTypeParm
:
2476 case Type::UnaryTransform
:
2477 case Type::SubstTemplateTypeParm
:
2479 // Some callers want a prefix before the mangled type.
2482 // This seems to do everything we want. It's not really
2483 // sanctioned for a substituted template parameter, though.
2486 // We never want to print 'E' directly after an unresolved-type,
2487 // so we return directly.
2491 mangleSourceNameWithAbiTags(cast
<TypedefType
>(Ty
)->getDecl());
2494 case Type::UnresolvedUsing
:
2495 mangleSourceNameWithAbiTags(
2496 cast
<UnresolvedUsingType
>(Ty
)->getDecl());
2501 mangleSourceNameWithAbiTags(cast
<TagType
>(Ty
)->getDecl());
2504 case Type::TemplateSpecialization
: {
2505 const TemplateSpecializationType
*TST
=
2506 cast
<TemplateSpecializationType
>(Ty
);
2507 TemplateName TN
= TST
->getTemplateName();
2508 switch (TN
.getKind()) {
2509 case TemplateName::Template
:
2510 case TemplateName::QualifiedTemplate
: {
2511 TemplateDecl
*TD
= TN
.getAsTemplateDecl();
2513 // If the base is a template template parameter, this is an
2515 assert(TD
&& "no template for template specialization type");
2516 if (isa
<TemplateTemplateParmDecl
>(TD
))
2517 goto unresolvedType
;
2519 mangleSourceNameWithAbiTags(TD
);
2523 case TemplateName::OverloadedTemplate
:
2524 case TemplateName::AssumedTemplate
:
2525 case TemplateName::DependentTemplate
:
2526 case TemplateName::DeducedTemplate
:
2527 llvm_unreachable("invalid base for a template specialization type");
2529 case TemplateName::SubstTemplateTemplateParm
: {
2530 SubstTemplateTemplateParmStorage
*subst
=
2531 TN
.getAsSubstTemplateTemplateParm();
2532 mangleExistingSubstitution(subst
->getReplacement());
2536 case TemplateName::SubstTemplateTemplateParmPack
: {
2537 // FIXME: not clear how to mangle this!
2538 // template <template <class U> class T...> class A {
2539 // template <class U...> void foo(decltype(T<U>::foo) x...);
2541 Out
<< "_SUBSTPACK_";
2544 case TemplateName::UsingTemplate
: {
2545 TemplateDecl
*TD
= TN
.getAsTemplateDecl();
2546 assert(TD
&& !isa
<TemplateTemplateParmDecl
>(TD
));
2547 mangleSourceNameWithAbiTags(TD
);
2552 // Note: we don't pass in the template name here. We are mangling the
2553 // original source-level template arguments, so we shouldn't consider
2554 // conversions to the corresponding template parameter.
2555 // FIXME: Other compilers mangle partially-resolved template arguments in
2556 // unresolved-qualifier-levels.
2557 mangleTemplateArgs(TemplateName(), TST
->template_arguments());
2561 case Type::InjectedClassName
:
2562 mangleSourceNameWithAbiTags(
2563 cast
<InjectedClassNameType
>(Ty
)->getDecl());
2566 case Type::DependentName
:
2567 mangleSourceName(cast
<DependentNameType
>(Ty
)->getIdentifier());
2570 case Type::DependentTemplateSpecialization
: {
2571 const DependentTemplateSpecializationType
*DTST
=
2572 cast
<DependentTemplateSpecializationType
>(Ty
);
2573 TemplateName Template
= getASTContext().getDependentTemplateName(
2574 DTST
->getQualifier(), DTST
->getIdentifier());
2575 mangleSourceName(DTST
->getIdentifier());
2576 mangleTemplateArgs(Template
, DTST
->template_arguments());
2581 return mangleUnresolvedTypeOrSimpleId(cast
<UsingType
>(Ty
)->desugar(),
2583 case Type::Elaborated
:
2584 return mangleUnresolvedTypeOrSimpleId(
2585 cast
<ElaboratedType
>(Ty
)->getNamedType(), Prefix
);
2591 void CXXNameMangler::mangleOperatorName(DeclarationName Name
, unsigned Arity
) {
2592 switch (Name
.getNameKind()) {
2593 case DeclarationName::CXXConstructorName
:
2594 case DeclarationName::CXXDestructorName
:
2595 case DeclarationName::CXXDeductionGuideName
:
2596 case DeclarationName::CXXUsingDirective
:
2597 case DeclarationName::Identifier
:
2598 case DeclarationName::ObjCMultiArgSelector
:
2599 case DeclarationName::ObjCOneArgSelector
:
2600 case DeclarationName::ObjCZeroArgSelector
:
2601 llvm_unreachable("Not an operator name");
2603 case DeclarationName::CXXConversionFunctionName
:
2604 // <operator-name> ::= cv <type> # (cast)
2606 mangleType(Name
.getCXXNameType());
2609 case DeclarationName::CXXLiteralOperatorName
:
2611 mangleSourceName(Name
.getCXXLiteralIdentifier());
2614 case DeclarationName::CXXOperatorName
:
2615 mangleOperatorName(Name
.getCXXOverloadedOperator(), Arity
);
2621 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO
, unsigned Arity
) {
2623 // <operator-name> ::= nw # new
2624 case OO_New
: Out
<< "nw"; break;
2626 case OO_Array_New
: Out
<< "na"; break;
2628 case OO_Delete
: Out
<< "dl"; break;
2629 // ::= da # delete[]
2630 case OO_Array_Delete
: Out
<< "da"; break;
2631 // ::= ps # + (unary)
2632 // ::= pl # + (binary or unknown)
2634 Out
<< (Arity
== 1? "ps" : "pl"); break;
2635 // ::= ng # - (unary)
2636 // ::= mi # - (binary or unknown)
2638 Out
<< (Arity
== 1? "ng" : "mi"); break;
2639 // ::= ad # & (unary)
2640 // ::= an # & (binary or unknown)
2642 Out
<< (Arity
== 1? "ad" : "an"); break;
2643 // ::= de # * (unary)
2644 // ::= ml # * (binary or unknown)
2646 // Use binary when unknown.
2647 Out
<< (Arity
== 1? "de" : "ml"); break;
2649 case OO_Tilde
: Out
<< "co"; break;
2651 case OO_Slash
: Out
<< "dv"; break;
2653 case OO_Percent
: Out
<< "rm"; break;
2655 case OO_Pipe
: Out
<< "or"; break;
2657 case OO_Caret
: Out
<< "eo"; break;
2659 case OO_Equal
: Out
<< "aS"; break;
2661 case OO_PlusEqual
: Out
<< "pL"; break;
2663 case OO_MinusEqual
: Out
<< "mI"; break;
2665 case OO_StarEqual
: Out
<< "mL"; break;
2667 case OO_SlashEqual
: Out
<< "dV"; break;
2669 case OO_PercentEqual
: Out
<< "rM"; break;
2671 case OO_AmpEqual
: Out
<< "aN"; break;
2673 case OO_PipeEqual
: Out
<< "oR"; break;
2675 case OO_CaretEqual
: Out
<< "eO"; break;
2677 case OO_LessLess
: Out
<< "ls"; break;
2679 case OO_GreaterGreater
: Out
<< "rs"; break;
2681 case OO_LessLessEqual
: Out
<< "lS"; break;
2683 case OO_GreaterGreaterEqual
: Out
<< "rS"; break;
2685 case OO_EqualEqual
: Out
<< "eq"; break;
2687 case OO_ExclaimEqual
: Out
<< "ne"; break;
2689 case OO_Less
: Out
<< "lt"; break;
2691 case OO_Greater
: Out
<< "gt"; break;
2693 case OO_LessEqual
: Out
<< "le"; break;
2695 case OO_GreaterEqual
: Out
<< "ge"; break;
2697 case OO_Exclaim
: Out
<< "nt"; break;
2699 case OO_AmpAmp
: Out
<< "aa"; break;
2701 case OO_PipePipe
: Out
<< "oo"; break;
2703 case OO_PlusPlus
: Out
<< "pp"; break;
2705 case OO_MinusMinus
: Out
<< "mm"; break;
2707 case OO_Comma
: Out
<< "cm"; break;
2709 case OO_ArrowStar
: Out
<< "pm"; break;
2711 case OO_Arrow
: Out
<< "pt"; break;
2713 case OO_Call
: Out
<< "cl"; break;
2715 case OO_Subscript
: Out
<< "ix"; break;
2718 // The conditional operator can't be overloaded, but we still handle it when
2719 // mangling expressions.
2720 case OO_Conditional
: Out
<< "qu"; break;
2721 // Proposal on cxx-abi-dev, 2015-10-21.
2722 // ::= aw # co_await
2723 case OO_Coawait
: Out
<< "aw"; break;
2724 // Proposed in cxx-abi github issue 43.
2726 case OO_Spaceship
: Out
<< "ss"; break;
2729 case NUM_OVERLOADED_OPERATORS
:
2730 llvm_unreachable("Not an overloaded operator");
2734 void CXXNameMangler::mangleQualifiers(Qualifiers Quals
, const DependentAddressSpaceType
*DAST
) {
2735 // Vendor qualifiers come first and if they are order-insensitive they must
2736 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2738 // <type> ::= U <addrspace-expr>
2741 mangleExpression(DAST
->getAddrSpaceExpr());
2745 // Address space qualifiers start with an ordinary letter.
2746 if (Quals
.hasAddressSpace()) {
2747 // Address space extension:
2749 // <type> ::= U <target-addrspace>
2750 // <type> ::= U <OpenCL-addrspace>
2751 // <type> ::= U <CUDA-addrspace>
2753 SmallString
<64> ASString
;
2754 LangAS AS
= Quals
.getAddressSpace();
2756 if (Context
.getASTContext().addressSpaceMapManglingFor(AS
)) {
2757 // <target-addrspace> ::= "AS" <address-space-number>
2758 unsigned TargetAS
= Context
.getASTContext().getTargetAddressSpace(AS
);
2759 if (TargetAS
!= 0 ||
2760 Context
.getASTContext().getTargetAddressSpace(LangAS::Default
) != 0)
2761 ASString
= "AS" + llvm::utostr(TargetAS
);
2764 default: llvm_unreachable("Not a language specific address space");
2765 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2766 // "private"| "generic" | "device" |
2768 case LangAS::opencl_global
:
2769 ASString
= "CLglobal";
2771 case LangAS::opencl_global_device
:
2772 ASString
= "CLdevice";
2774 case LangAS::opencl_global_host
:
2775 ASString
= "CLhost";
2777 case LangAS::opencl_local
:
2778 ASString
= "CLlocal";
2780 case LangAS::opencl_constant
:
2781 ASString
= "CLconstant";
2783 case LangAS::opencl_private
:
2784 ASString
= "CLprivate";
2786 case LangAS::opencl_generic
:
2787 ASString
= "CLgeneric";
2789 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2790 // "device" | "host" ]
2791 case LangAS::sycl_global
:
2792 ASString
= "SYglobal";
2794 case LangAS::sycl_global_device
:
2795 ASString
= "SYdevice";
2797 case LangAS::sycl_global_host
:
2798 ASString
= "SYhost";
2800 case LangAS::sycl_local
:
2801 ASString
= "SYlocal";
2803 case LangAS::sycl_private
:
2804 ASString
= "SYprivate";
2806 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2807 case LangAS::cuda_device
:
2808 ASString
= "CUdevice";
2810 case LangAS::cuda_constant
:
2811 ASString
= "CUconstant";
2813 case LangAS::cuda_shared
:
2814 ASString
= "CUshared";
2816 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2817 case LangAS::ptr32_sptr
:
2818 ASString
= "ptr32_sptr";
2820 case LangAS::ptr32_uptr
:
2821 // For z/OS, there are no special mangling rules applied to the ptr32
2822 // qualifier. Ex: void foo(int * __ptr32 p) -> _Z3f2Pi. The mangling for
2823 // "p" is treated the same as a regular integer pointer.
2824 if (!getASTContext().getTargetInfo().getTriple().isOSzOS())
2825 ASString
= "ptr32_uptr";
2832 if (!ASString
.empty())
2833 mangleVendorQualifier(ASString
);
2836 // The ARC ownership qualifiers start with underscores.
2837 // Objective-C ARC Extension:
2839 // <type> ::= U "__strong"
2840 // <type> ::= U "__weak"
2841 // <type> ::= U "__autoreleasing"
2843 // Note: we emit __weak first to preserve the order as
2844 // required by the Itanium ABI.
2845 if (Quals
.getObjCLifetime() == Qualifiers::OCL_Weak
)
2846 mangleVendorQualifier("__weak");
2848 // __unaligned (from -fms-extensions)
2849 if (Quals
.hasUnaligned())
2850 mangleVendorQualifier("__unaligned");
2852 // Remaining ARC ownership qualifiers.
2853 switch (Quals
.getObjCLifetime()) {
2854 case Qualifiers::OCL_None
:
2857 case Qualifiers::OCL_Weak
:
2858 // Do nothing as we already handled this case above.
2861 case Qualifiers::OCL_Strong
:
2862 mangleVendorQualifier("__strong");
2865 case Qualifiers::OCL_Autoreleasing
:
2866 mangleVendorQualifier("__autoreleasing");
2869 case Qualifiers::OCL_ExplicitNone
:
2870 // The __unsafe_unretained qualifier is *not* mangled, so that
2871 // __unsafe_unretained types in ARC produce the same manglings as the
2872 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2873 // better ABI compatibility.
2875 // It's safe to do this because unqualified 'id' won't show up
2876 // in any type signatures that need to be mangled.
2880 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2881 if (Quals
.hasRestrict())
2883 if (Quals
.hasVolatile())
2885 if (Quals
.hasConst())
2889 void CXXNameMangler::mangleVendorQualifier(StringRef name
) {
2890 Out
<< 'U' << name
.size() << name
;
2893 void CXXNameMangler::mangleVendorType(StringRef name
) {
2894 Out
<< 'u' << name
.size() << name
;
2897 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier
) {
2898 // <ref-qualifier> ::= R # lvalue reference
2899 // ::= O # rvalue-reference
2900 switch (RefQualifier
) {
2914 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl
*MD
) {
2915 Context
.mangleObjCMethodNameAsSourceName(MD
, Out
);
2918 static bool isTypeSubstitutable(Qualifiers Quals
, const Type
*Ty
,
2922 if (Ty
->isSpecificBuiltinType(BuiltinType::ObjCSel
))
2924 if (Ty
->isOpenCLSpecificType())
2926 // From Clang 18.0 we correctly treat SVE types as substitution candidates.
2927 if (Ty
->isSVESizelessBuiltinType() &&
2928 Ctx
.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17
)
2930 if (Ty
->isBuiltinType())
2932 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2933 // substitution candidates.
2934 if (Ctx
.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6
&&
2937 // A placeholder type for class template deduction is substitutable with
2938 // its corresponding template name; this is handled specially when mangling
2940 if (auto *DeducedTST
= Ty
->getAs
<DeducedTemplateSpecializationType
>())
2941 if (DeducedTST
->getDeducedType().isNull())
2946 void CXXNameMangler::mangleType(QualType T
) {
2947 // If our type is instantiation-dependent but not dependent, we mangle
2948 // it as it was written in the source, removing any top-level sugar.
2949 // Otherwise, use the canonical type.
2951 // FIXME: This is an approximation of the instantiation-dependent name
2952 // mangling rules, since we should really be using the type as written and
2953 // augmented via semantic analysis (i.e., with implicit conversions and
2954 // default template arguments) for any instantiation-dependent type.
2955 // Unfortunately, that requires several changes to our AST:
2956 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2957 // uniqued, so that we can handle substitutions properly
2958 // - Default template arguments will need to be represented in the
2959 // TemplateSpecializationType, since they need to be mangled even though
2960 // they aren't written.
2961 // - Conversions on non-type template arguments need to be expressed, since
2962 // they can affect the mangling of sizeof/alignof.
2964 // FIXME: This is wrong when mapping to the canonical type for a dependent
2965 // type discards instantiation-dependent portions of the type, such as for:
2967 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2968 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2970 // It's also wrong in the opposite direction when instantiation-dependent,
2971 // canonically-equivalent types differ in some irrelevant portion of inner
2972 // type sugar. In such cases, we fail to form correct substitutions, eg:
2974 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2976 // We should instead canonicalize the non-instantiation-dependent parts,
2977 // regardless of whether the type as a whole is dependent or instantiation
2979 if (!T
->isInstantiationDependentType() || T
->isDependentType())
2980 T
= T
.getCanonicalType();
2982 // Desugar any types that are purely sugar.
2984 // Don't desugar through template specialization types that aren't
2985 // type aliases. We need to mangle the template arguments as written.
2986 if (const TemplateSpecializationType
*TST
2987 = dyn_cast
<TemplateSpecializationType
>(T
))
2988 if (!TST
->isTypeAlias())
2991 // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2992 // instantation-dependent qualifiers. See
2993 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2996 = T
.getSingleStepDesugaredType(Context
.getASTContext());
3003 SplitQualType split
= T
.split();
3004 Qualifiers quals
= split
.Quals
;
3005 const Type
*ty
= split
.Ty
;
3007 bool isSubstitutable
=
3008 isTypeSubstitutable(quals
, ty
, Context
.getASTContext());
3009 if (isSubstitutable
&& mangleSubstitution(T
))
3012 // If we're mangling a qualified array type, push the qualifiers to
3013 // the element type.
3014 if (quals
&& isa
<ArrayType
>(T
)) {
3015 ty
= Context
.getASTContext().getAsArrayType(T
);
3016 quals
= Qualifiers();
3018 // Note that we don't update T: we want to add the
3019 // substitution at the original type.
3022 if (quals
|| ty
->isDependentAddressSpaceType()) {
3023 if (const DependentAddressSpaceType
*DAST
=
3024 dyn_cast
<DependentAddressSpaceType
>(ty
)) {
3025 SplitQualType splitDAST
= DAST
->getPointeeType().split();
3026 mangleQualifiers(splitDAST
.Quals
, DAST
);
3027 mangleType(QualType(splitDAST
.Ty
, 0));
3029 mangleQualifiers(quals
);
3031 // Recurse: even if the qualified type isn't yet substitutable,
3032 // the unqualified type might be.
3033 mangleType(QualType(ty
, 0));
3036 switch (ty
->getTypeClass()) {
3037 #define ABSTRACT_TYPE(CLASS, PARENT)
3038 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
3040 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
3042 #define TYPE(CLASS, PARENT) \
3044 mangleType(static_cast<const CLASS##Type*>(ty)); \
3046 #include "clang/AST/TypeNodes.inc"
3050 // Add the substitution.
3051 if (isSubstitutable
)
3055 void CXXNameMangler::mangleCXXRecordDecl(const CXXRecordDecl
*Record
) {
3056 if (mangleSubstitution(Record
))
3059 if (isCompatibleWith(LangOptions::ClangABI::Ver19
))
3061 addSubstitution(Record
);
3064 void CXXNameMangler::mangleType(const BuiltinType
*T
) {
3065 // <type> ::= <builtin-type>
3066 // <builtin-type> ::= v # void
3070 // ::= a # signed char
3071 // ::= h # unsigned char
3073 // ::= t # unsigned short
3075 // ::= j # unsigned int
3077 // ::= m # unsigned long
3078 // ::= x # long long, __int64
3079 // ::= y # unsigned long long, __int64
3081 // ::= o # unsigned __int128
3084 // ::= e # long double, __float80
3085 // ::= g # __float128
3087 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
3088 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
3089 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
3090 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3091 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
3092 // ::= Di # char32_t
3093 // ::= Ds # char16_t
3094 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3095 // ::= [DS] DA # N1169 fixed-point [_Sat] T _Accum
3096 // ::= [DS] DR # N1169 fixed-point [_Sat] T _Fract
3097 // ::= u <source-name> # vendor extended type
3099 // <fixed-point-size>
3101 // ::= t # unsigned short
3105 // ::= m # unsigned long
3106 std::string type_name
;
3107 // Normalize integer types as vendor extended types:
3108 // u<length>i<type size>
3109 // u<length>u<type size>
3110 if (NormalizeIntegers
&& T
->isInteger()) {
3111 if (T
->isSignedInteger()) {
3112 switch (getASTContext().getTypeSize(T
)) {
3114 // Pick a representative for each integer size in the substitution
3115 // dictionary. (Its actual defined size is not relevant.)
3116 if (mangleSubstitution(BuiltinType::SChar
))
3119 addSubstitution(BuiltinType::SChar
);
3122 if (mangleSubstitution(BuiltinType::Short
))
3125 addSubstitution(BuiltinType::Short
);
3128 if (mangleSubstitution(BuiltinType::Int
))
3131 addSubstitution(BuiltinType::Int
);
3134 if (mangleSubstitution(BuiltinType::Long
))
3137 addSubstitution(BuiltinType::Long
);
3140 if (mangleSubstitution(BuiltinType::Int128
))
3143 addSubstitution(BuiltinType::Int128
);
3146 llvm_unreachable("Unknown integer size for normalization");
3149 switch (getASTContext().getTypeSize(T
)) {
3151 if (mangleSubstitution(BuiltinType::UChar
))
3154 addSubstitution(BuiltinType::UChar
);
3157 if (mangleSubstitution(BuiltinType::UShort
))
3160 addSubstitution(BuiltinType::UShort
);
3163 if (mangleSubstitution(BuiltinType::UInt
))
3166 addSubstitution(BuiltinType::UInt
);
3169 if (mangleSubstitution(BuiltinType::ULong
))
3172 addSubstitution(BuiltinType::ULong
);
3175 if (mangleSubstitution(BuiltinType::UInt128
))
3178 addSubstitution(BuiltinType::UInt128
);
3181 llvm_unreachable("Unknown integer size for normalization");
3186 switch (T
->getKind()) {
3187 case BuiltinType::Void
:
3190 case BuiltinType::Bool
:
3193 case BuiltinType::Char_U
:
3194 case BuiltinType::Char_S
:
3197 case BuiltinType::UChar
:
3200 case BuiltinType::UShort
:
3203 case BuiltinType::UInt
:
3206 case BuiltinType::ULong
:
3209 case BuiltinType::ULongLong
:
3212 case BuiltinType::UInt128
:
3215 case BuiltinType::SChar
:
3218 case BuiltinType::WChar_S
:
3219 case BuiltinType::WChar_U
:
3222 case BuiltinType::Char8
:
3225 case BuiltinType::Char16
:
3228 case BuiltinType::Char32
:
3231 case BuiltinType::Short
:
3234 case BuiltinType::Int
:
3237 case BuiltinType::Long
:
3240 case BuiltinType::LongLong
:
3243 case BuiltinType::Int128
:
3246 case BuiltinType::Float16
:
3249 case BuiltinType::ShortAccum
:
3252 case BuiltinType::Accum
:
3255 case BuiltinType::LongAccum
:
3258 case BuiltinType::UShortAccum
:
3261 case BuiltinType::UAccum
:
3264 case BuiltinType::ULongAccum
:
3267 case BuiltinType::ShortFract
:
3270 case BuiltinType::Fract
:
3273 case BuiltinType::LongFract
:
3276 case BuiltinType::UShortFract
:
3279 case BuiltinType::UFract
:
3282 case BuiltinType::ULongFract
:
3285 case BuiltinType::SatShortAccum
:
3288 case BuiltinType::SatAccum
:
3291 case BuiltinType::SatLongAccum
:
3294 case BuiltinType::SatUShortAccum
:
3297 case BuiltinType::SatUAccum
:
3300 case BuiltinType::SatULongAccum
:
3303 case BuiltinType::SatShortFract
:
3306 case BuiltinType::SatFract
:
3309 case BuiltinType::SatLongFract
:
3312 case BuiltinType::SatUShortFract
:
3315 case BuiltinType::SatUFract
:
3318 case BuiltinType::SatULongFract
:
3321 case BuiltinType::Half
:
3324 case BuiltinType::Float
:
3327 case BuiltinType::Double
:
3330 case BuiltinType::LongDouble
: {
3331 const TargetInfo
*TI
=
3332 getASTContext().getLangOpts().OpenMP
&&
3333 getASTContext().getLangOpts().OpenMPIsTargetDevice
3334 ? getASTContext().getAuxTargetInfo()
3335 : &getASTContext().getTargetInfo();
3336 Out
<< TI
->getLongDoubleMangling();
3339 case BuiltinType::Float128
: {
3340 const TargetInfo
*TI
=
3341 getASTContext().getLangOpts().OpenMP
&&
3342 getASTContext().getLangOpts().OpenMPIsTargetDevice
3343 ? getASTContext().getAuxTargetInfo()
3344 : &getASTContext().getTargetInfo();
3345 Out
<< TI
->getFloat128Mangling();
3348 case BuiltinType::BFloat16
: {
3349 const TargetInfo
*TI
=
3350 ((getASTContext().getLangOpts().OpenMP
&&
3351 getASTContext().getLangOpts().OpenMPIsTargetDevice
) ||
3352 getASTContext().getLangOpts().SYCLIsDevice
)
3353 ? getASTContext().getAuxTargetInfo()
3354 : &getASTContext().getTargetInfo();
3355 Out
<< TI
->getBFloat16Mangling();
3358 case BuiltinType::Ibm128
: {
3359 const TargetInfo
*TI
= &getASTContext().getTargetInfo();
3360 Out
<< TI
->getIbm128Mangling();
3363 case BuiltinType::NullPtr
:
3367 #define BUILTIN_TYPE(Id, SingletonId)
3368 #define PLACEHOLDER_TYPE(Id, SingletonId) \
3369 case BuiltinType::Id:
3370 #include "clang/AST/BuiltinTypes.def"
3371 case BuiltinType::Dependent
:
3373 llvm_unreachable("mangling a placeholder type");
3375 case BuiltinType::ObjCId
:
3376 Out
<< "11objc_object";
3378 case BuiltinType::ObjCClass
:
3379 Out
<< "10objc_class";
3381 case BuiltinType::ObjCSel
:
3382 Out
<< "13objc_selector";
3384 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3385 case BuiltinType::Id: \
3386 type_name = "ocl_" #ImgType "_" #Suffix; \
3387 Out << type_name.size() << type_name; \
3389 #include "clang/Basic/OpenCLImageTypes.def"
3390 case BuiltinType::OCLSampler
:
3391 Out
<< "11ocl_sampler";
3393 case BuiltinType::OCLEvent
:
3394 Out
<< "9ocl_event";
3396 case BuiltinType::OCLClkEvent
:
3397 Out
<< "12ocl_clkevent";
3399 case BuiltinType::OCLQueue
:
3400 Out
<< "9ocl_queue";
3402 case BuiltinType::OCLReserveID
:
3403 Out
<< "13ocl_reserveid";
3405 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3406 case BuiltinType::Id: \
3407 type_name = "ocl_" #ExtType; \
3408 Out << type_name.size() << type_name; \
3410 #include "clang/Basic/OpenCLExtensionTypes.def"
3411 // The SVE types are effectively target-specific. The mangling scheme
3412 // is defined in the appendices to the Procedure Call Standard for the
3413 // Arm Architecture.
3414 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
3415 case BuiltinType::Id: \
3416 if (T->getKind() == BuiltinType::SveBFloat16 && \
3417 isCompatibleWith(LangOptions::ClangABI::Ver17)) { \
3418 /* Prior to Clang 18.0 we used this incorrect mangled name */ \
3419 mangleVendorType("__SVBFloat16_t"); \
3421 type_name = MangledName; \
3422 Out << (type_name == Name ? "u" : "") << type_name.size() << type_name; \
3425 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
3426 case BuiltinType::Id: \
3427 type_name = MangledName; \
3428 Out << (type_name == Name ? "u" : "") << type_name.size() << type_name; \
3430 #define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
3431 case BuiltinType::Id: \
3432 type_name = MangledName; \
3433 Out << (type_name == Name ? "u" : "") << type_name.size() << type_name; \
3435 #define AARCH64_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
3436 case BuiltinType::Id: \
3437 type_name = MangledName; \
3438 Out << (type_name == Name ? "u" : "") << type_name.size() << type_name; \
3440 #include "clang/Basic/AArch64SVEACLETypes.def"
3441 #define PPC_VECTOR_TYPE(Name, Id, Size) \
3442 case BuiltinType::Id: \
3443 mangleVendorType(#Name); \
3445 #include "clang/Basic/PPCTypes.def"
3446 // TODO: Check the mangling scheme for RISC-V V.
3447 #define RVV_TYPE(Name, Id, SingletonId) \
3448 case BuiltinType::Id: \
3449 mangleVendorType(Name); \
3451 #include "clang/Basic/RISCVVTypes.def"
3452 #define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \
3453 case BuiltinType::Id: \
3454 mangleVendorType(MangledName); \
3456 #include "clang/Basic/WebAssemblyReferenceTypes.def"
3457 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
3458 case BuiltinType::Id: \
3459 mangleVendorType(Name); \
3461 #include "clang/Basic/AMDGPUTypes.def"
3462 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3463 case BuiltinType::Id: \
3464 mangleVendorType(#Name); \
3466 #include "clang/Basic/HLSLIntangibleTypes.def"
3470 StringRef
CXXNameMangler::getCallingConvQualifierName(CallingConv CC
) {
3475 case CC_X86VectorCall
:
3480 case CC_AArch64VectorCall
:
3481 case CC_AArch64SVEPCS
:
3482 case CC_AMDGPUKernelCall
:
3483 case CC_IntelOclBicc
:
3484 case CC_SpirFunction
:
3485 case CC_OpenCLKernel
:
3486 case CC_PreserveMost
:
3487 case CC_PreserveAll
:
3489 case CC_PreserveNone
:
3490 case CC_RISCVVectorCall
:
3491 // FIXME: we should be mangling all of the above.
3494 case CC_X86ThisCall
:
3495 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3496 // used explicitly. At this point, we don't have that much information in
3497 // the AST, since clang tends to bake the convention into the canonical
3498 // function type. thiscall only rarely used explicitly, so don't mangle it
3504 case CC_X86FastCall
:
3513 return "swiftasynccall";
3515 llvm_unreachable("bad calling convention");
3518 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType
*T
) {
3520 if (T
->getExtInfo() == FunctionType::ExtInfo())
3523 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3524 // This will get more complicated in the future if we mangle other
3525 // things here; but for now, since we mangle ns_returns_retained as
3526 // a qualifier on the result type, we can get away with this:
3527 StringRef CCQualifier
= getCallingConvQualifierName(T
->getExtInfo().getCC());
3528 if (!CCQualifier
.empty())
3529 mangleVendorQualifier(CCQualifier
);
3536 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI
) {
3537 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3539 // Note that these are *not* substitution candidates. Demanglers might
3540 // have trouble with this if the parameter type is fully substituted.
3542 switch (PI
.getABI()) {
3543 case ParameterABI::Ordinary
:
3546 // HLSL parameter mangling.
3547 case ParameterABI::HLSLOut
:
3548 case ParameterABI::HLSLInOut
:
3549 mangleVendorQualifier(getParameterABISpelling(PI
.getABI()));
3552 // All of these start with "swift", so they come before "ns_consumed".
3553 case ParameterABI::SwiftContext
:
3554 case ParameterABI::SwiftAsyncContext
:
3555 case ParameterABI::SwiftErrorResult
:
3556 case ParameterABI::SwiftIndirectResult
:
3557 mangleVendorQualifier(getParameterABISpelling(PI
.getABI()));
3561 if (PI
.isConsumed())
3562 mangleVendorQualifier("ns_consumed");
3564 if (PI
.isNoEscape())
3565 mangleVendorQualifier("noescape");
3568 // <type> ::= <function-type>
3569 // <function-type> ::= [<CV-qualifiers>] F [Y]
3570 // <bare-function-type> [<ref-qualifier>] E
3571 void CXXNameMangler::mangleType(const FunctionProtoType
*T
) {
3572 mangleExtFunctionInfo(T
);
3574 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3575 // e.g. "const" in "int (A::*)() const".
3576 mangleQualifiers(T
->getMethodQuals());
3578 // Mangle instantiation-dependent exception-specification, if present,
3579 // per cxx-abi-dev proposal on 2016-10-11.
3580 if (T
->hasInstantiationDependentExceptionSpec()) {
3581 if (isComputedNoexcept(T
->getExceptionSpecType())) {
3583 mangleExpression(T
->getNoexceptExpr());
3586 assert(T
->getExceptionSpecType() == EST_Dynamic
);
3588 for (auto ExceptTy
: T
->exceptions())
3589 mangleType(ExceptTy
);
3592 } else if (T
->isNothrow()) {
3598 // FIXME: We don't have enough information in the AST to produce the 'Y'
3599 // encoding for extern "C" function types.
3600 mangleBareFunctionType(T
, /*MangleReturnType=*/true);
3602 // Mangle the ref-qualifier, if present.
3603 mangleRefQualifier(T
->getRefQualifier());
3608 void CXXNameMangler::mangleType(const FunctionNoProtoType
*T
) {
3609 // Function types without prototypes can arise when mangling a function type
3610 // within an overloadable function in C. We mangle these as the absence of any
3611 // parameter types (not even an empty parameter list).
3614 FunctionTypeDepthState saved
= FunctionTypeDepth
.push();
3616 FunctionTypeDepth
.enterResultType();
3617 mangleType(T
->getReturnType());
3618 FunctionTypeDepth
.leaveResultType();
3620 FunctionTypeDepth
.pop(saved
);
3624 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType
*Proto
,
3625 bool MangleReturnType
,
3626 const FunctionDecl
*FD
) {
3627 // Record that we're in a function type. See mangleFunctionParam
3628 // for details on what we're trying to achieve here.
3629 FunctionTypeDepthState saved
= FunctionTypeDepth
.push();
3631 // <bare-function-type> ::= <signature type>+
3632 if (MangleReturnType
) {
3633 FunctionTypeDepth
.enterResultType();
3635 // Mangle ns_returns_retained as an order-sensitive qualifier here.
3636 if (Proto
->getExtInfo().getProducesResult() && FD
== nullptr)
3637 mangleVendorQualifier("ns_returns_retained");
3639 // Mangle the return type without any direct ARC ownership qualifiers.
3640 QualType ReturnTy
= Proto
->getReturnType();
3641 if (ReturnTy
.getObjCLifetime()) {
3642 auto SplitReturnTy
= ReturnTy
.split();
3643 SplitReturnTy
.Quals
.removeObjCLifetime();
3644 ReturnTy
= getASTContext().getQualifiedType(SplitReturnTy
);
3646 mangleType(ReturnTy
);
3648 FunctionTypeDepth
.leaveResultType();
3651 if (Proto
->getNumParams() == 0 && !Proto
->isVariadic()) {
3652 // <builtin-type> ::= v # void
3655 assert(!FD
|| FD
->getNumParams() == Proto
->getNumParams());
3656 for (unsigned I
= 0, E
= Proto
->getNumParams(); I
!= E
; ++I
) {
3657 // Mangle extended parameter info as order-sensitive qualifiers here.
3658 if (Proto
->hasExtParameterInfos() && FD
== nullptr) {
3659 mangleExtParameterInfo(Proto
->getExtParameterInfo(I
));
3663 QualType ParamTy
= Proto
->getParamType(I
);
3664 mangleType(Context
.getASTContext().getSignatureParameterType(ParamTy
));
3667 if (auto *Attr
= FD
->getParamDecl(I
)->getAttr
<PassObjectSizeAttr
>()) {
3668 // Attr can only take 1 character, so we can hardcode the length
3670 assert(Attr
->getType() <= 9 && Attr
->getType() >= 0);
3671 if (Attr
->isDynamic())
3672 Out
<< "U25pass_dynamic_object_size" << Attr
->getType();
3674 Out
<< "U17pass_object_size" << Attr
->getType();
3679 // <builtin-type> ::= z # ellipsis
3680 if (Proto
->isVariadic())
3685 FunctionTypeDepth
.enterResultType();
3686 mangleRequiresClause(FD
->getTrailingRequiresClause());
3689 FunctionTypeDepth
.pop(saved
);
3692 // <type> ::= <class-enum-type>
3693 // <class-enum-type> ::= <name>
3694 void CXXNameMangler::mangleType(const UnresolvedUsingType
*T
) {
3695 mangleName(T
->getDecl());
3698 // <type> ::= <class-enum-type>
3699 // <class-enum-type> ::= <name>
3700 void CXXNameMangler::mangleType(const EnumType
*T
) {
3701 mangleType(static_cast<const TagType
*>(T
));
3703 void CXXNameMangler::mangleType(const RecordType
*T
) {
3704 mangleType(static_cast<const TagType
*>(T
));
3706 void CXXNameMangler::mangleType(const TagType
*T
) {
3707 mangleName(T
->getDecl());
3710 // <type> ::= <array-type>
3711 // <array-type> ::= A <positive dimension number> _ <element type>
3712 // ::= A [<dimension expression>] _ <element type>
3713 void CXXNameMangler::mangleType(const ConstantArrayType
*T
) {
3714 Out
<< 'A' << T
->getSize() << '_';
3715 mangleType(T
->getElementType());
3717 void CXXNameMangler::mangleType(const VariableArrayType
*T
) {
3719 // decayed vla types (size 0) will just be skipped.
3720 if (T
->getSizeExpr())
3721 mangleExpression(T
->getSizeExpr());
3723 mangleType(T
->getElementType());
3725 void CXXNameMangler::mangleType(const DependentSizedArrayType
*T
) {
3727 // A DependentSizedArrayType might not have size expression as below
3729 // template<int ...N> int arr[] = {N...};
3730 if (T
->getSizeExpr())
3731 mangleExpression(T
->getSizeExpr());
3733 mangleType(T
->getElementType());
3735 void CXXNameMangler::mangleType(const IncompleteArrayType
*T
) {
3737 mangleType(T
->getElementType());
3740 // <type> ::= <pointer-to-member-type>
3741 // <pointer-to-member-type> ::= M <class type> <member type>
3742 void CXXNameMangler::mangleType(const MemberPointerType
*T
) {
3744 mangleType(QualType(T
->getClass(), 0));
3745 QualType PointeeType
= T
->getPointeeType();
3746 if (const FunctionProtoType
*FPT
= dyn_cast
<FunctionProtoType
>(PointeeType
)) {
3749 // Itanium C++ ABI 5.1.8:
3751 // The type of a non-static member function is considered to be different,
3752 // for the purposes of substitution, from the type of a namespace-scope or
3753 // static member function whose type appears similar. The types of two
3754 // non-static member functions are considered to be different, for the
3755 // purposes of substitution, if the functions are members of different
3756 // classes. In other words, for the purposes of substitution, the class of
3757 // which the function is a member is considered part of the type of
3760 // Given that we already substitute member function pointers as a
3761 // whole, the net effect of this rule is just to unconditionally
3762 // suppress substitution on the function type in a member pointer.
3763 // We increment the SeqID here to emulate adding an entry to the
3764 // substitution table.
3767 mangleType(PointeeType
);
3770 // <type> ::= <template-param>
3771 void CXXNameMangler::mangleType(const TemplateTypeParmType
*T
) {
3772 mangleTemplateParameter(T
->getDepth(), T
->getIndex());
3775 // <type> ::= <template-param>
3776 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType
*T
) {
3777 // FIXME: not clear how to mangle this!
3778 // template <class T...> class A {
3779 // template <class U...> void foo(T(*)(U) x...);
3781 Out
<< "_SUBSTPACK_";
3784 // <type> ::= P <type> # pointer-to
3785 void CXXNameMangler::mangleType(const PointerType
*T
) {
3787 mangleType(T
->getPointeeType());
3789 void CXXNameMangler::mangleType(const ObjCObjectPointerType
*T
) {
3791 mangleType(T
->getPointeeType());
3794 // <type> ::= R <type> # reference-to
3795 void CXXNameMangler::mangleType(const LValueReferenceType
*T
) {
3797 mangleType(T
->getPointeeType());
3800 // <type> ::= O <type> # rvalue reference-to (C++0x)
3801 void CXXNameMangler::mangleType(const RValueReferenceType
*T
) {
3803 mangleType(T
->getPointeeType());
3806 // <type> ::= C <type> # complex pair (C 2000)
3807 void CXXNameMangler::mangleType(const ComplexType
*T
) {
3809 mangleType(T
->getElementType());
3812 // ARM's ABI for Neon vector types specifies that they should be mangled as
3813 // if they are structs (to match ARM's initial implementation). The
3814 // vector type must be one of the special types predefined by ARM.
3815 void CXXNameMangler::mangleNeonVectorType(const VectorType
*T
) {
3816 QualType EltType
= T
->getElementType();
3817 assert(EltType
->isBuiltinType() && "Neon vector element not a BuiltinType");
3818 const char *EltName
= nullptr;
3819 if (T
->getVectorKind() == VectorKind::NeonPoly
) {
3820 switch (cast
<BuiltinType
>(EltType
)->getKind()) {
3821 case BuiltinType::SChar
:
3822 case BuiltinType::UChar
:
3823 EltName
= "poly8_t";
3825 case BuiltinType::Short
:
3826 case BuiltinType::UShort
:
3827 EltName
= "poly16_t";
3829 case BuiltinType::LongLong
:
3830 case BuiltinType::ULongLong
:
3831 EltName
= "poly64_t";
3833 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3836 switch (cast
<BuiltinType
>(EltType
)->getKind()) {
3837 case BuiltinType::SChar
: EltName
= "int8_t"; break;
3838 case BuiltinType::UChar
: EltName
= "uint8_t"; break;
3839 case BuiltinType::Short
: EltName
= "int16_t"; break;
3840 case BuiltinType::UShort
: EltName
= "uint16_t"; break;
3841 case BuiltinType::Int
: EltName
= "int32_t"; break;
3842 case BuiltinType::UInt
: EltName
= "uint32_t"; break;
3843 case BuiltinType::LongLong
: EltName
= "int64_t"; break;
3844 case BuiltinType::ULongLong
: EltName
= "uint64_t"; break;
3845 case BuiltinType::Double
: EltName
= "float64_t"; break;
3846 case BuiltinType::Float
: EltName
= "float32_t"; break;
3847 case BuiltinType::Half
: EltName
= "float16_t"; break;
3848 case BuiltinType::BFloat16
: EltName
= "bfloat16_t"; break;
3850 llvm_unreachable("unexpected Neon vector element type");
3853 const char *BaseName
= nullptr;
3854 unsigned BitSize
= (T
->getNumElements() *
3855 getASTContext().getTypeSize(EltType
));
3857 BaseName
= "__simd64_";
3859 assert(BitSize
== 128 && "Neon vector type not 64 or 128 bits");
3860 BaseName
= "__simd128_";
3862 Out
<< strlen(BaseName
) + strlen(EltName
);
3863 Out
<< BaseName
<< EltName
;
3866 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType
*T
) {
3867 DiagnosticsEngine
&Diags
= Context
.getDiags();
3868 unsigned DiagID
= Diags
.getCustomDiagID(
3869 DiagnosticsEngine::Error
,
3870 "cannot mangle this dependent neon vector type yet");
3871 Diags
.Report(T
->getAttributeLoc(), DiagID
);
3874 static StringRef
mangleAArch64VectorBase(const BuiltinType
*EltType
) {
3875 switch (EltType
->getKind()) {
3876 case BuiltinType::SChar
:
3878 case BuiltinType::Short
:
3880 case BuiltinType::Int
:
3882 case BuiltinType::Long
:
3883 case BuiltinType::LongLong
:
3885 case BuiltinType::UChar
:
3887 case BuiltinType::UShort
:
3889 case BuiltinType::UInt
:
3891 case BuiltinType::ULong
:
3892 case BuiltinType::ULongLong
:
3894 case BuiltinType::Half
:
3896 case BuiltinType::Float
:
3898 case BuiltinType::Double
:
3900 case BuiltinType::BFloat16
:
3903 llvm_unreachable("Unexpected vector element base type");
3907 // AArch64's ABI for Neon vector types specifies that they should be mangled as
3908 // the equivalent internal name. The vector type must be one of the special
3909 // types predefined by ARM.
3910 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType
*T
) {
3911 QualType EltType
= T
->getElementType();
3912 assert(EltType
->isBuiltinType() && "Neon vector element not a BuiltinType");
3914 (T
->getNumElements() * getASTContext().getTypeSize(EltType
));
3915 (void)BitSize
; // Silence warning.
3917 assert((BitSize
== 64 || BitSize
== 128) &&
3918 "Neon vector type not 64 or 128 bits");
3921 if (T
->getVectorKind() == VectorKind::NeonPoly
) {
3922 switch (cast
<BuiltinType
>(EltType
)->getKind()) {
3923 case BuiltinType::UChar
:
3926 case BuiltinType::UShort
:
3929 case BuiltinType::ULong
:
3930 case BuiltinType::ULongLong
:
3934 llvm_unreachable("unexpected Neon polynomial vector element type");
3937 EltName
= mangleAArch64VectorBase(cast
<BuiltinType
>(EltType
));
3939 std::string TypeName
=
3940 ("__" + EltName
+ "x" + Twine(T
->getNumElements()) + "_t").str();
3941 Out
<< TypeName
.length() << TypeName
;
3943 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType
*T
) {
3944 DiagnosticsEngine
&Diags
= Context
.getDiags();
3945 unsigned DiagID
= Diags
.getCustomDiagID(
3946 DiagnosticsEngine::Error
,
3947 "cannot mangle this dependent neon vector type yet");
3948 Diags
.Report(T
->getAttributeLoc(), DiagID
);
3951 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3952 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3953 // type as the sizeless variants.
3955 // The mangling scheme for VLS types is implemented as a "pseudo" template:
3957 // '__SVE_VLS<<type>, <vector length>>'
3959 // Combining the existing SVE type and a specific vector length (in bits).
3962 // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3964 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3966 // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3968 // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3970 // The latest ACLE specification (00bet5) does not contain details of this
3971 // mangling scheme, it will be specified in the next revision. The mangling
3972 // scheme is otherwise defined in the appendices to the Procedure Call Standard
3973 // for the Arm Architecture, see
3974 // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
3975 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType
*T
) {
3976 assert((T
->getVectorKind() == VectorKind::SveFixedLengthData
||
3977 T
->getVectorKind() == VectorKind::SveFixedLengthPredicate
) &&
3978 "expected fixed-length SVE vector!");
3980 QualType EltType
= T
->getElementType();
3981 assert(EltType
->isBuiltinType() &&
3982 "expected builtin type for fixed-length SVE vector!");
3985 switch (cast
<BuiltinType
>(EltType
)->getKind()) {
3986 case BuiltinType::SChar
:
3987 TypeName
= "__SVInt8_t";
3989 case BuiltinType::UChar
: {
3990 if (T
->getVectorKind() == VectorKind::SveFixedLengthData
)
3991 TypeName
= "__SVUint8_t";
3993 TypeName
= "__SVBool_t";
3996 case BuiltinType::Short
:
3997 TypeName
= "__SVInt16_t";
3999 case BuiltinType::UShort
:
4000 TypeName
= "__SVUint16_t";
4002 case BuiltinType::Int
:
4003 TypeName
= "__SVInt32_t";
4005 case BuiltinType::UInt
:
4006 TypeName
= "__SVUint32_t";
4008 case BuiltinType::Long
:
4009 TypeName
= "__SVInt64_t";
4011 case BuiltinType::ULong
:
4012 TypeName
= "__SVUint64_t";
4014 case BuiltinType::Half
:
4015 TypeName
= "__SVFloat16_t";
4017 case BuiltinType::Float
:
4018 TypeName
= "__SVFloat32_t";
4020 case BuiltinType::Double
:
4021 TypeName
= "__SVFloat64_t";
4023 case BuiltinType::BFloat16
:
4024 TypeName
= "__SVBfloat16_t";
4027 llvm_unreachable("unexpected element type for fixed-length SVE vector!");
4030 unsigned VecSizeInBits
= getASTContext().getTypeInfo(T
).Width
;
4032 if (T
->getVectorKind() == VectorKind::SveFixedLengthPredicate
)
4035 Out
<< "9__SVE_VLSI";
4036 mangleVendorType(TypeName
);
4037 Out
<< "Lj" << VecSizeInBits
<< "EE";
4040 void CXXNameMangler::mangleAArch64FixedSveVectorType(
4041 const DependentVectorType
*T
) {
4042 DiagnosticsEngine
&Diags
= Context
.getDiags();
4043 unsigned DiagID
= Diags
.getCustomDiagID(
4044 DiagnosticsEngine::Error
,
4045 "cannot mangle this dependent fixed-length SVE vector type yet");
4046 Diags
.Report(T
->getAttributeLoc(), DiagID
);
4049 void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType
*T
) {
4050 assert((T
->getVectorKind() == VectorKind::RVVFixedLengthData
||
4051 T
->getVectorKind() == VectorKind::RVVFixedLengthMask
||
4052 T
->getVectorKind() == VectorKind::RVVFixedLengthMask_1
||
4053 T
->getVectorKind() == VectorKind::RVVFixedLengthMask_2
||
4054 T
->getVectorKind() == VectorKind::RVVFixedLengthMask_4
) &&
4055 "expected fixed-length RVV vector!");
4057 QualType EltType
= T
->getElementType();
4058 assert(EltType
->isBuiltinType() &&
4059 "expected builtin type for fixed-length RVV vector!");
4061 SmallString
<20> TypeNameStr
;
4062 llvm::raw_svector_ostream
TypeNameOS(TypeNameStr
);
4063 TypeNameOS
<< "__rvv_";
4064 switch (cast
<BuiltinType
>(EltType
)->getKind()) {
4065 case BuiltinType::SChar
:
4066 TypeNameOS
<< "int8";
4068 case BuiltinType::UChar
:
4069 if (T
->getVectorKind() == VectorKind::RVVFixedLengthData
)
4070 TypeNameOS
<< "uint8";
4072 TypeNameOS
<< "bool";
4074 case BuiltinType::Short
:
4075 TypeNameOS
<< "int16";
4077 case BuiltinType::UShort
:
4078 TypeNameOS
<< "uint16";
4080 case BuiltinType::Int
:
4081 TypeNameOS
<< "int32";
4083 case BuiltinType::UInt
:
4084 TypeNameOS
<< "uint32";
4086 case BuiltinType::Long
:
4087 TypeNameOS
<< "int64";
4089 case BuiltinType::ULong
:
4090 TypeNameOS
<< "uint64";
4092 case BuiltinType::Float16
:
4093 TypeNameOS
<< "float16";
4095 case BuiltinType::Float
:
4096 TypeNameOS
<< "float32";
4098 case BuiltinType::Double
:
4099 TypeNameOS
<< "float64";
4102 llvm_unreachable("unexpected element type for fixed-length RVV vector!");
4105 unsigned VecSizeInBits
;
4106 switch (T
->getVectorKind()) {
4107 case VectorKind::RVVFixedLengthMask_1
:
4110 case VectorKind::RVVFixedLengthMask_2
:
4113 case VectorKind::RVVFixedLengthMask_4
:
4117 VecSizeInBits
= getASTContext().getTypeInfo(T
).Width
;
4121 // Apend the LMUL suffix.
4122 auto VScale
= getASTContext().getTargetInfo().getVScaleRange(
4123 getASTContext().getLangOpts());
4124 unsigned VLen
= VScale
->first
* llvm::RISCV::RVVBitsPerBlock
;
4126 if (T
->getVectorKind() == VectorKind::RVVFixedLengthData
) {
4128 if (VecSizeInBits
>= VLen
)
4129 TypeNameOS
<< (VecSizeInBits
/ VLen
);
4131 TypeNameOS
<< 'f' << (VLen
/ VecSizeInBits
);
4133 TypeNameOS
<< (VLen
/ VecSizeInBits
);
4137 Out
<< "9__RVV_VLSI";
4138 mangleVendorType(TypeNameStr
);
4139 Out
<< "Lj" << VecSizeInBits
<< "EE";
4142 void CXXNameMangler::mangleRISCVFixedRVVVectorType(
4143 const DependentVectorType
*T
) {
4144 DiagnosticsEngine
&Diags
= Context
.getDiags();
4145 unsigned DiagID
= Diags
.getCustomDiagID(
4146 DiagnosticsEngine::Error
,
4147 "cannot mangle this dependent fixed-length RVV vector type yet");
4148 Diags
.Report(T
->getAttributeLoc(), DiagID
);
4151 // GNU extension: vector types
4152 // <type> ::= <vector-type>
4153 // <vector-type> ::= Dv <positive dimension number> _
4154 // <extended element type>
4155 // ::= Dv [<dimension expression>] _ <element type>
4156 // <extended element type> ::= <element type>
4157 // ::= p # AltiVec vector pixel
4158 // ::= b # Altivec vector bool
4159 void CXXNameMangler::mangleType(const VectorType
*T
) {
4160 if ((T
->getVectorKind() == VectorKind::Neon
||
4161 T
->getVectorKind() == VectorKind::NeonPoly
)) {
4162 llvm::Triple Target
= getASTContext().getTargetInfo().getTriple();
4163 llvm::Triple::ArchType Arch
=
4164 getASTContext().getTargetInfo().getTriple().getArch();
4165 if ((Arch
== llvm::Triple::aarch64
||
4166 Arch
== llvm::Triple::aarch64_be
) && !Target
.isOSDarwin())
4167 mangleAArch64NeonVectorType(T
);
4169 mangleNeonVectorType(T
);
4171 } else if (T
->getVectorKind() == VectorKind::SveFixedLengthData
||
4172 T
->getVectorKind() == VectorKind::SveFixedLengthPredicate
) {
4173 mangleAArch64FixedSveVectorType(T
);
4175 } else if (T
->getVectorKind() == VectorKind::RVVFixedLengthData
||
4176 T
->getVectorKind() == VectorKind::RVVFixedLengthMask
||
4177 T
->getVectorKind() == VectorKind::RVVFixedLengthMask_1
||
4178 T
->getVectorKind() == VectorKind::RVVFixedLengthMask_2
||
4179 T
->getVectorKind() == VectorKind::RVVFixedLengthMask_4
) {
4180 mangleRISCVFixedRVVVectorType(T
);
4183 Out
<< "Dv" << T
->getNumElements() << '_';
4184 if (T
->getVectorKind() == VectorKind::AltiVecPixel
)
4186 else if (T
->getVectorKind() == VectorKind::AltiVecBool
)
4189 mangleType(T
->getElementType());
4192 void CXXNameMangler::mangleType(const DependentVectorType
*T
) {
4193 if ((T
->getVectorKind() == VectorKind::Neon
||
4194 T
->getVectorKind() == VectorKind::NeonPoly
)) {
4195 llvm::Triple Target
= getASTContext().getTargetInfo().getTriple();
4196 llvm::Triple::ArchType Arch
=
4197 getASTContext().getTargetInfo().getTriple().getArch();
4198 if ((Arch
== llvm::Triple::aarch64
|| Arch
== llvm::Triple::aarch64_be
) &&
4199 !Target
.isOSDarwin())
4200 mangleAArch64NeonVectorType(T
);
4202 mangleNeonVectorType(T
);
4204 } else if (T
->getVectorKind() == VectorKind::SveFixedLengthData
||
4205 T
->getVectorKind() == VectorKind::SveFixedLengthPredicate
) {
4206 mangleAArch64FixedSveVectorType(T
);
4208 } else if (T
->getVectorKind() == VectorKind::RVVFixedLengthData
) {
4209 mangleRISCVFixedRVVVectorType(T
);
4214 mangleExpression(T
->getSizeExpr());
4216 if (T
->getVectorKind() == VectorKind::AltiVecPixel
)
4218 else if (T
->getVectorKind() == VectorKind::AltiVecBool
)
4221 mangleType(T
->getElementType());
4224 void CXXNameMangler::mangleType(const ExtVectorType
*T
) {
4225 mangleType(static_cast<const VectorType
*>(T
));
4227 void CXXNameMangler::mangleType(const DependentSizedExtVectorType
*T
) {
4229 mangleExpression(T
->getSizeExpr());
4231 mangleType(T
->getElementType());
4234 void CXXNameMangler::mangleType(const ConstantMatrixType
*T
) {
4235 // Mangle matrix types as a vendor extended type:
4236 // u<Len>matrix_typeI<Rows><Columns><element type>E
4238 mangleVendorType("matrix_type");
4241 auto &ASTCtx
= getASTContext();
4242 unsigned BitWidth
= ASTCtx
.getTypeSize(ASTCtx
.getSizeType());
4243 llvm::APSInt
Rows(BitWidth
);
4244 Rows
= T
->getNumRows();
4245 mangleIntegerLiteral(ASTCtx
.getSizeType(), Rows
);
4246 llvm::APSInt
Columns(BitWidth
);
4247 Columns
= T
->getNumColumns();
4248 mangleIntegerLiteral(ASTCtx
.getSizeType(), Columns
);
4249 mangleType(T
->getElementType());
4253 void CXXNameMangler::mangleType(const DependentSizedMatrixType
*T
) {
4254 // Mangle matrix types as a vendor extended type:
4255 // u<Len>matrix_typeI<row expr><column expr><element type>E
4256 mangleVendorType("matrix_type");
4259 mangleTemplateArgExpr(T
->getRowExpr());
4260 mangleTemplateArgExpr(T
->getColumnExpr());
4261 mangleType(T
->getElementType());
4265 void CXXNameMangler::mangleType(const DependentAddressSpaceType
*T
) {
4266 SplitQualType split
= T
->getPointeeType().split();
4267 mangleQualifiers(split
.Quals
, T
);
4268 mangleType(QualType(split
.Ty
, 0));
4271 void CXXNameMangler::mangleType(const PackExpansionType
*T
) {
4272 // <type> ::= Dp <type> # pack expansion (C++0x)
4274 mangleType(T
->getPattern());
4277 void CXXNameMangler::mangleType(const PackIndexingType
*T
) {
4278 if (!T
->hasSelectedType())
4279 mangleType(T
->getPattern());
4281 mangleType(T
->getSelectedType());
4284 void CXXNameMangler::mangleType(const ObjCInterfaceType
*T
) {
4285 mangleSourceName(T
->getDecl()->getIdentifier());
4288 void CXXNameMangler::mangleType(const ObjCObjectType
*T
) {
4289 // Treat __kindof as a vendor extended type qualifier.
4290 if (T
->isKindOfType())
4291 Out
<< "U8__kindof";
4293 if (!T
->qual_empty()) {
4294 // Mangle protocol qualifiers.
4295 SmallString
<64> QualStr
;
4296 llvm::raw_svector_ostream
QualOS(QualStr
);
4297 QualOS
<< "objcproto";
4298 for (const auto *I
: T
->quals()) {
4299 StringRef name
= I
->getName();
4300 QualOS
<< name
.size() << name
;
4302 mangleVendorQualifier(QualStr
);
4305 mangleType(T
->getBaseType());
4307 if (T
->isSpecialized()) {
4308 // Mangle type arguments as I <type>+ E
4310 for (auto typeArg
: T
->getTypeArgs())
4311 mangleType(typeArg
);
4316 void CXXNameMangler::mangleType(const BlockPointerType
*T
) {
4317 Out
<< "U13block_pointer";
4318 mangleType(T
->getPointeeType());
4321 void CXXNameMangler::mangleType(const InjectedClassNameType
*T
) {
4322 // Mangle injected class name types as if the user had written the
4323 // specialization out fully. It may not actually be possible to see
4324 // this mangling, though.
4325 mangleType(T
->getInjectedSpecializationType());
4328 void CXXNameMangler::mangleType(const TemplateSpecializationType
*T
) {
4329 if (TemplateDecl
*TD
= T
->getTemplateName().getAsTemplateDecl()) {
4330 mangleTemplateName(TD
, T
->template_arguments());
4332 if (mangleSubstitution(QualType(T
, 0)))
4335 mangleTemplatePrefix(T
->getTemplateName());
4337 // FIXME: GCC does not appear to mangle the template arguments when
4338 // the template in question is a dependent template name. Should we
4339 // emulate that badness?
4340 mangleTemplateArgs(T
->getTemplateName(), T
->template_arguments());
4341 addSubstitution(QualType(T
, 0));
4345 void CXXNameMangler::mangleType(const DependentNameType
*T
) {
4346 // Proposal by cxx-abi-dev, 2014-03-26
4347 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
4348 // # dependent elaborated type specifier using
4350 // ::= Ts <name> # dependent elaborated type specifier using
4351 // # 'struct' or 'class'
4352 // ::= Tu <name> # dependent elaborated type specifier using
4354 // ::= Te <name> # dependent elaborated type specifier using
4356 switch (T
->getKeyword()) {
4357 case ElaboratedTypeKeyword::None
:
4358 case ElaboratedTypeKeyword::Typename
:
4360 case ElaboratedTypeKeyword::Struct
:
4361 case ElaboratedTypeKeyword::Class
:
4362 case ElaboratedTypeKeyword::Interface
:
4365 case ElaboratedTypeKeyword::Union
:
4368 case ElaboratedTypeKeyword::Enum
:
4372 // Typename types are always nested
4374 manglePrefix(T
->getQualifier());
4375 mangleSourceName(T
->getIdentifier());
4379 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType
*T
) {
4380 // Dependently-scoped template types are nested if they have a prefix.
4383 // TODO: avoid making this TemplateName.
4384 TemplateName Prefix
=
4385 getASTContext().getDependentTemplateName(T
->getQualifier(),
4386 T
->getIdentifier());
4387 mangleTemplatePrefix(Prefix
);
4389 // FIXME: GCC does not appear to mangle the template arguments when
4390 // the template in question is a dependent template name. Should we
4391 // emulate that badness?
4392 mangleTemplateArgs(Prefix
, T
->template_arguments());
4396 void CXXNameMangler::mangleType(const TypeOfType
*T
) {
4397 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4398 // "extension with parameters" mangling.
4402 void CXXNameMangler::mangleType(const TypeOfExprType
*T
) {
4403 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4404 // "extension with parameters" mangling.
4408 void CXXNameMangler::mangleType(const DecltypeType
*T
) {
4409 Expr
*E
= T
->getUnderlyingExpr();
4411 // type ::= Dt <expression> E # decltype of an id-expression
4412 // # or class member access
4413 // ::= DT <expression> E # decltype of an expression
4415 // This purports to be an exhaustive list of id-expressions and
4416 // class member accesses. Note that we do not ignore parentheses;
4417 // parentheses change the semantics of decltype for these
4418 // expressions (and cause the mangler to use the other form).
4419 if (isa
<DeclRefExpr
>(E
) ||
4420 isa
<MemberExpr
>(E
) ||
4421 isa
<UnresolvedLookupExpr
>(E
) ||
4422 isa
<DependentScopeDeclRefExpr
>(E
) ||
4423 isa
<CXXDependentScopeMemberExpr
>(E
) ||
4424 isa
<UnresolvedMemberExpr
>(E
))
4428 mangleExpression(E
);
4432 void CXXNameMangler::mangleType(const UnaryTransformType
*T
) {
4433 // If this is dependent, we need to record that. If not, we simply
4434 // mangle it as the underlying type since they are equivalent.
4435 if (T
->isDependentType()) {
4436 StringRef BuiltinName
;
4437 switch (T
->getUTTKind()) {
4438 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
4439 case UnaryTransformType::Enum: \
4440 BuiltinName = "__" #Trait; \
4442 #include "clang/Basic/TransformTypeTraits.def"
4444 mangleVendorType(BuiltinName
);
4448 mangleType(T
->getBaseType());
4452 void CXXNameMangler::mangleType(const AutoType
*T
) {
4453 assert(T
->getDeducedType().isNull() &&
4454 "Deduced AutoType shouldn't be handled here!");
4455 assert(T
->getKeyword() != AutoTypeKeyword::GNUAutoType
&&
4456 "shouldn't need to mangle __auto_type!");
4457 // <builtin-type> ::= Da # auto
4458 // ::= Dc # decltype(auto)
4459 // ::= Dk # constrained auto
4460 // ::= DK # constrained decltype(auto)
4461 if (T
->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17
)) {
4462 Out
<< (T
->isDecltypeAuto() ? "DK" : "Dk");
4463 mangleTypeConstraint(T
->getTypeConstraintConcept(),
4464 T
->getTypeConstraintArguments());
4466 Out
<< (T
->isDecltypeAuto() ? "Dc" : "Da");
4470 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType
*T
) {
4471 QualType Deduced
= T
->getDeducedType();
4472 if (!Deduced
.isNull())
4473 return mangleType(Deduced
);
4475 TemplateName TN
= T
->getTemplateName();
4476 assert(TN
.getAsTemplateDecl() &&
4477 "shouldn't form deduced TST unless we know we have a template");
4481 void CXXNameMangler::mangleType(const AtomicType
*T
) {
4482 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4483 // (Until there's a standardized mangling...)
4485 mangleType(T
->getValueType());
4488 void CXXNameMangler::mangleType(const PipeType
*T
) {
4489 // Pipe type mangling rules are described in SPIR 2.0 specification
4490 // A.1 Data types and A.3 Summary of changes
4491 // <type> ::= 8ocl_pipe
4495 void CXXNameMangler::mangleType(const BitIntType
*T
) {
4496 // 5.1.5.2 Builtin types
4497 // <type> ::= DB <number | instantiation-dependent expression> _
4498 // ::= DU <number | instantiation-dependent expression> _
4499 Out
<< "D" << (T
->isUnsigned() ? "U" : "B") << T
->getNumBits() << "_";
4502 void CXXNameMangler::mangleType(const DependentBitIntType
*T
) {
4503 // 5.1.5.2 Builtin types
4504 // <type> ::= DB <number | instantiation-dependent expression> _
4505 // ::= DU <number | instantiation-dependent expression> _
4506 Out
<< "D" << (T
->isUnsigned() ? "U" : "B");
4507 mangleExpression(T
->getNumBitsExpr());
4511 void CXXNameMangler::mangleType(const ArrayParameterType
*T
) {
4512 mangleType(cast
<ConstantArrayType
>(T
));
4515 void CXXNameMangler::mangleType(const HLSLAttributedResourceType
*T
) {
4516 llvm::SmallString
<64> Str("_Res");
4517 const HLSLAttributedResourceType::Attributes
&Attrs
= T
->getAttrs();
4518 // map resource class to HLSL virtual register letter
4519 switch (Attrs
.ResourceClass
) {
4520 case llvm::dxil::ResourceClass::UAV
:
4523 case llvm::dxil::ResourceClass::SRV
:
4526 case llvm::dxil::ResourceClass::CBuffer
:
4529 case llvm::dxil::ResourceClass::Sampler
:
4535 if (Attrs
.RawBuffer
)
4537 if (T
->hasContainedType())
4539 mangleVendorQualifier(Str
);
4541 if (T
->hasContainedType()) {
4542 mangleType(T
->getContainedType());
4544 mangleType(T
->getWrappedType());
4547 void CXXNameMangler::mangleIntegerLiteral(QualType T
,
4548 const llvm::APSInt
&Value
) {
4549 // <expr-primary> ::= L <type> <value number> E # integer literal
4553 if (T
->isBooleanType()) {
4554 // Boolean values are encoded as 0/1.
4555 Out
<< (Value
.getBoolValue() ? '1' : '0');
4557 mangleNumber(Value
);
4563 void CXXNameMangler::mangleMemberExprBase(const Expr
*Base
, bool IsArrow
) {
4564 // Ignore member expressions involving anonymous unions.
4565 while (const auto *RT
= Base
->getType()->getAs
<RecordType
>()) {
4566 if (!RT
->getDecl()->isAnonymousStructOrUnion())
4568 const auto *ME
= dyn_cast
<MemberExpr
>(Base
);
4571 Base
= ME
->getBase();
4572 IsArrow
= ME
->isArrow();
4575 if (Base
->isImplicitCXXThis()) {
4576 // Note: GCC mangles member expressions to the implicit 'this' as
4577 // *this., whereas we represent them as this->. The Itanium C++ ABI
4578 // does not specify anything here, so we follow GCC.
4581 Out
<< (IsArrow
? "pt" : "dt");
4582 mangleExpression(Base
);
4586 /// Mangles a member expression.
4587 void CXXNameMangler::mangleMemberExpr(const Expr
*base
,
4589 NestedNameSpecifier
*qualifier
,
4590 NamedDecl
*firstQualifierLookup
,
4591 DeclarationName member
,
4592 const TemplateArgumentLoc
*TemplateArgs
,
4593 unsigned NumTemplateArgs
,
4595 // <expression> ::= dt <expression> <unresolved-name>
4596 // ::= pt <expression> <unresolved-name>
4598 mangleMemberExprBase(base
, isArrow
);
4599 mangleUnresolvedName(qualifier
, member
, TemplateArgs
, NumTemplateArgs
, arity
);
4602 /// Look at the callee of the given call expression and determine if
4603 /// it's a parenthesized id-expression which would have triggered ADL
4605 static bool isParenthesizedADLCallee(const CallExpr
*call
) {
4606 const Expr
*callee
= call
->getCallee();
4607 const Expr
*fn
= callee
->IgnoreParens();
4609 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4610 // too, but for those to appear in the callee, it would have to be
4612 if (callee
== fn
) return false;
4614 // Must be an unresolved lookup.
4615 const UnresolvedLookupExpr
*lookup
= dyn_cast
<UnresolvedLookupExpr
>(fn
);
4616 if (!lookup
) return false;
4618 assert(!lookup
->requiresADL());
4620 // Must be an unqualified lookup.
4621 if (lookup
->getQualifier()) return false;
4623 // Must not have found a class member. Note that if one is a class
4624 // member, they're all class members.
4625 if (lookup
->getNumDecls() > 0 &&
4626 (*lookup
->decls_begin())->isCXXClassMember())
4629 // Otherwise, ADL would have been triggered.
4633 void CXXNameMangler::mangleCastExpression(const Expr
*E
, StringRef CastEncoding
) {
4634 const ExplicitCastExpr
*ECE
= cast
<ExplicitCastExpr
>(E
);
4635 Out
<< CastEncoding
;
4636 mangleType(ECE
->getType());
4637 mangleExpression(ECE
->getSubExpr());
4640 void CXXNameMangler::mangleInitListElements(const InitListExpr
*InitList
) {
4641 if (auto *Syntactic
= InitList
->getSyntacticForm())
4642 InitList
= Syntactic
;
4643 for (unsigned i
= 0, e
= InitList
->getNumInits(); i
!= e
; ++i
)
4644 mangleExpression(InitList
->getInit(i
));
4647 void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc
,
4648 const concepts::Requirement
*Req
) {
4649 using concepts::Requirement
;
4651 // TODO: We can't mangle the result of a failed substitution. It's not clear
4652 // whether we should be mangling the original form prior to any substitution
4653 // instead. See https://lists.isocpp.org/core/2023/04/14118.php
4654 auto HandleSubstitutionFailure
=
4655 [&](SourceLocation Loc
) {
4656 DiagnosticsEngine
&Diags
= Context
.getDiags();
4657 unsigned DiagID
= Diags
.getCustomDiagID(
4658 DiagnosticsEngine::Error
, "cannot mangle this requires-expression "
4659 "containing a substitution failure");
4660 Diags
.Report(Loc
, DiagID
);
4664 switch (Req
->getKind()) {
4665 case Requirement::RK_Type
: {
4666 const auto *TR
= cast
<concepts::TypeRequirement
>(Req
);
4667 if (TR
->isSubstitutionFailure())
4668 return HandleSubstitutionFailure(
4669 TR
->getSubstitutionDiagnostic()->DiagLoc
);
4672 mangleType(TR
->getType()->getType());
4676 case Requirement::RK_Simple
:
4677 case Requirement::RK_Compound
: {
4678 const auto *ER
= cast
<concepts::ExprRequirement
>(Req
);
4679 if (ER
->isExprSubstitutionFailure())
4680 return HandleSubstitutionFailure(
4681 ER
->getExprSubstitutionDiagnostic()->DiagLoc
);
4684 mangleExpression(ER
->getExpr());
4686 if (ER
->hasNoexceptRequirement())
4689 if (!ER
->getReturnTypeRequirement().isEmpty()) {
4690 if (ER
->getReturnTypeRequirement().isSubstitutionFailure())
4691 return HandleSubstitutionFailure(ER
->getReturnTypeRequirement()
4692 .getSubstitutionDiagnostic()
4696 mangleTypeConstraint(ER
->getReturnTypeRequirement().getTypeConstraint());
4701 case Requirement::RK_Nested
:
4702 const auto *NR
= cast
<concepts::NestedRequirement
>(Req
);
4703 if (NR
->hasInvalidConstraint()) {
4704 // FIXME: NestedRequirement should track the location of its requires
4706 return HandleSubstitutionFailure(RequiresExprLoc
);
4710 mangleExpression(NR
->getConstraintExpr());
4715 void CXXNameMangler::mangleExpression(const Expr
*E
, unsigned Arity
,
4716 bool AsTemplateArg
) {
4717 // <expression> ::= <unary operator-name> <expression>
4718 // ::= <binary operator-name> <expression> <expression>
4719 // ::= <trinary operator-name> <expression> <expression> <expression>
4720 // ::= cv <type> expression # conversion with one argument
4721 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4722 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
4723 // ::= sc <type> <expression> # static_cast<type> (expression)
4724 // ::= cc <type> <expression> # const_cast<type> (expression)
4725 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4726 // ::= st <type> # sizeof (a type)
4727 // ::= at <type> # alignof (a type)
4728 // ::= <template-param>
4729 // ::= <function-param>
4730 // ::= fpT # 'this' expression (part of <function-param>)
4731 // ::= sr <type> <unqualified-name> # dependent name
4732 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
4733 // ::= ds <expression> <expression> # expr.*expr
4734 // ::= sZ <template-param> # size of a parameter pack
4735 // ::= sZ <function-param> # size of a function parameter pack
4736 // ::= u <source-name> <template-arg>* E # vendor extended expression
4737 // ::= <expr-primary>
4738 // <expr-primary> ::= L <type> <value number> E # integer literal
4739 // ::= L <type> <value float> E # floating literal
4740 // ::= L <type> <string type> E # string literal
4741 // ::= L <nullptr type> E # nullptr literal "LDnE"
4742 // ::= L <pointer type> 0 E # null pointer template argument
4743 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
4744 // ::= L <mangled-name> E # external name
4745 QualType ImplicitlyConvertedToType
;
4747 // A top-level expression that's not <expr-primary> needs to be wrapped in
4748 // X...E in a template arg.
4749 bool IsPrimaryExpr
= true;
4750 auto NotPrimaryExpr
= [&] {
4751 if (AsTemplateArg
&& IsPrimaryExpr
)
4753 IsPrimaryExpr
= false;
4756 auto MangleDeclRefExpr
= [&](const NamedDecl
*D
) {
4757 switch (D
->getKind()) {
4759 // <expr-primary> ::= L <mangled-name> E # external name
4767 mangleFunctionParam(cast
<ParmVarDecl
>(D
));
4770 case Decl::EnumConstant
: {
4772 const EnumConstantDecl
*ED
= cast
<EnumConstantDecl
>(D
);
4773 mangleIntegerLiteral(ED
->getType(), ED
->getInitVal());
4777 case Decl::NonTypeTemplateParm
:
4779 const NonTypeTemplateParmDecl
*PD
= cast
<NonTypeTemplateParmDecl
>(D
);
4780 mangleTemplateParameter(PD
->getDepth(), PD
->getIndex());
4785 // 'goto recurse' is used when handling a simple "unwrapping" node which
4786 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4789 switch (E
->getStmtClass()) {
4790 case Expr::NoStmtClass
:
4791 #define ABSTRACT_STMT(Type)
4792 #define EXPR(Type, Base)
4793 #define STMT(Type, Base) \
4794 case Expr::Type##Class:
4795 #include "clang/AST/StmtNodes.inc"
4798 // These all can only appear in local or variable-initialization
4799 // contexts and so should never appear in a mangling.
4800 case Expr::AddrLabelExprClass
:
4801 case Expr::DesignatedInitUpdateExprClass
:
4802 case Expr::ImplicitValueInitExprClass
:
4803 case Expr::ArrayInitLoopExprClass
:
4804 case Expr::ArrayInitIndexExprClass
:
4805 case Expr::NoInitExprClass
:
4806 case Expr::ParenListExprClass
:
4807 case Expr::MSPropertyRefExprClass
:
4808 case Expr::MSPropertySubscriptExprClass
:
4809 case Expr::TypoExprClass
: // This should no longer exist in the AST by now.
4810 case Expr::RecoveryExprClass
:
4811 case Expr::ArraySectionExprClass
:
4812 case Expr::OMPArrayShapingExprClass
:
4813 case Expr::OMPIteratorExprClass
:
4814 case Expr::CXXInheritedCtorInitExprClass
:
4815 case Expr::CXXParenListInitExprClass
:
4816 case Expr::PackIndexingExprClass
:
4817 llvm_unreachable("unexpected statement kind");
4819 case Expr::ConstantExprClass
:
4820 E
= cast
<ConstantExpr
>(E
)->getSubExpr();
4823 // FIXME: invent manglings for all these.
4824 case Expr::BlockExprClass
:
4825 case Expr::ChooseExprClass
:
4826 case Expr::CompoundLiteralExprClass
:
4827 case Expr::ExtVectorElementExprClass
:
4828 case Expr::GenericSelectionExprClass
:
4829 case Expr::ObjCEncodeExprClass
:
4830 case Expr::ObjCIsaExprClass
:
4831 case Expr::ObjCIvarRefExprClass
:
4832 case Expr::ObjCMessageExprClass
:
4833 case Expr::ObjCPropertyRefExprClass
:
4834 case Expr::ObjCProtocolExprClass
:
4835 case Expr::ObjCSelectorExprClass
:
4836 case Expr::ObjCStringLiteralClass
:
4837 case Expr::ObjCBoxedExprClass
:
4838 case Expr::ObjCArrayLiteralClass
:
4839 case Expr::ObjCDictionaryLiteralClass
:
4840 case Expr::ObjCSubscriptRefExprClass
:
4841 case Expr::ObjCIndirectCopyRestoreExprClass
:
4842 case Expr::ObjCAvailabilityCheckExprClass
:
4843 case Expr::OffsetOfExprClass
:
4844 case Expr::PredefinedExprClass
:
4845 case Expr::ShuffleVectorExprClass
:
4846 case Expr::ConvertVectorExprClass
:
4847 case Expr::StmtExprClass
:
4848 case Expr::ArrayTypeTraitExprClass
:
4849 case Expr::ExpressionTraitExprClass
:
4850 case Expr::VAArgExprClass
:
4851 case Expr::CUDAKernelCallExprClass
:
4852 case Expr::AsTypeExprClass
:
4853 case Expr::PseudoObjectExprClass
:
4854 case Expr::AtomicExprClass
:
4855 case Expr::SourceLocExprClass
:
4856 case Expr::EmbedExprClass
:
4857 case Expr::BuiltinBitCastExprClass
:
4861 // As bad as this diagnostic is, it's better than crashing.
4862 DiagnosticsEngine
&Diags
= Context
.getDiags();
4863 unsigned DiagID
= Diags
.getCustomDiagID(DiagnosticsEngine::Error
,
4864 "cannot yet mangle expression type %0");
4865 Diags
.Report(E
->getExprLoc(), DiagID
)
4866 << E
->getStmtClassName() << E
->getSourceRange();
4872 case Expr::CXXUuidofExprClass
: {
4874 const CXXUuidofExpr
*UE
= cast
<CXXUuidofExpr
>(E
);
4875 // As of clang 12, uuidof uses the vendor extended expression
4876 // mangling. Previously, it used a special-cased nonstandard extension.
4877 if (!isCompatibleWith(LangOptions::ClangABI::Ver11
)) {
4878 Out
<< "u8__uuidof";
4879 if (UE
->isTypeOperand())
4880 mangleType(UE
->getTypeOperand(Context
.getASTContext()));
4882 mangleTemplateArgExpr(UE
->getExprOperand());
4885 if (UE
->isTypeOperand()) {
4886 QualType UuidT
= UE
->getTypeOperand(Context
.getASTContext());
4887 Out
<< "u8__uuidoft";
4890 Expr
*UuidExp
= UE
->getExprOperand();
4891 Out
<< "u8__uuidofz";
4892 mangleExpression(UuidExp
);
4898 // Even gcc-4.5 doesn't mangle this.
4899 case Expr::BinaryConditionalOperatorClass
: {
4901 DiagnosticsEngine
&Diags
= Context
.getDiags();
4903 Diags
.getCustomDiagID(DiagnosticsEngine::Error
,
4904 "?: operator with omitted middle operand cannot be mangled");
4905 Diags
.Report(E
->getExprLoc(), DiagID
)
4906 << E
->getStmtClassName() << E
->getSourceRange();
4910 // These are used for internal purposes and cannot be meaningfully mangled.
4911 case Expr::OpaqueValueExprClass
:
4912 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
4914 case Expr::InitListExprClass
: {
4917 mangleInitListElements(cast
<InitListExpr
>(E
));
4922 case Expr::DesignatedInitExprClass
: {
4924 auto *DIE
= cast
<DesignatedInitExpr
>(E
);
4925 for (const auto &Designator
: DIE
->designators()) {
4926 if (Designator
.isFieldDesignator()) {
4928 mangleSourceName(Designator
.getFieldName());
4929 } else if (Designator
.isArrayDesignator()) {
4931 mangleExpression(DIE
->getArrayIndex(Designator
));
4933 assert(Designator
.isArrayRangeDesignator() &&
4934 "unknown designator kind");
4936 mangleExpression(DIE
->getArrayRangeStart(Designator
));
4937 mangleExpression(DIE
->getArrayRangeEnd(Designator
));
4940 mangleExpression(DIE
->getInit());
4944 case Expr::CXXDefaultArgExprClass
:
4945 E
= cast
<CXXDefaultArgExpr
>(E
)->getExpr();
4948 case Expr::CXXDefaultInitExprClass
:
4949 E
= cast
<CXXDefaultInitExpr
>(E
)->getExpr();
4952 case Expr::CXXStdInitializerListExprClass
:
4953 E
= cast
<CXXStdInitializerListExpr
>(E
)->getSubExpr();
4956 case Expr::SubstNonTypeTemplateParmExprClass
: {
4957 // Mangle a substituted parameter the same way we mangle the template
4959 auto *SNTTPE
= cast
<SubstNonTypeTemplateParmExpr
>(E
);
4960 if (auto *CE
= dyn_cast
<ConstantExpr
>(SNTTPE
->getReplacement())) {
4961 // Pull out the constant value and mangle it as a template argument.
4962 QualType ParamType
= SNTTPE
->getParameterType(Context
.getASTContext());
4963 assert(CE
->hasAPValueResult() && "expected the NTTP to have an APValue");
4964 mangleValueInTemplateArg(ParamType
, CE
->getAPValueResult(), false,
4965 /*NeedExactType=*/true);
4968 // The remaining cases all happen to be substituted with expressions that
4969 // mangle the same as a corresponding template argument anyway.
4970 E
= cast
<SubstNonTypeTemplateParmExpr
>(E
)->getReplacement();
4974 case Expr::UserDefinedLiteralClass
:
4975 // We follow g++'s approach of mangling a UDL as a call to the literal
4977 case Expr::CXXMemberCallExprClass
: // fallthrough
4978 case Expr::CallExprClass
: {
4980 const CallExpr
*CE
= cast
<CallExpr
>(E
);
4982 // <expression> ::= cp <simple-id> <expression>* E
4983 // We use this mangling only when the call would use ADL except
4984 // for being parenthesized. Per discussion with David
4985 // Vandervoorde, 2011.04.25.
4986 if (isParenthesizedADLCallee(CE
)) {
4988 // The callee here is a parenthesized UnresolvedLookupExpr with
4989 // no qualifier and should always get mangled as a <simple-id>
4992 // <expression> ::= cl <expression>* E
4997 unsigned CallArity
= CE
->getNumArgs();
4998 for (const Expr
*Arg
: CE
->arguments())
4999 if (isa
<PackExpansionExpr
>(Arg
))
5000 CallArity
= UnknownArity
;
5002 mangleExpression(CE
->getCallee(), CallArity
);
5003 for (const Expr
*Arg
: CE
->arguments())
5004 mangleExpression(Arg
);
5009 case Expr::CXXNewExprClass
: {
5011 const CXXNewExpr
*New
= cast
<CXXNewExpr
>(E
);
5012 if (New
->isGlobalNew()) Out
<< "gs";
5013 Out
<< (New
->isArray() ? "na" : "nw");
5014 for (CXXNewExpr::const_arg_iterator I
= New
->placement_arg_begin(),
5015 E
= New
->placement_arg_end(); I
!= E
; ++I
)
5016 mangleExpression(*I
);
5018 mangleType(New
->getAllocatedType());
5019 if (New
->hasInitializer()) {
5020 if (New
->getInitializationStyle() == CXXNewInitializationStyle::Braces
)
5024 const Expr
*Init
= New
->getInitializer();
5025 if (const CXXConstructExpr
*CCE
= dyn_cast
<CXXConstructExpr
>(Init
)) {
5026 // Directly inline the initializers.
5027 for (CXXConstructExpr::const_arg_iterator I
= CCE
->arg_begin(),
5030 mangleExpression(*I
);
5031 } else if (const ParenListExpr
*PLE
= dyn_cast
<ParenListExpr
>(Init
)) {
5032 for (unsigned i
= 0, e
= PLE
->getNumExprs(); i
!= e
; ++i
)
5033 mangleExpression(PLE
->getExpr(i
));
5034 } else if (New
->getInitializationStyle() ==
5035 CXXNewInitializationStyle::Braces
&&
5036 isa
<InitListExpr
>(Init
)) {
5037 // Only take InitListExprs apart for list-initialization.
5038 mangleInitListElements(cast
<InitListExpr
>(Init
));
5040 mangleExpression(Init
);
5046 case Expr::CXXPseudoDestructorExprClass
: {
5048 const auto *PDE
= cast
<CXXPseudoDestructorExpr
>(E
);
5049 if (const Expr
*Base
= PDE
->getBase())
5050 mangleMemberExprBase(Base
, PDE
->isArrow());
5051 NestedNameSpecifier
*Qualifier
= PDE
->getQualifier();
5052 if (TypeSourceInfo
*ScopeInfo
= PDE
->getScopeTypeInfo()) {
5054 mangleUnresolvedPrefix(Qualifier
,
5055 /*recursive=*/true);
5056 mangleUnresolvedTypeOrSimpleId(ScopeInfo
->getType());
5060 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo
->getType()))
5063 } else if (Qualifier
) {
5064 mangleUnresolvedPrefix(Qualifier
);
5066 // <base-unresolved-name> ::= dn <destructor-name>
5068 QualType DestroyedType
= PDE
->getDestroyedType();
5069 mangleUnresolvedTypeOrSimpleId(DestroyedType
);
5073 case Expr::MemberExprClass
: {
5075 const MemberExpr
*ME
= cast
<MemberExpr
>(E
);
5076 mangleMemberExpr(ME
->getBase(), ME
->isArrow(),
5077 ME
->getQualifier(), nullptr,
5078 ME
->getMemberDecl()->getDeclName(),
5079 ME
->getTemplateArgs(), ME
->getNumTemplateArgs(),
5084 case Expr::UnresolvedMemberExprClass
: {
5086 const UnresolvedMemberExpr
*ME
= cast
<UnresolvedMemberExpr
>(E
);
5087 mangleMemberExpr(ME
->isImplicitAccess() ? nullptr : ME
->getBase(),
5088 ME
->isArrow(), ME
->getQualifier(), nullptr,
5089 ME
->getMemberName(),
5090 ME
->getTemplateArgs(), ME
->getNumTemplateArgs(),
5095 case Expr::CXXDependentScopeMemberExprClass
: {
5097 const CXXDependentScopeMemberExpr
*ME
5098 = cast
<CXXDependentScopeMemberExpr
>(E
);
5099 mangleMemberExpr(ME
->isImplicitAccess() ? nullptr : ME
->getBase(),
5100 ME
->isArrow(), ME
->getQualifier(),
5101 ME
->getFirstQualifierFoundInScope(),
5103 ME
->getTemplateArgs(), ME
->getNumTemplateArgs(),
5108 case Expr::UnresolvedLookupExprClass
: {
5110 const UnresolvedLookupExpr
*ULE
= cast
<UnresolvedLookupExpr
>(E
);
5111 mangleUnresolvedName(ULE
->getQualifier(), ULE
->getName(),
5112 ULE
->getTemplateArgs(), ULE
->getNumTemplateArgs(),
5117 case Expr::CXXUnresolvedConstructExprClass
: {
5119 const CXXUnresolvedConstructExpr
*CE
= cast
<CXXUnresolvedConstructExpr
>(E
);
5120 unsigned N
= CE
->getNumArgs();
5122 if (CE
->isListInitialization()) {
5123 assert(N
== 1 && "unexpected form for list initialization");
5124 auto *IL
= cast
<InitListExpr
>(CE
->getArg(0));
5126 mangleType(CE
->getType());
5127 mangleInitListElements(IL
);
5133 mangleType(CE
->getType());
5134 if (N
!= 1) Out
<< '_';
5135 for (unsigned I
= 0; I
!= N
; ++I
) mangleExpression(CE
->getArg(I
));
5136 if (N
!= 1) Out
<< 'E';
5140 case Expr::CXXConstructExprClass
: {
5141 // An implicit cast is silent, thus may contain <expr-primary>.
5142 const auto *CE
= cast
<CXXConstructExpr
>(E
);
5143 if (!CE
->isListInitialization() || CE
->isStdInitListInitialization()) {
5145 CE
->getNumArgs() >= 1 &&
5146 (CE
->getNumArgs() == 1 || isa
<CXXDefaultArgExpr
>(CE
->getArg(1))) &&
5147 "implicit CXXConstructExpr must have one argument");
5148 E
= cast
<CXXConstructExpr
>(E
)->getArg(0);
5153 for (auto *E
: CE
->arguments())
5154 mangleExpression(E
);
5159 case Expr::CXXTemporaryObjectExprClass
: {
5161 const auto *CE
= cast
<CXXTemporaryObjectExpr
>(E
);
5162 unsigned N
= CE
->getNumArgs();
5163 bool List
= CE
->isListInitialization();
5169 mangleType(CE
->getType());
5170 if (!List
&& N
!= 1)
5172 if (CE
->isStdInitListInitialization()) {
5173 // We implicitly created a std::initializer_list<T> for the first argument
5174 // of a constructor of type U in an expression of the form U{a, b, c}.
5175 // Strip all the semantic gunk off the initializer list.
5177 cast
<CXXStdInitializerListExpr
>(CE
->getArg(0)->IgnoreImplicit());
5178 auto *ILE
= cast
<InitListExpr
>(SILE
->getSubExpr()->IgnoreImplicit());
5179 mangleInitListElements(ILE
);
5181 for (auto *E
: CE
->arguments())
5182 mangleExpression(E
);
5189 case Expr::CXXScalarValueInitExprClass
:
5192 mangleType(E
->getType());
5196 case Expr::CXXNoexceptExprClass
:
5199 mangleExpression(cast
<CXXNoexceptExpr
>(E
)->getOperand());
5202 case Expr::UnaryExprOrTypeTraitExprClass
: {
5203 // Non-instantiation-dependent traits are an <expr-primary> integer literal.
5204 const UnaryExprOrTypeTraitExpr
*SAE
= cast
<UnaryExprOrTypeTraitExpr
>(E
);
5206 if (!SAE
->isInstantiationDependent()) {
5208 // If the operand of a sizeof or alignof operator is not
5209 // instantiation-dependent it is encoded as an integer literal
5210 // reflecting the result of the operator.
5212 // If the result of the operator is implicitly converted to a known
5213 // integer type, that type is used for the literal; otherwise, the type
5214 // of std::size_t or std::ptrdiff_t is used.
5216 // FIXME: We still include the operand in the profile in this case. This
5217 // can lead to mangling collisions between function templates that we
5218 // consider to be different.
5219 QualType T
= (ImplicitlyConvertedToType
.isNull() ||
5220 !ImplicitlyConvertedToType
->isIntegerType())? SAE
->getType()
5221 : ImplicitlyConvertedToType
;
5222 llvm::APSInt V
= SAE
->EvaluateKnownConstInt(Context
.getASTContext());
5223 mangleIntegerLiteral(T
, V
);
5227 NotPrimaryExpr(); // But otherwise, they are not.
5229 auto MangleAlignofSizeofArg
= [&] {
5230 if (SAE
->isArgumentType()) {
5232 mangleType(SAE
->getArgumentType());
5235 mangleExpression(SAE
->getArgumentExpr());
5239 switch(SAE
->getKind()) {
5242 MangleAlignofSizeofArg();
5244 case UETT_PreferredAlignOf
:
5245 // As of clang 12, we mangle __alignof__ differently than alignof. (They
5246 // have acted differently since Clang 8, but were previously mangled the
5248 if (!isCompatibleWith(LangOptions::ClangABI::Ver11
)) {
5249 Out
<< "u11__alignof__";
5250 if (SAE
->isArgumentType())
5251 mangleType(SAE
->getArgumentType());
5253 mangleTemplateArgExpr(SAE
->getArgumentExpr());
5260 MangleAlignofSizeofArg();
5262 case UETT_DataSizeOf
: {
5263 DiagnosticsEngine
&Diags
= Context
.getDiags();
5265 Diags
.getCustomDiagID(DiagnosticsEngine::Error
,
5266 "cannot yet mangle __datasizeof expression");
5267 Diags
.Report(DiagID
);
5270 case UETT_PtrAuthTypeDiscriminator
: {
5271 DiagnosticsEngine
&Diags
= Context
.getDiags();
5272 unsigned DiagID
= Diags
.getCustomDiagID(
5273 DiagnosticsEngine::Error
,
5274 "cannot yet mangle __builtin_ptrauth_type_discriminator expression");
5275 Diags
.Report(E
->getExprLoc(), DiagID
);
5278 case UETT_VecStep
: {
5279 DiagnosticsEngine
&Diags
= Context
.getDiags();
5280 unsigned DiagID
= Diags
.getCustomDiagID(DiagnosticsEngine::Error
,
5281 "cannot yet mangle vec_step expression");
5282 Diags
.Report(DiagID
);
5285 case UETT_OpenMPRequiredSimdAlign
: {
5286 DiagnosticsEngine
&Diags
= Context
.getDiags();
5287 unsigned DiagID
= Diags
.getCustomDiagID(
5288 DiagnosticsEngine::Error
,
5289 "cannot yet mangle __builtin_omp_required_simd_align expression");
5290 Diags
.Report(DiagID
);
5293 case UETT_VectorElements
: {
5294 DiagnosticsEngine
&Diags
= Context
.getDiags();
5295 unsigned DiagID
= Diags
.getCustomDiagID(
5296 DiagnosticsEngine::Error
,
5297 "cannot yet mangle __builtin_vectorelements expression");
5298 Diags
.Report(DiagID
);
5305 case Expr::TypeTraitExprClass
: {
5306 // <expression> ::= u <source-name> <template-arg>* E # vendor extension
5307 const TypeTraitExpr
*TTE
= cast
<TypeTraitExpr
>(E
);
5309 llvm::StringRef Spelling
= getTraitSpelling(TTE
->getTrait());
5310 mangleVendorType(Spelling
);
5311 for (TypeSourceInfo
*TSI
: TTE
->getArgs()) {
5312 mangleType(TSI
->getType());
5318 case Expr::CXXThrowExprClass
: {
5320 const CXXThrowExpr
*TE
= cast
<CXXThrowExpr
>(E
);
5321 // <expression> ::= tw <expression> # throw expression
5323 if (TE
->getSubExpr()) {
5325 mangleExpression(TE
->getSubExpr());
5332 case Expr::CXXTypeidExprClass
: {
5334 const CXXTypeidExpr
*TIE
= cast
<CXXTypeidExpr
>(E
);
5335 // <expression> ::= ti <type> # typeid (type)
5336 // ::= te <expression> # typeid (expression)
5337 if (TIE
->isTypeOperand()) {
5339 mangleType(TIE
->getTypeOperand(Context
.getASTContext()));
5342 mangleExpression(TIE
->getExprOperand());
5347 case Expr::CXXDeleteExprClass
: {
5349 const CXXDeleteExpr
*DE
= cast
<CXXDeleteExpr
>(E
);
5350 // <expression> ::= [gs] dl <expression> # [::] delete expr
5351 // ::= [gs] da <expression> # [::] delete [] expr
5352 if (DE
->isGlobalDelete()) Out
<< "gs";
5353 Out
<< (DE
->isArrayForm() ? "da" : "dl");
5354 mangleExpression(DE
->getArgument());
5358 case Expr::UnaryOperatorClass
: {
5360 const UnaryOperator
*UO
= cast
<UnaryOperator
>(E
);
5361 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO
->getOpcode()),
5363 mangleExpression(UO
->getSubExpr());
5367 case Expr::ArraySubscriptExprClass
: {
5369 const ArraySubscriptExpr
*AE
= cast
<ArraySubscriptExpr
>(E
);
5371 // Array subscript is treated as a syntactically weird form of
5374 mangleExpression(AE
->getLHS());
5375 mangleExpression(AE
->getRHS());
5379 case Expr::MatrixSubscriptExprClass
: {
5381 const MatrixSubscriptExpr
*ME
= cast
<MatrixSubscriptExpr
>(E
);
5383 mangleExpression(ME
->getBase());
5384 mangleExpression(ME
->getRowIdx());
5385 mangleExpression(ME
->getColumnIdx());
5389 case Expr::CompoundAssignOperatorClass
: // fallthrough
5390 case Expr::BinaryOperatorClass
: {
5392 const BinaryOperator
*BO
= cast
<BinaryOperator
>(E
);
5393 if (BO
->getOpcode() == BO_PtrMemD
)
5396 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO
->getOpcode()),
5398 mangleExpression(BO
->getLHS());
5399 mangleExpression(BO
->getRHS());
5403 case Expr::CXXRewrittenBinaryOperatorClass
: {
5405 // The mangled form represents the original syntax.
5406 CXXRewrittenBinaryOperator::DecomposedForm Decomposed
=
5407 cast
<CXXRewrittenBinaryOperator
>(E
)->getDecomposedForm();
5408 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed
.Opcode
),
5410 mangleExpression(Decomposed
.LHS
);
5411 mangleExpression(Decomposed
.RHS
);
5415 case Expr::ConditionalOperatorClass
: {
5417 const ConditionalOperator
*CO
= cast
<ConditionalOperator
>(E
);
5418 mangleOperatorName(OO_Conditional
, /*Arity=*/3);
5419 mangleExpression(CO
->getCond());
5420 mangleExpression(CO
->getLHS(), Arity
);
5421 mangleExpression(CO
->getRHS(), Arity
);
5425 case Expr::ImplicitCastExprClass
: {
5426 ImplicitlyConvertedToType
= E
->getType();
5427 E
= cast
<ImplicitCastExpr
>(E
)->getSubExpr();
5431 case Expr::ObjCBridgedCastExprClass
: {
5433 // Mangle ownership casts as a vendor extended operator __bridge,
5434 // __bridge_transfer, or __bridge_retain.
5435 StringRef Kind
= cast
<ObjCBridgedCastExpr
>(E
)->getBridgeKindName();
5436 Out
<< "v1U" << Kind
.size() << Kind
;
5437 mangleCastExpression(E
, "cv");
5441 case Expr::CStyleCastExprClass
:
5443 mangleCastExpression(E
, "cv");
5446 case Expr::CXXFunctionalCastExprClass
: {
5448 auto *Sub
= cast
<ExplicitCastExpr
>(E
)->getSubExpr()->IgnoreImplicit();
5449 // FIXME: Add isImplicit to CXXConstructExpr.
5450 if (auto *CCE
= dyn_cast
<CXXConstructExpr
>(Sub
))
5451 if (CCE
->getParenOrBraceRange().isInvalid())
5452 Sub
= CCE
->getArg(0)->IgnoreImplicit();
5453 if (auto *StdInitList
= dyn_cast
<CXXStdInitializerListExpr
>(Sub
))
5454 Sub
= StdInitList
->getSubExpr()->IgnoreImplicit();
5455 if (auto *IL
= dyn_cast
<InitListExpr
>(Sub
)) {
5457 mangleType(E
->getType());
5458 mangleInitListElements(IL
);
5461 mangleCastExpression(E
, "cv");
5466 case Expr::CXXStaticCastExprClass
:
5468 mangleCastExpression(E
, "sc");
5470 case Expr::CXXDynamicCastExprClass
:
5472 mangleCastExpression(E
, "dc");
5474 case Expr::CXXReinterpretCastExprClass
:
5476 mangleCastExpression(E
, "rc");
5478 case Expr::CXXConstCastExprClass
:
5480 mangleCastExpression(E
, "cc");
5482 case Expr::CXXAddrspaceCastExprClass
:
5484 mangleCastExpression(E
, "ac");
5487 case Expr::CXXOperatorCallExprClass
: {
5489 const CXXOperatorCallExpr
*CE
= cast
<CXXOperatorCallExpr
>(E
);
5490 unsigned NumArgs
= CE
->getNumArgs();
5491 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
5492 // (the enclosing MemberExpr covers the syntactic portion).
5493 if (CE
->getOperator() != OO_Arrow
)
5494 mangleOperatorName(CE
->getOperator(), /*Arity=*/NumArgs
);
5495 // Mangle the arguments.
5496 for (unsigned i
= 0; i
!= NumArgs
; ++i
)
5497 mangleExpression(CE
->getArg(i
));
5501 case Expr::ParenExprClass
:
5502 E
= cast
<ParenExpr
>(E
)->getSubExpr();
5505 case Expr::ConceptSpecializationExprClass
: {
5506 auto *CSE
= cast
<ConceptSpecializationExpr
>(E
);
5507 if (isCompatibleWith(LangOptions::ClangABI::Ver17
)) {
5508 // Clang 17 and before mangled concept-ids as if they resolved to an
5509 // entity, meaning that references to enclosing template arguments don't
5512 mangleTemplateName(CSE
->getNamedConcept(), CSE
->getTemplateArguments());
5516 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5518 mangleUnresolvedName(
5519 CSE
->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
5520 CSE
->getConceptNameInfo().getName(),
5521 CSE
->getTemplateArgsAsWritten()->getTemplateArgs(),
5522 CSE
->getTemplateArgsAsWritten()->getNumTemplateArgs());
5526 case Expr::RequiresExprClass
: {
5527 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5528 auto *RE
= cast
<RequiresExpr
>(E
);
5529 // This is a primary-expression in the C++ grammar, but does not have an
5530 // <expr-primary> mangling (starting with 'L').
5532 if (RE
->getLParenLoc().isValid()) {
5534 FunctionTypeDepthState saved
= FunctionTypeDepth
.push();
5535 if (RE
->getLocalParameters().empty()) {
5538 for (ParmVarDecl
*Param
: RE
->getLocalParameters()) {
5539 mangleType(Context
.getASTContext().getSignatureParameterType(
5545 // The rest of the mangling is in the immediate scope of the parameters.
5546 FunctionTypeDepth
.enterResultType();
5547 for (const concepts::Requirement
*Req
: RE
->getRequirements())
5548 mangleRequirement(RE
->getExprLoc(), Req
);
5549 FunctionTypeDepth
.pop(saved
);
5553 for (const concepts::Requirement
*Req
: RE
->getRequirements())
5554 mangleRequirement(RE
->getExprLoc(), Req
);
5560 case Expr::DeclRefExprClass
:
5561 // MangleDeclRefExpr helper handles primary-vs-nonprimary
5562 MangleDeclRefExpr(cast
<DeclRefExpr
>(E
)->getDecl());
5565 case Expr::SubstNonTypeTemplateParmPackExprClass
:
5567 // FIXME: not clear how to mangle this!
5568 // template <unsigned N...> class A {
5569 // template <class U...> void foo(U (&x)[N]...);
5571 Out
<< "_SUBSTPACK_";
5574 case Expr::FunctionParmPackExprClass
: {
5576 // FIXME: not clear how to mangle this!
5577 const FunctionParmPackExpr
*FPPE
= cast
<FunctionParmPackExpr
>(E
);
5578 Out
<< "v110_SUBSTPACK";
5579 MangleDeclRefExpr(FPPE
->getParameterPack());
5583 case Expr::DependentScopeDeclRefExprClass
: {
5585 const DependentScopeDeclRefExpr
*DRE
= cast
<DependentScopeDeclRefExpr
>(E
);
5586 mangleUnresolvedName(DRE
->getQualifier(), DRE
->getDeclName(),
5587 DRE
->getTemplateArgs(), DRE
->getNumTemplateArgs(),
5592 case Expr::CXXBindTemporaryExprClass
:
5593 E
= cast
<CXXBindTemporaryExpr
>(E
)->getSubExpr();
5596 case Expr::ExprWithCleanupsClass
:
5597 E
= cast
<ExprWithCleanups
>(E
)->getSubExpr();
5600 case Expr::FloatingLiteralClass
: {
5602 const FloatingLiteral
*FL
= cast
<FloatingLiteral
>(E
);
5603 mangleFloatLiteral(FL
->getType(), FL
->getValue());
5607 case Expr::FixedPointLiteralClass
:
5608 // Currently unimplemented -- might be <expr-primary> in future?
5609 mangleFixedPointLiteral();
5612 case Expr::CharacterLiteralClass
:
5615 mangleType(E
->getType());
5616 Out
<< cast
<CharacterLiteral
>(E
)->getValue();
5620 // FIXME. __objc_yes/__objc_no are mangled same as true/false
5621 case Expr::ObjCBoolLiteralExprClass
:
5624 Out
<< (cast
<ObjCBoolLiteralExpr
>(E
)->getValue() ? '1' : '0');
5628 case Expr::CXXBoolLiteralExprClass
:
5631 Out
<< (cast
<CXXBoolLiteralExpr
>(E
)->getValue() ? '1' : '0');
5635 case Expr::IntegerLiteralClass
: {
5637 llvm::APSInt
Value(cast
<IntegerLiteral
>(E
)->getValue());
5638 if (E
->getType()->isSignedIntegerType())
5639 Value
.setIsSigned(true);
5640 mangleIntegerLiteral(E
->getType(), Value
);
5644 case Expr::ImaginaryLiteralClass
: {
5646 const ImaginaryLiteral
*IE
= cast
<ImaginaryLiteral
>(E
);
5647 // Mangle as if a complex literal.
5648 // Proposal from David Vandevoorde, 2010.06.30.
5650 mangleType(E
->getType());
5651 if (const FloatingLiteral
*Imag
=
5652 dyn_cast
<FloatingLiteral
>(IE
->getSubExpr())) {
5653 // Mangle a floating-point zero of the appropriate type.
5654 mangleFloat(llvm::APFloat(Imag
->getValue().getSemantics()));
5656 mangleFloat(Imag
->getValue());
5659 llvm::APSInt
Value(cast
<IntegerLiteral
>(IE
->getSubExpr())->getValue());
5660 if (IE
->getSubExpr()->getType()->isSignedIntegerType())
5661 Value
.setIsSigned(true);
5662 mangleNumber(Value
);
5668 case Expr::StringLiteralClass
: {
5670 // Revised proposal from David Vandervoorde, 2010.07.15.
5672 assert(isa
<ConstantArrayType
>(E
->getType()));
5673 mangleType(E
->getType());
5678 case Expr::GNUNullExprClass
:
5680 // Mangle as if an integer literal 0.
5681 mangleIntegerLiteral(E
->getType(), llvm::APSInt(32));
5684 case Expr::CXXNullPtrLiteralExprClass
: {
5690 case Expr::LambdaExprClass
: {
5691 // A lambda-expression can't appear in the signature of an
5692 // externally-visible declaration, so there's no standard mangling for
5693 // this, but mangling as a literal of the closure type seems reasonable.
5695 mangleType(Context
.getASTContext().getRecordType(cast
<LambdaExpr
>(E
)->getLambdaClass()));
5700 case Expr::PackExpansionExprClass
:
5703 mangleExpression(cast
<PackExpansionExpr
>(E
)->getPattern());
5706 case Expr::SizeOfPackExprClass
: {
5708 auto *SPE
= cast
<SizeOfPackExpr
>(E
);
5709 if (SPE
->isPartiallySubstituted()) {
5711 for (const auto &A
: SPE
->getPartialArguments())
5712 mangleTemplateArg(A
, false);
5718 const NamedDecl
*Pack
= SPE
->getPack();
5719 if (const TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(Pack
))
5720 mangleTemplateParameter(TTP
->getDepth(), TTP
->getIndex());
5721 else if (const NonTypeTemplateParmDecl
*NTTP
5722 = dyn_cast
<NonTypeTemplateParmDecl
>(Pack
))
5723 mangleTemplateParameter(NTTP
->getDepth(), NTTP
->getIndex());
5724 else if (const TemplateTemplateParmDecl
*TempTP
5725 = dyn_cast
<TemplateTemplateParmDecl
>(Pack
))
5726 mangleTemplateParameter(TempTP
->getDepth(), TempTP
->getIndex());
5728 mangleFunctionParam(cast
<ParmVarDecl
>(Pack
));
5732 case Expr::MaterializeTemporaryExprClass
:
5733 E
= cast
<MaterializeTemporaryExpr
>(E
)->getSubExpr();
5736 case Expr::CXXFoldExprClass
: {
5738 auto *FE
= cast
<CXXFoldExpr
>(E
);
5739 if (FE
->isLeftFold())
5740 Out
<< (FE
->getInit() ? "fL" : "fl");
5742 Out
<< (FE
->getInit() ? "fR" : "fr");
5744 if (FE
->getOperator() == BO_PtrMemD
)
5748 BinaryOperator::getOverloadedOperator(FE
->getOperator()),
5752 mangleExpression(FE
->getLHS());
5754 mangleExpression(FE
->getRHS());
5758 case Expr::CXXThisExprClass
:
5763 case Expr::CoawaitExprClass
:
5764 // FIXME: Propose a non-vendor mangling.
5766 Out
<< "v18co_await";
5767 mangleExpression(cast
<CoawaitExpr
>(E
)->getOperand());
5770 case Expr::DependentCoawaitExprClass
:
5771 // FIXME: Propose a non-vendor mangling.
5773 Out
<< "v18co_await";
5774 mangleExpression(cast
<DependentCoawaitExpr
>(E
)->getOperand());
5777 case Expr::CoyieldExprClass
:
5778 // FIXME: Propose a non-vendor mangling.
5780 Out
<< "v18co_yield";
5781 mangleExpression(cast
<CoawaitExpr
>(E
)->getOperand());
5783 case Expr::SYCLUniqueStableNameExprClass
: {
5784 const auto *USN
= cast
<SYCLUniqueStableNameExpr
>(E
);
5787 Out
<< "u33__builtin_sycl_unique_stable_name";
5788 mangleType(USN
->getTypeSourceInfo()->getType());
5793 case Expr::HLSLOutArgExprClass
:
5795 "cannot mangle hlsl temporary value; mangling wrong thing?");
5796 case Expr::OpenACCAsteriskSizeExprClass
: {
5797 // We shouldn't ever be able to get here, but diagnose anyway.
5798 DiagnosticsEngine
&Diags
= Context
.getDiags();
5799 unsigned DiagID
= Diags
.getCustomDiagID(
5800 DiagnosticsEngine::Error
,
5801 "cannot yet mangle OpenACC Asterisk Size expression");
5802 Diags
.Report(DiagID
);
5807 if (AsTemplateArg
&& !IsPrimaryExpr
)
5811 /// Mangle an expression which refers to a parameter variable.
5813 /// <expression> ::= <function-param>
5814 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
5815 /// <function-param> ::= fp <top-level CV-qualifiers>
5816 /// <parameter-2 non-negative number> _ # L == 0, I > 0
5817 /// <function-param> ::= fL <L-1 non-negative number>
5818 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
5819 /// <function-param> ::= fL <L-1 non-negative number>
5820 /// p <top-level CV-qualifiers>
5821 /// <I-1 non-negative number> _ # L > 0, I > 0
5823 /// L is the nesting depth of the parameter, defined as 1 if the
5824 /// parameter comes from the innermost function prototype scope
5825 /// enclosing the current context, 2 if from the next enclosing
5826 /// function prototype scope, and so on, with one special case: if
5827 /// we've processed the full parameter clause for the innermost
5828 /// function type, then L is one less. This definition conveniently
5829 /// makes it irrelevant whether a function's result type was written
5830 /// trailing or leading, but is otherwise overly complicated; the
5831 /// numbering was first designed without considering references to
5832 /// parameter in locations other than return types, and then the
5833 /// mangling had to be generalized without changing the existing
5836 /// I is the zero-based index of the parameter within its parameter
5837 /// declaration clause. Note that the original ABI document describes
5838 /// this using 1-based ordinals.
5839 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl
*parm
) {
5840 unsigned parmDepth
= parm
->getFunctionScopeDepth();
5841 unsigned parmIndex
= parm
->getFunctionScopeIndex();
5844 // parmDepth does not include the declaring function prototype.
5845 // FunctionTypeDepth does account for that.
5846 assert(parmDepth
< FunctionTypeDepth
.getDepth());
5847 unsigned nestingDepth
= FunctionTypeDepth
.getDepth() - parmDepth
;
5848 if (FunctionTypeDepth
.isInResultType())
5851 if (nestingDepth
== 0) {
5854 Out
<< "fL" << (nestingDepth
- 1) << 'p';
5857 // Top-level qualifiers. We don't have to worry about arrays here,
5858 // because parameters declared as arrays should already have been
5859 // transformed to have pointer type. FIXME: apparently these don't
5860 // get mangled if used as an rvalue of a known non-class type?
5861 assert(!parm
->getType()->isArrayType()
5862 && "parameter's type is still an array type?");
5864 if (const DependentAddressSpaceType
*DAST
=
5865 dyn_cast
<DependentAddressSpaceType
>(parm
->getType())) {
5866 mangleQualifiers(DAST
->getPointeeType().getQualifiers(), DAST
);
5868 mangleQualifiers(parm
->getType().getQualifiers());
5872 if (parmIndex
!= 0) {
5873 Out
<< (parmIndex
- 1);
5878 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T
,
5879 const CXXRecordDecl
*InheritedFrom
) {
5880 // <ctor-dtor-name> ::= C1 # complete object constructor
5881 // ::= C2 # base object constructor
5882 // ::= CI1 <type> # complete inheriting constructor
5883 // ::= CI2 <type> # base inheriting constructor
5885 // In addition, C5 is a comdat name with C1 and C2 in it.
5899 case Ctor_DefaultClosure
:
5900 case Ctor_CopyingClosure
:
5901 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
5904 mangleName(InheritedFrom
);
5907 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T
) {
5908 // <ctor-dtor-name> ::= D0 # deleting destructor
5909 // ::= D1 # complete object destructor
5910 // ::= D2 # base object destructor
5912 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
5929 // Helper to provide ancillary information on a template used to mangle its
5931 struct CXXNameMangler::TemplateArgManglingInfo
{
5932 const CXXNameMangler
&Mangler
;
5933 TemplateDecl
*ResolvedTemplate
= nullptr;
5934 bool SeenPackExpansionIntoNonPack
= false;
5935 const NamedDecl
*UnresolvedExpandedPack
= nullptr;
5937 TemplateArgManglingInfo(const CXXNameMangler
&Mangler
, TemplateName TN
)
5938 : Mangler(Mangler
) {
5939 if (TemplateDecl
*TD
= TN
.getAsTemplateDecl())
5940 ResolvedTemplate
= TD
;
5943 /// Information about how to mangle a template argument.
5945 /// Do we need to mangle the template argument with an exactly correct type?
5947 /// If we need to prefix the mangling with a mangling of the template
5948 /// parameter, the corresponding parameter.
5949 const NamedDecl
*TemplateParameterToMangle
;
5952 /// Determine whether the resolved template might be overloaded on its
5953 /// template parameter list. If so, the mangling needs to include enough
5954 /// information to reconstruct the template parameter list.
5955 bool isOverloadable() {
5956 // Function templates are generally overloadable. As a special case, a
5957 // member function template of a generic lambda is not overloadable.
5958 if (auto *FTD
= dyn_cast_or_null
<FunctionTemplateDecl
>(ResolvedTemplate
)) {
5959 auto *RD
= dyn_cast
<CXXRecordDecl
>(FTD
->getDeclContext());
5960 if (!RD
|| !RD
->isGenericLambda())
5964 // All other templates are not overloadable. Partial specializations would
5965 // be, but we never mangle them.
5969 /// Determine whether we need to prefix this <template-arg> mangling with a
5970 /// <template-param-decl>. This happens if the natural template parameter for
5971 /// the argument mangling is not the same as the actual template parameter.
5972 bool needToMangleTemplateParam(const NamedDecl
*Param
,
5973 const TemplateArgument
&Arg
) {
5974 // For a template type parameter, the natural parameter is 'typename T'.
5975 // The actual parameter might be constrained.
5976 if (auto *TTP
= dyn_cast
<TemplateTypeParmDecl
>(Param
))
5977 return TTP
->hasTypeConstraint();
5979 if (Arg
.getKind() == TemplateArgument::Pack
) {
5980 // For an empty pack, the natural parameter is `typename...`.
5981 if (Arg
.pack_size() == 0)
5984 // For any other pack, we use the first argument to determine the natural
5985 // template parameter.
5986 return needToMangleTemplateParam(Param
, *Arg
.pack_begin());
5989 // For a non-type template parameter, the natural parameter is `T V` (for a
5990 // prvalue argument) or `T &V` (for a glvalue argument), where `T` is the
5991 // type of the argument, which we require to exactly match. If the actual
5992 // parameter has a deduced or instantiation-dependent type, it is not
5993 // equivalent to the natural parameter.
5994 if (auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(Param
))
5995 return NTTP
->getType()->isInstantiationDependentType() ||
5996 NTTP
->getType()->getContainedDeducedType();
5998 // For a template template parameter, the template-head might differ from
5999 // that of the template.
6000 auto *TTP
= cast
<TemplateTemplateParmDecl
>(Param
);
6001 TemplateName ArgTemplateName
= Arg
.getAsTemplateOrTemplatePattern();
6002 assert(!ArgTemplateName
.getTemplateDeclAndDefaultArgs().second
&&
6003 "A DeducedTemplateName shouldn't escape partial ordering");
6004 const TemplateDecl
*ArgTemplate
=
6005 ArgTemplateName
.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6009 // Mangle the template parameter list of the parameter and argument to see
6010 // if they are the same. We can't use Profile for this, because it can't
6011 // model the depth difference between parameter and argument and might not
6012 // necessarily have the same definition of "identical" that we use here --
6013 // that is, same mangling.
6014 auto MangleTemplateParamListToString
=
6015 [&](SmallVectorImpl
<char> &Buffer
, const TemplateParameterList
*Params
,
6016 unsigned DepthOffset
) {
6017 llvm::raw_svector_ostream
Stream(Buffer
);
6018 CXXNameMangler(Mangler
.Context
, Stream
,
6019 WithTemplateDepthOffset
{DepthOffset
})
6020 .mangleTemplateParameterList(Params
);
6022 llvm::SmallString
<128> ParamTemplateHead
, ArgTemplateHead
;
6023 MangleTemplateParamListToString(ParamTemplateHead
,
6024 TTP
->getTemplateParameters(), 0);
6025 // Add the depth of the parameter's template parameter list to all
6026 // parameters appearing in the argument to make the indexes line up
6028 MangleTemplateParamListToString(ArgTemplateHead
,
6029 ArgTemplate
->getTemplateParameters(),
6030 TTP
->getTemplateParameters()->getDepth());
6031 return ParamTemplateHead
!= ArgTemplateHead
;
6034 /// Determine information about how this template argument should be mangled.
6035 /// This should be called exactly once for each parameter / argument pair, in
6037 Info
getArgInfo(unsigned ParamIdx
, const TemplateArgument
&Arg
) {
6038 // We need correct types when the template-name is unresolved or when it
6039 // names a template that is able to be overloaded.
6040 if (!ResolvedTemplate
|| SeenPackExpansionIntoNonPack
)
6041 return {true, nullptr};
6043 // Move to the next parameter.
6044 const NamedDecl
*Param
= UnresolvedExpandedPack
;
6046 assert(ParamIdx
< ResolvedTemplate
->getTemplateParameters()->size() &&
6047 "no parameter for argument");
6048 Param
= ResolvedTemplate
->getTemplateParameters()->getParam(ParamIdx
);
6050 // If we reach a parameter pack whose argument isn't in pack form, that
6051 // means Sema couldn't or didn't figure out which arguments belonged to
6052 // it, because it contains a pack expansion or because Sema bailed out of
6053 // computing parameter / argument correspondence before this point. Track
6054 // the pack as the corresponding parameter for all further template
6055 // arguments until we hit a pack expansion, at which point we don't know
6056 // the correspondence between parameters and arguments at all.
6057 if (Param
->isParameterPack() && Arg
.getKind() != TemplateArgument::Pack
) {
6058 UnresolvedExpandedPack
= Param
;
6062 // If we encounter a pack argument that is expanded into a non-pack
6063 // parameter, we can no longer track parameter / argument correspondence,
6064 // and need to use exact types from this point onwards.
6065 if (Arg
.isPackExpansion() &&
6066 (!Param
->isParameterPack() || UnresolvedExpandedPack
)) {
6067 SeenPackExpansionIntoNonPack
= true;
6068 return {true, nullptr};
6071 // We need exact types for arguments of a template that might be overloaded
6072 // on template parameter type.
6073 if (isOverloadable())
6074 return {true, needToMangleTemplateParam(Param
, Arg
) ? Param
: nullptr};
6076 // Otherwise, we only need a correct type if the parameter has a deduced
6079 // Note: for an expanded parameter pack, getType() returns the type prior
6080 // to expansion. We could ask for the expanded type with getExpansionType(),
6081 // but it doesn't matter because substitution and expansion don't affect
6082 // whether a deduced type appears in the type.
6083 auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(Param
);
6084 bool NeedExactType
= NTTP
&& NTTP
->getType()->getContainedDeducedType();
6085 return {NeedExactType
, nullptr};
6088 /// Determine if we should mangle a requires-clause after the template
6089 /// argument list. If so, returns the expression to mangle.
6090 const Expr
*getTrailingRequiresClauseToMangle() {
6091 if (!isOverloadable())
6093 return ResolvedTemplate
->getTemplateParameters()->getRequiresClause();
6097 void CXXNameMangler::mangleTemplateArgs(TemplateName TN
,
6098 const TemplateArgumentLoc
*TemplateArgs
,
6099 unsigned NumTemplateArgs
) {
6100 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6102 TemplateArgManglingInfo
Info(*this, TN
);
6103 for (unsigned i
= 0; i
!= NumTemplateArgs
; ++i
) {
6104 mangleTemplateArg(Info
, i
, TemplateArgs
[i
].getArgument());
6106 mangleRequiresClause(Info
.getTrailingRequiresClauseToMangle());
6110 void CXXNameMangler::mangleTemplateArgs(TemplateName TN
,
6111 const TemplateArgumentList
&AL
) {
6112 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6114 TemplateArgManglingInfo
Info(*this, TN
);
6115 for (unsigned i
= 0, e
= AL
.size(); i
!= e
; ++i
) {
6116 mangleTemplateArg(Info
, i
, AL
[i
]);
6118 mangleRequiresClause(Info
.getTrailingRequiresClauseToMangle());
6122 void CXXNameMangler::mangleTemplateArgs(TemplateName TN
,
6123 ArrayRef
<TemplateArgument
> Args
) {
6124 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6126 TemplateArgManglingInfo
Info(*this, TN
);
6127 for (unsigned i
= 0; i
!= Args
.size(); ++i
) {
6128 mangleTemplateArg(Info
, i
, Args
[i
]);
6130 mangleRequiresClause(Info
.getTrailingRequiresClauseToMangle());
6134 void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo
&Info
,
6135 unsigned Index
, TemplateArgument A
) {
6136 TemplateArgManglingInfo::Info ArgInfo
= Info
.getArgInfo(Index
, A
);
6138 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6139 if (ArgInfo
.TemplateParameterToMangle
&&
6140 !isCompatibleWith(LangOptions::ClangABI::Ver17
)) {
6141 // The template parameter is mangled if the mangling would otherwise be
6144 // <template-arg> ::= <template-param-decl> <template-arg>
6146 // Clang 17 and before did not do this.
6147 mangleTemplateParamDecl(ArgInfo
.TemplateParameterToMangle
);
6150 mangleTemplateArg(A
, ArgInfo
.NeedExactType
);
6153 void CXXNameMangler::mangleTemplateArg(TemplateArgument A
, bool NeedExactType
) {
6154 // <template-arg> ::= <type> # type or template
6155 // ::= X <expression> E # expression
6156 // ::= <expr-primary> # simple expressions
6157 // ::= J <template-arg>* E # argument pack
6158 if (!A
.isInstantiationDependent() || A
.isDependent())
6159 A
= Context
.getASTContext().getCanonicalTemplateArgument(A
);
6161 switch (A
.getKind()) {
6162 case TemplateArgument::Null
:
6163 llvm_unreachable("Cannot mangle NULL template argument");
6165 case TemplateArgument::Type
:
6166 mangleType(A
.getAsType());
6168 case TemplateArgument::Template
:
6169 // This is mangled as <type>.
6170 mangleType(A
.getAsTemplate());
6172 case TemplateArgument::TemplateExpansion
:
6173 // <type> ::= Dp <type> # pack expansion (C++0x)
6175 mangleType(A
.getAsTemplateOrTemplatePattern());
6177 case TemplateArgument::Expression
:
6178 mangleTemplateArgExpr(A
.getAsExpr());
6180 case TemplateArgument::Integral
:
6181 mangleIntegerLiteral(A
.getIntegralType(), A
.getAsIntegral());
6183 case TemplateArgument::Declaration
: {
6184 // <expr-primary> ::= L <mangled-name> E # external name
6185 ValueDecl
*D
= A
.getAsDecl();
6187 // Template parameter objects are modeled by reproducing a source form
6188 // produced as if by aggregate initialization.
6189 if (A
.getParamTypeForDecl()->isRecordType()) {
6190 auto *TPO
= cast
<TemplateParamObjectDecl
>(D
);
6191 mangleValueInTemplateArg(TPO
->getType().getUnqualifiedType(),
6192 TPO
->getValue(), /*TopLevel=*/true,
6197 ASTContext
&Ctx
= Context
.getASTContext();
6199 if (D
->isCXXInstanceMember())
6200 // Simple pointer-to-member with no conversion.
6201 Value
= APValue(D
, /*IsDerivedMember=*/false, /*Path=*/{});
6202 else if (D
->getType()->isArrayType() &&
6203 Ctx
.hasSimilarType(Ctx
.getDecayedType(D
->getType()),
6204 A
.getParamTypeForDecl()) &&
6205 !isCompatibleWith(LangOptions::ClangABI::Ver11
))
6206 // Build a value corresponding to this implicit array-to-pointer decay.
6207 Value
= APValue(APValue::LValueBase(D
), CharUnits::Zero(),
6208 {APValue::LValuePathEntry::ArrayIndex(0)},
6209 /*OnePastTheEnd=*/false);
6211 // Regular pointer or reference to a declaration.
6212 Value
= APValue(APValue::LValueBase(D
), CharUnits::Zero(),
6213 ArrayRef
<APValue::LValuePathEntry
>(),
6214 /*OnePastTheEnd=*/false);
6215 mangleValueInTemplateArg(A
.getParamTypeForDecl(), Value
, /*TopLevel=*/true,
6219 case TemplateArgument::NullPtr
: {
6220 mangleNullPointer(A
.getNullPtrType());
6223 case TemplateArgument::StructuralValue
:
6224 mangleValueInTemplateArg(A
.getStructuralValueType(),
6225 A
.getAsStructuralValue(),
6226 /*TopLevel=*/true, NeedExactType
);
6228 case TemplateArgument::Pack
: {
6229 // <template-arg> ::= J <template-arg>* E
6231 for (const auto &P
: A
.pack_elements())
6232 mangleTemplateArg(P
, NeedExactType
);
6238 void CXXNameMangler::mangleTemplateArgExpr(const Expr
*E
) {
6239 if (!isCompatibleWith(LangOptions::ClangABI::Ver11
)) {
6240 mangleExpression(E
, UnknownArity
, /*AsTemplateArg=*/true);
6244 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
6245 // correctly in cases where the template argument was
6246 // constructed from an expression rather than an already-evaluated
6247 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
6250 // We did special-case DeclRefExpr to attempt to DTRT for that one
6251 // expression-kind, but while doing so, unfortunately handled ParmVarDecl
6252 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
6253 // the proper 'Xfp_E'.
6254 E
= E
->IgnoreParenImpCasts();
6255 if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
6256 const ValueDecl
*D
= DRE
->getDecl();
6257 if (isa
<VarDecl
>(D
) || isa
<FunctionDecl
>(D
)) {
6265 mangleExpression(E
);
6269 /// Determine whether a given value is equivalent to zero-initialization for
6270 /// the purpose of discarding a trailing portion of a 'tl' mangling.
6272 /// Note that this is not in general equivalent to determining whether the
6273 /// value has an all-zeroes bit pattern.
6274 static bool isZeroInitialized(QualType T
, const APValue
&V
) {
6275 // FIXME: mangleValueInTemplateArg has quadratic time complexity in
6276 // pathological cases due to using this, but it's a little awkward
6277 // to do this in linear time in general.
6278 switch (V
.getKind()) {
6280 case APValue::Indeterminate
:
6281 case APValue::AddrLabelDiff
:
6284 case APValue::Struct
: {
6285 const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl();
6286 assert(RD
&& "unexpected type for record value");
6288 for (const CXXBaseSpecifier
&BS
: RD
->bases()) {
6289 if (!isZeroInitialized(BS
.getType(), V
.getStructBase(I
)))
6294 for (const FieldDecl
*FD
: RD
->fields()) {
6295 if (!FD
->isUnnamedBitField() &&
6296 !isZeroInitialized(FD
->getType(), V
.getStructField(I
)))
6303 case APValue::Union
: {
6304 const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl();
6305 assert(RD
&& "unexpected type for union value");
6306 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
6307 for (const FieldDecl
*FD
: RD
->fields()) {
6308 if (!FD
->isUnnamedBitField())
6309 return V
.getUnionField() && declaresSameEntity(FD
, V
.getUnionField()) &&
6310 isZeroInitialized(FD
->getType(), V
.getUnionValue());
6312 // If there are no fields (other than unnamed bitfields), the value is
6313 // necessarily zero-initialized.
6317 case APValue::Array
: {
6318 QualType
ElemT(T
->getArrayElementTypeNoTypeQual(), 0);
6319 for (unsigned I
= 0, N
= V
.getArrayInitializedElts(); I
!= N
; ++I
)
6320 if (!isZeroInitialized(ElemT
, V
.getArrayInitializedElt(I
)))
6322 return !V
.hasArrayFiller() || isZeroInitialized(ElemT
, V
.getArrayFiller());
6325 case APValue::Vector
: {
6326 const VectorType
*VT
= T
->castAs
<VectorType
>();
6327 for (unsigned I
= 0, N
= V
.getVectorLength(); I
!= N
; ++I
)
6328 if (!isZeroInitialized(VT
->getElementType(), V
.getVectorElt(I
)))
6336 case APValue::Float
:
6337 return V
.getFloat().isPosZero();
6339 case APValue::FixedPoint
:
6340 return !V
.getFixedPoint().getValue();
6342 case APValue::ComplexFloat
:
6343 return V
.getComplexFloatReal().isPosZero() &&
6344 V
.getComplexFloatImag().isPosZero();
6346 case APValue::ComplexInt
:
6347 return !V
.getComplexIntReal() && !V
.getComplexIntImag();
6349 case APValue::LValue
:
6350 return V
.isNullPointer();
6352 case APValue::MemberPointer
:
6353 return !V
.getMemberPointerDecl();
6356 llvm_unreachable("Unhandled APValue::ValueKind enum");
6359 static QualType
getLValueType(ASTContext
&Ctx
, const APValue
&LV
) {
6360 QualType T
= LV
.getLValueBase().getType();
6361 for (APValue::LValuePathEntry E
: LV
.getLValuePath()) {
6362 if (const ArrayType
*AT
= Ctx
.getAsArrayType(T
))
6363 T
= AT
->getElementType();
6364 else if (const FieldDecl
*FD
=
6365 dyn_cast
<FieldDecl
>(E
.getAsBaseOrMember().getPointer()))
6368 T
= Ctx
.getRecordType(
6369 cast
<CXXRecordDecl
>(E
.getAsBaseOrMember().getPointer()));
6374 static IdentifierInfo
*getUnionInitName(SourceLocation UnionLoc
,
6375 DiagnosticsEngine
&Diags
,
6376 const FieldDecl
*FD
) {
6378 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
6379 // For the purposes of mangling, the name of an anonymous union is considered
6380 // to be the name of the first named data member found by a pre-order,
6381 // depth-first, declaration-order walk of the data members of the anonymous
6384 if (FD
->getIdentifier())
6385 return FD
->getIdentifier();
6387 // The only cases where the identifer of a FieldDecl would be blank is if the
6388 // field represents an anonymous record type or if it is an unnamed bitfield.
6389 // There is no type to descend into in the case of a bitfield, so we can just
6390 // return nullptr in that case.
6391 if (FD
->isBitField())
6393 const CXXRecordDecl
*RD
= FD
->getType()->getAsCXXRecordDecl();
6395 // Consider only the fields in declaration order, searched depth-first. We
6396 // don't care about the active member of the union, as all we are doing is
6397 // looking for a valid name. We also don't check bases, due to guidance from
6398 // the Itanium ABI folks.
6399 for (const FieldDecl
*RDField
: RD
->fields()) {
6400 if (IdentifierInfo
*II
= getUnionInitName(UnionLoc
, Diags
, RDField
))
6404 // According to the Itanium ABI: If there is no such data member (i.e., if all
6405 // of the data members in the union are unnamed), then there is no way for a
6406 // program to refer to the anonymous union, and there is therefore no need to
6407 // mangle its name. However, we should diagnose this anyway.
6408 unsigned DiagID
= Diags
.getCustomDiagID(
6409 DiagnosticsEngine::Error
, "cannot mangle this unnamed union NTTP yet");
6410 Diags
.Report(UnionLoc
, DiagID
);
6415 void CXXNameMangler::mangleValueInTemplateArg(QualType T
, const APValue
&V
,
6417 bool NeedExactType
) {
6418 // Ignore all top-level cv-qualifiers, to match GCC.
6420 T
= getASTContext().getUnqualifiedArrayType(T
, Quals
);
6422 // A top-level expression that's not a primary expression is wrapped in X...E.
6423 bool IsPrimaryExpr
= true;
6424 auto NotPrimaryExpr
= [&] {
6425 if (TopLevel
&& IsPrimaryExpr
)
6427 IsPrimaryExpr
= false;
6430 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
6431 switch (V
.getKind()) {
6433 case APValue::Indeterminate
:
6439 case APValue::AddrLabelDiff
:
6440 llvm_unreachable("unexpected value kind in template argument");
6442 case APValue::Struct
: {
6443 const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl();
6444 assert(RD
&& "unexpected type for record value");
6446 // Drop trailing zero-initialized elements.
6447 llvm::SmallVector
<const FieldDecl
*, 16> Fields(RD
->fields());
6450 (Fields
.back()->isUnnamedBitField() ||
6451 isZeroInitialized(Fields
.back()->getType(),
6452 V
.getStructField(Fields
.back()->getFieldIndex())))) {
6455 llvm::ArrayRef
<CXXBaseSpecifier
> Bases(RD
->bases_begin(), RD
->bases_end());
6456 if (Fields
.empty()) {
6457 while (!Bases
.empty() &&
6458 isZeroInitialized(Bases
.back().getType(),
6459 V
.getStructBase(Bases
.size() - 1)))
6460 Bases
= Bases
.drop_back();
6463 // <expression> ::= tl <type> <braced-expression>* E
6467 for (unsigned I
= 0, N
= Bases
.size(); I
!= N
; ++I
)
6468 mangleValueInTemplateArg(Bases
[I
].getType(), V
.getStructBase(I
), false);
6469 for (unsigned I
= 0, N
= Fields
.size(); I
!= N
; ++I
) {
6470 if (Fields
[I
]->isUnnamedBitField())
6472 mangleValueInTemplateArg(Fields
[I
]->getType(),
6473 V
.getStructField(Fields
[I
]->getFieldIndex()),
6480 case APValue::Union
: {
6481 assert(T
->getAsCXXRecordDecl() && "unexpected type for union value");
6482 const FieldDecl
*FD
= V
.getUnionField();
6491 // <braced-expression> ::= di <field source-name> <braced-expression>
6495 if (!isZeroInitialized(T
, V
)) {
6497 IdentifierInfo
*II
= (getUnionInitName(
6498 T
->getAsCXXRecordDecl()->getLocation(), Context
.getDiags(), FD
));
6500 mangleSourceName(II
);
6501 mangleValueInTemplateArg(FD
->getType(), V
.getUnionValue(), false);
6507 case APValue::Array
: {
6508 QualType
ElemT(T
->getArrayElementTypeNoTypeQual(), 0);
6514 // Drop trailing zero-initialized elements.
6515 unsigned N
= V
.getArraySize();
6516 if (!V
.hasArrayFiller() || isZeroInitialized(ElemT
, V
.getArrayFiller())) {
6517 N
= V
.getArrayInitializedElts();
6518 while (N
&& isZeroInitialized(ElemT
, V
.getArrayInitializedElt(N
- 1)))
6522 for (unsigned I
= 0; I
!= N
; ++I
) {
6523 const APValue
&Elem
= I
< V
.getArrayInitializedElts()
6524 ? V
.getArrayInitializedElt(I
)
6525 : V
.getArrayFiller();
6526 mangleValueInTemplateArg(ElemT
, Elem
, false);
6532 case APValue::Vector
: {
6533 const VectorType
*VT
= T
->castAs
<VectorType
>();
6538 unsigned N
= V
.getVectorLength();
6539 while (N
&& isZeroInitialized(VT
->getElementType(), V
.getVectorElt(N
- 1)))
6541 for (unsigned I
= 0; I
!= N
; ++I
)
6542 mangleValueInTemplateArg(VT
->getElementType(), V
.getVectorElt(I
), false);
6548 mangleIntegerLiteral(T
, V
.getInt());
6551 case APValue::Float
:
6552 mangleFloatLiteral(T
, V
.getFloat());
6555 case APValue::FixedPoint
:
6556 mangleFixedPointLiteral();
6559 case APValue::ComplexFloat
: {
6560 const ComplexType
*CT
= T
->castAs
<ComplexType
>();
6564 if (!V
.getComplexFloatReal().isPosZero() ||
6565 !V
.getComplexFloatImag().isPosZero())
6566 mangleFloatLiteral(CT
->getElementType(), V
.getComplexFloatReal());
6567 if (!V
.getComplexFloatImag().isPosZero())
6568 mangleFloatLiteral(CT
->getElementType(), V
.getComplexFloatImag());
6573 case APValue::ComplexInt
: {
6574 const ComplexType
*CT
= T
->castAs
<ComplexType
>();
6578 if (V
.getComplexIntReal().getBoolValue() ||
6579 V
.getComplexIntImag().getBoolValue())
6580 mangleIntegerLiteral(CT
->getElementType(), V
.getComplexIntReal());
6581 if (V
.getComplexIntImag().getBoolValue())
6582 mangleIntegerLiteral(CT
->getElementType(), V
.getComplexIntImag());
6587 case APValue::LValue
: {
6588 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6589 assert((T
->isPointerOrReferenceType()) &&
6590 "unexpected type for LValue template arg");
6592 if (V
.isNullPointer()) {
6593 mangleNullPointer(T
);
6597 APValue::LValueBase B
= V
.getLValueBase();
6599 // Non-standard mangling for integer cast to a pointer; this can only
6600 // occur as an extension.
6601 CharUnits Offset
= V
.getLValueOffset();
6602 if (Offset
.isZero()) {
6603 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
6604 // a cast, because L <type> 0 E means something else.
6614 Out
<< Offset
.getQuantity() << 'E';
6619 ASTContext
&Ctx
= Context
.getASTContext();
6621 enum { Base
, Offset
, Path
} Kind
;
6622 if (!V
.hasLValuePath()) {
6623 // Mangle as (T*)((char*)&base + N).
6624 if (T
->isReferenceType()) {
6627 mangleType(T
->getPointeeType());
6636 // Clang 11 and before mangled an array subject to array-to-pointer decay
6637 // as if it were the declaration itself.
6638 bool IsArrayToPointerDecayMangledAsDecl
= false;
6639 if (TopLevel
&& Ctx
.getLangOpts().getClangABICompat() <=
6640 LangOptions::ClangABI::Ver11
) {
6641 QualType BType
= B
.getType();
6642 IsArrayToPointerDecayMangledAsDecl
=
6643 BType
->isArrayType() && V
.getLValuePath().size() == 1 &&
6644 V
.getLValuePath()[0].getAsArrayIndex() == 0 &&
6645 Ctx
.hasSimilarType(T
, Ctx
.getDecayedType(BType
));
6648 if ((!V
.getLValuePath().empty() || V
.isLValueOnePastTheEnd()) &&
6649 !IsArrayToPointerDecayMangledAsDecl
) {
6651 // A final conversion to the template parameter's type is usually
6652 // folded into the 'so' mangling, but we can't do that for 'void*'
6653 // parameters without introducing collisions.
6654 if (NeedExactType
&& T
->isVoidPointerType()) {
6658 if (T
->isPointerType())
6661 mangleType(T
->isVoidPointerType()
6662 ? getLValueType(Ctx
, V
).getUnqualifiedType()
6663 : T
->getPointeeType());
6666 if (NeedExactType
&&
6667 !Ctx
.hasSameType(T
->getPointeeType(), getLValueType(Ctx
, V
)) &&
6668 !isCompatibleWith(LangOptions::ClangABI::Ver11
)) {
6673 if (T
->isPointerType()) {
6681 QualType TypeSoFar
= B
.getType();
6682 if (auto *VD
= B
.dyn_cast
<const ValueDecl
*>()) {
6686 } else if (auto *E
= B
.dyn_cast
<const Expr
*>()) {
6688 mangleExpression(E
);
6689 } else if (auto TI
= B
.dyn_cast
<TypeInfoLValue
>()) {
6692 mangleType(QualType(TI
.getType(), 0));
6694 // We should never see dynamic allocations here.
6695 llvm_unreachable("unexpected lvalue base kind in template argument");
6704 mangleType(Ctx
.getPointerDiffType());
6705 mangleNumber(V
.getLValueOffset().getQuantity());
6710 // <expression> ::= so <referent type> <expr> [<offset number>]
6711 // <union-selector>* [p] E
6712 if (!V
.getLValueOffset().isZero())
6713 mangleNumber(V
.getLValueOffset().getQuantity());
6715 // We model a past-the-end array pointer as array indexing with index N,
6716 // not with the "past the end" flag. Compensate for that.
6717 bool OnePastTheEnd
= V
.isLValueOnePastTheEnd();
6719 for (APValue::LValuePathEntry E
: V
.getLValuePath()) {
6720 if (auto *AT
= TypeSoFar
->getAsArrayTypeUnsafe()) {
6721 if (auto *CAT
= dyn_cast
<ConstantArrayType
>(AT
))
6722 OnePastTheEnd
|= CAT
->getSize() == E
.getAsArrayIndex();
6723 TypeSoFar
= AT
->getElementType();
6725 const Decl
*D
= E
.getAsBaseOrMember().getPointer();
6726 if (auto *FD
= dyn_cast
<FieldDecl
>(D
)) {
6727 // <union-selector> ::= _ <number>
6728 if (FD
->getParent()->isUnion()) {
6730 if (FD
->getFieldIndex())
6731 Out
<< (FD
->getFieldIndex() - 1);
6733 TypeSoFar
= FD
->getType();
6735 TypeSoFar
= Ctx
.getRecordType(cast
<CXXRecordDecl
>(D
));
6749 case APValue::MemberPointer
:
6750 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6751 if (!V
.getMemberPointerDecl()) {
6752 mangleNullPointer(T
);
6756 ASTContext
&Ctx
= Context
.getASTContext();
6759 if (!V
.getMemberPointerPath().empty()) {
6762 } else if (NeedExactType
&&
6764 T
->castAs
<MemberPointerType
>()->getPointeeType(),
6765 V
.getMemberPointerDecl()->getType()) &&
6766 !isCompatibleWith(LangOptions::ClangABI::Ver11
)) {
6771 mangle(V
.getMemberPointerDecl());
6773 if (!V
.getMemberPointerPath().empty()) {
6775 Context
.getASTContext().getMemberPointerPathAdjustment(V
);
6776 if (!Offset
.isZero())
6777 mangleNumber(Offset
.getQuantity());
6783 if (TopLevel
&& !IsPrimaryExpr
)
6787 void CXXNameMangler::mangleTemplateParameter(unsigned Depth
, unsigned Index
) {
6788 // <template-param> ::= T_ # first template parameter
6789 // ::= T <parameter-2 non-negative number> _
6790 // ::= TL <L-1 non-negative number> __
6791 // ::= TL <L-1 non-negative number> _
6792 // <parameter-2 non-negative number> _
6794 // The latter two manglings are from a proposal here:
6795 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
6797 Depth
+= TemplateDepthOffset
;
6799 Out
<< 'L' << (Depth
- 1) << '_';
6805 void CXXNameMangler::mangleSeqID(unsigned SeqID
) {
6808 } else if (SeqID
== 1) {
6813 // <seq-id> is encoded in base-36, using digits and upper case letters.
6814 char Buffer
[7]; // log(2**32) / log(36) ~= 7
6815 MutableArrayRef
<char> BufferRef(Buffer
);
6816 MutableArrayRef
<char>::reverse_iterator I
= BufferRef
.rbegin();
6818 for (; SeqID
!= 0; SeqID
/= 36) {
6819 unsigned C
= SeqID
% 36;
6820 *I
++ = (C
< 10 ? '0' + C
: 'A' + C
- 10);
6823 Out
.write(I
.base(), I
- BufferRef
.rbegin());
6828 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname
) {
6829 bool result
= mangleSubstitution(tname
);
6830 assert(result
&& "no existing substitution for template name");
6834 // <substitution> ::= S <seq-id> _
6836 bool CXXNameMangler::mangleSubstitution(const NamedDecl
*ND
) {
6837 // Try one of the standard substitutions first.
6838 if (mangleStandardSubstitution(ND
))
6841 ND
= cast
<NamedDecl
>(ND
->getCanonicalDecl());
6842 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND
));
6845 bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier
*NNS
) {
6846 assert(NNS
->getKind() == NestedNameSpecifier::Identifier
&&
6847 "mangleSubstitution(NestedNameSpecifier *) is only used for "
6848 "identifier nested name specifiers.");
6849 NNS
= Context
.getASTContext().getCanonicalNestedNameSpecifier(NNS
);
6850 return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS
));
6853 /// Determine whether the given type has any qualifiers that are relevant for
6855 static bool hasMangledSubstitutionQualifiers(QualType T
) {
6856 Qualifiers Qs
= T
.getQualifiers();
6857 return Qs
.getCVRQualifiers() || Qs
.hasAddressSpace() || Qs
.hasUnaligned();
6860 bool CXXNameMangler::mangleSubstitution(QualType T
) {
6861 if (!hasMangledSubstitutionQualifiers(T
)) {
6862 if (const RecordType
*RT
= T
->getAs
<RecordType
>())
6863 return mangleSubstitution(RT
->getDecl());
6866 uintptr_t TypePtr
= reinterpret_cast<uintptr_t>(T
.getAsOpaquePtr());
6868 return mangleSubstitution(TypePtr
);
6871 bool CXXNameMangler::mangleSubstitution(TemplateName Template
) {
6872 if (TemplateDecl
*TD
= Template
.getAsTemplateDecl())
6873 return mangleSubstitution(TD
);
6875 Template
= Context
.getASTContext().getCanonicalTemplateName(Template
);
6876 return mangleSubstitution(
6877 reinterpret_cast<uintptr_t>(Template
.getAsVoidPointer()));
6880 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr
) {
6881 llvm::DenseMap
<uintptr_t, unsigned>::iterator I
= Substitutions
.find(Ptr
);
6882 if (I
== Substitutions
.end())
6885 unsigned SeqID
= I
->second
;
6892 /// Returns whether S is a template specialization of std::Name with a single
6893 /// argument of type A.
6894 bool CXXNameMangler::isSpecializedAs(QualType S
, llvm::StringRef Name
,
6899 const RecordType
*RT
= S
->getAs
<RecordType
>();
6903 const ClassTemplateSpecializationDecl
*SD
=
6904 dyn_cast
<ClassTemplateSpecializationDecl
>(RT
->getDecl());
6905 if (!SD
|| !SD
->getIdentifier()->isStr(Name
))
6908 if (!isStdNamespace(Context
.getEffectiveDeclContext(SD
)))
6911 const TemplateArgumentList
&TemplateArgs
= SD
->getTemplateArgs();
6912 if (TemplateArgs
.size() != 1)
6915 if (TemplateArgs
[0].getAsType() != A
)
6918 if (SD
->getSpecializedTemplate()->getOwningModuleForLinkage())
6924 /// Returns whether SD is a template specialization std::Name<char,
6925 /// std::char_traits<char> [, std::allocator<char>]>
6926 /// HasAllocator controls whether the 3rd template argument is needed.
6927 bool CXXNameMangler::isStdCharSpecialization(
6928 const ClassTemplateSpecializationDecl
*SD
, llvm::StringRef Name
,
6929 bool HasAllocator
) {
6930 if (!SD
->getIdentifier()->isStr(Name
))
6933 const TemplateArgumentList
&TemplateArgs
= SD
->getTemplateArgs();
6934 if (TemplateArgs
.size() != (HasAllocator
? 3 : 2))
6937 QualType A
= TemplateArgs
[0].getAsType();
6940 // Plain 'char' is named Char_S or Char_U depending on the target ABI.
6941 if (!A
->isSpecificBuiltinType(BuiltinType::Char_S
) &&
6942 !A
->isSpecificBuiltinType(BuiltinType::Char_U
))
6945 if (!isSpecializedAs(TemplateArgs
[1].getAsType(), "char_traits", A
))
6949 !isSpecializedAs(TemplateArgs
[2].getAsType(), "allocator", A
))
6952 if (SD
->getSpecializedTemplate()->getOwningModuleForLinkage())
6958 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl
*ND
) {
6959 // <substitution> ::= St # ::std::
6960 if (const NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(ND
)) {
6968 if (const ClassTemplateDecl
*TD
= dyn_cast
<ClassTemplateDecl
>(ND
)) {
6969 if (!isStdNamespace(Context
.getEffectiveDeclContext(TD
)))
6972 if (TD
->getOwningModuleForLinkage())
6975 // <substitution> ::= Sa # ::std::allocator
6976 if (TD
->getIdentifier()->isStr("allocator")) {
6981 // <<substitution> ::= Sb # ::std::basic_string
6982 if (TD
->getIdentifier()->isStr("basic_string")) {
6989 if (const ClassTemplateSpecializationDecl
*SD
=
6990 dyn_cast
<ClassTemplateSpecializationDecl
>(ND
)) {
6991 if (!isStdNamespace(Context
.getEffectiveDeclContext(SD
)))
6994 if (SD
->getSpecializedTemplate()->getOwningModuleForLinkage())
6997 // <substitution> ::= Ss # ::std::basic_string<char,
6998 // ::std::char_traits<char>,
6999 // ::std::allocator<char> >
7000 if (isStdCharSpecialization(SD
, "basic_string", /*HasAllocator=*/true)) {
7005 // <substitution> ::= Si # ::std::basic_istream<char,
7006 // ::std::char_traits<char> >
7007 if (isStdCharSpecialization(SD
, "basic_istream", /*HasAllocator=*/false)) {
7012 // <substitution> ::= So # ::std::basic_ostream<char,
7013 // ::std::char_traits<char> >
7014 if (isStdCharSpecialization(SD
, "basic_ostream", /*HasAllocator=*/false)) {
7019 // <substitution> ::= Sd # ::std::basic_iostream<char,
7020 // ::std::char_traits<char> >
7021 if (isStdCharSpecialization(SD
, "basic_iostream", /*HasAllocator=*/false)) {
7031 void CXXNameMangler::addSubstitution(QualType T
) {
7032 if (!hasMangledSubstitutionQualifiers(T
)) {
7033 if (const RecordType
*RT
= T
->getAs
<RecordType
>()) {
7034 addSubstitution(RT
->getDecl());
7039 uintptr_t TypePtr
= reinterpret_cast<uintptr_t>(T
.getAsOpaquePtr());
7040 addSubstitution(TypePtr
);
7043 void CXXNameMangler::addSubstitution(TemplateName Template
) {
7044 if (TemplateDecl
*TD
= Template
.getAsTemplateDecl())
7045 return addSubstitution(TD
);
7047 Template
= Context
.getASTContext().getCanonicalTemplateName(Template
);
7048 addSubstitution(reinterpret_cast<uintptr_t>(Template
.getAsVoidPointer()));
7051 void CXXNameMangler::addSubstitution(uintptr_t Ptr
) {
7052 assert(!Substitutions
.count(Ptr
) && "Substitution already exists!");
7053 Substitutions
[Ptr
] = SeqID
++;
7056 void CXXNameMangler::extendSubstitutions(CXXNameMangler
* Other
) {
7057 assert(Other
->SeqID
>= SeqID
&& "Must be superset of substitutions!");
7058 if (Other
->SeqID
> SeqID
) {
7059 Substitutions
.swap(Other
->Substitutions
);
7060 SeqID
= Other
->SeqID
;
7064 CXXNameMangler::AbiTagList
7065 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl
*FD
) {
7066 // When derived abi tags are disabled there is no need to make any list.
7067 if (DisableDerivedAbiTags
)
7068 return AbiTagList();
7070 llvm::raw_null_ostream NullOutStream
;
7071 CXXNameMangler
TrackReturnTypeTags(*this, NullOutStream
);
7072 TrackReturnTypeTags
.disableDerivedAbiTags();
7074 const FunctionProtoType
*Proto
=
7075 cast
<FunctionProtoType
>(FD
->getType()->getAs
<FunctionType
>());
7076 FunctionTypeDepthState saved
= TrackReturnTypeTags
.FunctionTypeDepth
.push();
7077 TrackReturnTypeTags
.FunctionTypeDepth
.enterResultType();
7078 TrackReturnTypeTags
.mangleType(Proto
->getReturnType());
7079 TrackReturnTypeTags
.FunctionTypeDepth
.leaveResultType();
7080 TrackReturnTypeTags
.FunctionTypeDepth
.pop(saved
);
7082 return TrackReturnTypeTags
.AbiTagsRoot
.getSortedUniqueUsedAbiTags();
7085 CXXNameMangler::AbiTagList
7086 CXXNameMangler::makeVariableTypeTags(const VarDecl
*VD
) {
7087 // When derived abi tags are disabled there is no need to make any list.
7088 if (DisableDerivedAbiTags
)
7089 return AbiTagList();
7091 llvm::raw_null_ostream NullOutStream
;
7092 CXXNameMangler
TrackVariableType(*this, NullOutStream
);
7093 TrackVariableType
.disableDerivedAbiTags();
7095 TrackVariableType
.mangleType(VD
->getType());
7097 return TrackVariableType
.AbiTagsRoot
.getSortedUniqueUsedAbiTags();
7100 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl
&C
,
7101 const VarDecl
*VD
) {
7102 llvm::raw_null_ostream NullOutStream
;
7103 CXXNameMangler
TrackAbiTags(C
, NullOutStream
, nullptr, true);
7104 TrackAbiTags
.mangle(VD
);
7105 return TrackAbiTags
.AbiTagsRoot
.getUsedAbiTags().size();
7110 /// Mangles the name of the declaration D and emits that name to the given
7113 /// If the declaration D requires a mangled name, this routine will emit that
7114 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
7115 /// and this routine will return false. In this case, the caller should just
7116 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
7118 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD
,
7120 const NamedDecl
*D
= cast
<NamedDecl
>(GD
.getDecl());
7121 assert((isa
<FunctionDecl
, VarDecl
, TemplateParamObjectDecl
>(D
)) &&
7122 "Invalid mangleName() call, argument is not a variable or function!");
7124 PrettyStackTraceDecl
CrashInfo(D
, SourceLocation(),
7125 getASTContext().getSourceManager(),
7126 "Mangling declaration");
7128 if (auto *CD
= dyn_cast
<CXXConstructorDecl
>(D
)) {
7129 auto Type
= GD
.getCtorType();
7130 CXXNameMangler
Mangler(*this, Out
, CD
, Type
);
7131 return Mangler
.mangle(GlobalDecl(CD
, Type
));
7134 if (auto *DD
= dyn_cast
<CXXDestructorDecl
>(D
)) {
7135 auto Type
= GD
.getDtorType();
7136 CXXNameMangler
Mangler(*this, Out
, DD
, Type
);
7137 return Mangler
.mangle(GlobalDecl(DD
, Type
));
7140 CXXNameMangler
Mangler(*this, Out
, D
);
7144 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl
*D
,
7146 CXXNameMangler
Mangler(*this, Out
, D
, Ctor_Comdat
);
7147 Mangler
.mangle(GlobalDecl(D
, Ctor_Comdat
));
7150 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl
*D
,
7152 CXXNameMangler
Mangler(*this, Out
, D
, Dtor_Comdat
);
7153 Mangler
.mangle(GlobalDecl(D
, Dtor_Comdat
));
7156 /// Mangles the pointer authentication override attribute for classes
7157 /// that have explicit overrides for the vtable authentication schema.
7159 /// The override is mangled as a parameterized vendor extension as follows
7161 /// <type> ::= U "__vtptrauth" I
7163 /// <addressDiscriminated>
7164 /// <extraDiscriminator>
7167 /// The extra discriminator encodes the explicit value derived from the
7168 /// override schema, e.g. if the override has specified type based
7169 /// discrimination the encoded value will be the discriminator derived from the
7171 static void mangleOverrideDiscrimination(CXXNameMangler
&Mangler
,
7172 ASTContext
&Context
,
7173 const ThunkInfo
&Thunk
) {
7174 auto &LangOpts
= Context
.getLangOpts();
7175 const CXXRecordDecl
*ThisRD
= Thunk
.ThisType
->getPointeeCXXRecordDecl();
7176 const CXXRecordDecl
*PtrauthClassRD
=
7177 Context
.baseForVTableAuthentication(ThisRD
);
7178 unsigned TypedDiscriminator
=
7179 Context
.getPointerAuthVTablePointerDiscriminator(ThisRD
);
7180 Mangler
.mangleVendorQualifier("__vtptrauth");
7181 auto &ManglerStream
= Mangler
.getStream();
7182 ManglerStream
<< "I";
7183 if (const auto *ExplicitAuth
=
7184 PtrauthClassRD
->getAttr
<VTablePointerAuthenticationAttr
>()) {
7185 ManglerStream
<< "Lj" << ExplicitAuth
->getKey();
7187 if (ExplicitAuth
->getAddressDiscrimination() ==
7188 VTablePointerAuthenticationAttr::DefaultAddressDiscrimination
)
7189 ManglerStream
<< "Lb" << LangOpts
.PointerAuthVTPtrAddressDiscrimination
;
7191 ManglerStream
<< "Lb"
7192 << (ExplicitAuth
->getAddressDiscrimination() ==
7193 VTablePointerAuthenticationAttr::AddressDiscrimination
);
7195 switch (ExplicitAuth
->getExtraDiscrimination()) {
7196 case VTablePointerAuthenticationAttr::DefaultExtraDiscrimination
: {
7197 if (LangOpts
.PointerAuthVTPtrTypeDiscrimination
)
7198 ManglerStream
<< "Lj" << TypedDiscriminator
;
7200 ManglerStream
<< "Lj" << 0;
7203 case VTablePointerAuthenticationAttr::TypeDiscrimination
:
7204 ManglerStream
<< "Lj" << TypedDiscriminator
;
7206 case VTablePointerAuthenticationAttr::CustomDiscrimination
:
7207 ManglerStream
<< "Lj" << ExplicitAuth
->getCustomDiscriminationValue();
7209 case VTablePointerAuthenticationAttr::NoExtraDiscrimination
:
7210 ManglerStream
<< "Lj" << 0;
7214 ManglerStream
<< "Lj"
7215 << (unsigned)VTablePointerAuthenticationAttr::DefaultKey
;
7216 ManglerStream
<< "Lb" << LangOpts
.PointerAuthVTPtrAddressDiscrimination
;
7217 if (LangOpts
.PointerAuthVTPtrTypeDiscrimination
)
7218 ManglerStream
<< "Lj" << TypedDiscriminator
;
7220 ManglerStream
<< "Lj" << 0;
7222 ManglerStream
<< "E";
7225 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl
*MD
,
7226 const ThunkInfo
&Thunk
,
7227 bool ElideOverrideInfo
,
7229 // <special-name> ::= T <call-offset> <base encoding>
7230 // # base is the nominal target function of thunk
7231 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
7232 // # base is the nominal target function of thunk
7233 // # first call-offset is 'this' adjustment
7234 // # second call-offset is result adjustment
7236 assert(!isa
<CXXDestructorDecl
>(MD
) &&
7237 "Use mangleCXXDtor for destructor decls!");
7238 CXXNameMangler
Mangler(*this, Out
);
7239 Mangler
.getStream() << "_ZT";
7240 if (!Thunk
.Return
.isEmpty())
7241 Mangler
.getStream() << 'c';
7243 // Mangle the 'this' pointer adjustment.
7244 Mangler
.mangleCallOffset(Thunk
.This
.NonVirtual
,
7245 Thunk
.This
.Virtual
.Itanium
.VCallOffsetOffset
);
7247 // Mangle the return pointer adjustment if there is one.
7248 if (!Thunk
.Return
.isEmpty())
7249 Mangler
.mangleCallOffset(Thunk
.Return
.NonVirtual
,
7250 Thunk
.Return
.Virtual
.Itanium
.VBaseOffsetOffset
);
7252 Mangler
.mangleFunctionEncoding(MD
);
7253 if (!ElideOverrideInfo
)
7254 mangleOverrideDiscrimination(Mangler
, getASTContext(), Thunk
);
7257 void ItaniumMangleContextImpl::mangleCXXDtorThunk(const CXXDestructorDecl
*DD
,
7259 const ThunkInfo
&Thunk
,
7260 bool ElideOverrideInfo
,
7262 // <special-name> ::= T <call-offset> <base encoding>
7263 // # base is the nominal target function of thunk
7264 CXXNameMangler
Mangler(*this, Out
, DD
, Type
);
7265 Mangler
.getStream() << "_ZT";
7267 auto &ThisAdjustment
= Thunk
.This
;
7268 // Mangle the 'this' pointer adjustment.
7269 Mangler
.mangleCallOffset(ThisAdjustment
.NonVirtual
,
7270 ThisAdjustment
.Virtual
.Itanium
.VCallOffsetOffset
);
7272 Mangler
.mangleFunctionEncoding(GlobalDecl(DD
, Type
));
7273 if (!ElideOverrideInfo
)
7274 mangleOverrideDiscrimination(Mangler
, getASTContext(), Thunk
);
7277 /// Returns the mangled name for a guard variable for the passed in VarDecl.
7278 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl
*D
,
7280 // <special-name> ::= GV <object name> # Guard variable for one-time
7282 CXXNameMangler
Mangler(*this, Out
);
7283 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
7284 // be a bug that is fixed in trunk.
7285 Mangler
.getStream() << "_ZGV";
7286 Mangler
.mangleName(D
);
7289 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl
*MD
,
7291 // These symbols are internal in the Itanium ABI, so the names don't matter.
7292 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
7293 // avoid duplicate symbols.
7294 Out
<< "__cxx_global_var_init";
7297 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl
*D
,
7299 // Prefix the mangling of D with __dtor_.
7300 CXXNameMangler
Mangler(*this, Out
);
7301 Mangler
.getStream() << "__dtor_";
7302 if (shouldMangleDeclName(D
))
7305 Mangler
.getStream() << D
->getName();
7308 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl
*D
,
7310 // Clang generates these internal-linkage functions as part of its
7311 // implementation of the XL ABI.
7312 CXXNameMangler
Mangler(*this, Out
);
7313 Mangler
.getStream() << "__finalize_";
7314 if (shouldMangleDeclName(D
))
7317 Mangler
.getStream() << D
->getName();
7320 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
7321 GlobalDecl EnclosingDecl
, raw_ostream
&Out
) {
7322 CXXNameMangler
Mangler(*this, Out
);
7323 Mangler
.getStream() << "__filt_";
7324 auto *EnclosingFD
= cast
<FunctionDecl
>(EnclosingDecl
.getDecl());
7325 if (shouldMangleDeclName(EnclosingFD
))
7326 Mangler
.mangle(EnclosingDecl
);
7328 Mangler
.getStream() << EnclosingFD
->getName();
7331 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
7332 GlobalDecl EnclosingDecl
, raw_ostream
&Out
) {
7333 CXXNameMangler
Mangler(*this, Out
);
7334 Mangler
.getStream() << "__fin_";
7335 auto *EnclosingFD
= cast
<FunctionDecl
>(EnclosingDecl
.getDecl());
7336 if (shouldMangleDeclName(EnclosingFD
))
7337 Mangler
.mangle(EnclosingDecl
);
7339 Mangler
.getStream() << EnclosingFD
->getName();
7342 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl
*D
,
7344 // <special-name> ::= TH <object name>
7345 CXXNameMangler
Mangler(*this, Out
);
7346 Mangler
.getStream() << "_ZTH";
7347 Mangler
.mangleName(D
);
7351 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl
*D
,
7353 // <special-name> ::= TW <object name>
7354 CXXNameMangler
Mangler(*this, Out
);
7355 Mangler
.getStream() << "_ZTW";
7356 Mangler
.mangleName(D
);
7359 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl
*D
,
7360 unsigned ManglingNumber
,
7362 // We match the GCC mangling here.
7363 // <special-name> ::= GR <object name>
7364 CXXNameMangler
Mangler(*this, Out
);
7365 Mangler
.getStream() << "_ZGR";
7366 Mangler
.mangleName(D
);
7367 assert(ManglingNumber
> 0 && "Reference temporary mangling number is zero!");
7368 Mangler
.mangleSeqID(ManglingNumber
- 1);
7371 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl
*RD
,
7373 // <special-name> ::= TV <type> # virtual table
7374 CXXNameMangler
Mangler(*this, Out
);
7375 Mangler
.getStream() << "_ZTV";
7376 Mangler
.mangleCXXRecordDecl(RD
);
7379 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl
*RD
,
7381 // <special-name> ::= TT <type> # VTT structure
7382 CXXNameMangler
Mangler(*this, Out
);
7383 Mangler
.getStream() << "_ZTT";
7384 Mangler
.mangleCXXRecordDecl(RD
);
7387 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl
*RD
,
7389 const CXXRecordDecl
*Type
,
7391 // <special-name> ::= TC <type> <offset number> _ <base type>
7392 CXXNameMangler
Mangler(*this, Out
);
7393 Mangler
.getStream() << "_ZTC";
7394 Mangler
.mangleCXXRecordDecl(RD
);
7395 Mangler
.getStream() << Offset
;
7396 Mangler
.getStream() << '_';
7397 Mangler
.mangleCXXRecordDecl(Type
);
7400 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty
, raw_ostream
&Out
) {
7401 // <special-name> ::= TI <type> # typeinfo structure
7402 assert(!Ty
.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
7403 CXXNameMangler
Mangler(*this, Out
);
7404 Mangler
.getStream() << "_ZTI";
7405 Mangler
.mangleType(Ty
);
7408 void ItaniumMangleContextImpl::mangleCXXRTTIName(
7409 QualType Ty
, raw_ostream
&Out
, bool NormalizeIntegers
= false) {
7410 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
7411 CXXNameMangler
Mangler(*this, Out
, NormalizeIntegers
);
7412 Mangler
.getStream() << "_ZTS";
7413 Mangler
.mangleType(Ty
);
7416 void ItaniumMangleContextImpl::mangleCanonicalTypeName(
7417 QualType Ty
, raw_ostream
&Out
, bool NormalizeIntegers
= false) {
7418 mangleCXXRTTIName(Ty
, Out
, NormalizeIntegers
);
7421 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral
*, raw_ostream
&) {
7422 llvm_unreachable("Can't mangle string literals");
7425 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl
*Lambda
,
7427 CXXNameMangler
Mangler(*this, Out
);
7428 Mangler
.mangleLambdaSig(Lambda
);
7431 void ItaniumMangleContextImpl::mangleModuleInitializer(const Module
*M
,
7433 // <special-name> ::= GI <module-name> # module initializer function
7434 CXXNameMangler
Mangler(*this, Out
);
7435 Mangler
.getStream() << "_ZGI";
7436 Mangler
.mangleModuleNamePrefix(M
->getPrimaryModuleInterfaceName());
7437 if (M
->isModulePartition()) {
7438 // The partition needs including, as partitions can have them too.
7439 auto Partition
= M
->Name
.find(':');
7440 Mangler
.mangleModuleNamePrefix(
7441 StringRef(&M
->Name
[Partition
+ 1], M
->Name
.size() - Partition
- 1),
7442 /*IsPartition*/ true);
7446 ItaniumMangleContext
*ItaniumMangleContext::create(ASTContext
&Context
,
7447 DiagnosticsEngine
&Diags
,
7449 return new ItaniumMangleContextImpl(
7451 [](ASTContext
&, const NamedDecl
*) -> std::optional
<unsigned> {
7452 return std::nullopt
;
7457 ItaniumMangleContext
*
7458 ItaniumMangleContext::create(ASTContext
&Context
, DiagnosticsEngine
&Diags
,
7459 DiscriminatorOverrideTy DiscriminatorOverride
,
7461 return new ItaniumMangleContextImpl(Context
, Diags
, DiscriminatorOverride
,