[NFC][Fuzzer] Extract CreateGateBranch method. (#117236)
[llvm-project.git] / clang / lib / AST / ItaniumMangle.cpp
blob27a993a631dae9c0050830333914c47b154f9b3a
1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implements C++ name mangling according to the Itanium C++ ABI,
10 // which is used in GCC 3.2 and newer (and many compilers that are
11 // ABI-compatible with GCC):
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"
38 #include <optional>
40 using namespace clang;
42 namespace {
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();
52 return fn;
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);
62 if (!Record)
63 return false;
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;
79 public:
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
87 /// @{
89 bool shouldMangleCXXName(const NamedDecl *D) override;
90 bool shouldMangleStringLiteral(const StringLiteral *) override {
91 return false;
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.
139 if (isLambda(ND))
140 return false;
142 // Anonymous tags are already numbered.
143 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
144 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
145 return false;
148 // Use the canonical number for externally visible decls.
149 if (ND->isExternallyVisible()) {
150 unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
151 if (discriminator == 1)
152 return false;
153 disc = discriminator - 2;
154 return true;
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)
164 return false;
165 disc = discriminator-2;
166 return true;
169 std::string getLambdaString(const CXXRecordDecl *Lambda) override {
170 // This function matches the one in MicrosoftMangle, which returns
171 // the string that is used in lambda mangled names.
172 assert(Lambda->isLambda() && "RD must be a lambda!");
173 std::string Name("<lambda");
174 Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
175 unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
176 unsigned LambdaId;
177 const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
178 const FunctionDecl *Func =
179 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
181 if (Func) {
182 unsigned DefaultArgNo =
183 Func->getNumParams() - Parm->getFunctionScopeIndex();
184 Name += llvm::utostr(DefaultArgNo);
185 Name += "_";
188 if (LambdaManglingNumber)
189 LambdaId = LambdaManglingNumber;
190 else
191 LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
193 Name += llvm::utostr(LambdaId);
194 Name += '>';
195 return Name;
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);
211 /// @}
214 /// Manage the mangling of a single name.
215 class CXXNameMangler {
216 ItaniumMangleContextImpl &Context;
217 raw_ostream &Out;
218 /// Normalize integer types for cross-language CFI support with other
219 /// languages that can't represent and encode C/C++ integer types.
220 bool NormalizeIntegers = false;
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.
241 unsigned SeqID = 0;
243 class FunctionTypeDepthState {
244 unsigned Bits = 0;
246 enum { InResultTypeMask = 1 };
248 public:
249 FunctionTypeDepthState() = default;
251 /// The number of function types we're inside.
252 unsigned getDepth() const {
253 return Bits >> 1;
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;
264 return tmp;
267 void enterResultType() {
268 Bits |= InResultTypeMask;
271 void leaveResultType() {
272 Bits &= ~InResultTypeMask;
275 void pop(FunctionTypeDepthState saved) {
276 assert(getDepth() == saved.getDepth() + 1);
277 Bits = saved.Bits;
280 } FunctionTypeDepth;
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
290 // track.
291 class AbiTagState final {
292 public:
293 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
294 Parent = LinkHead;
295 LinkHead = this;
298 // No copy, no move.
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)) {
308 assert(
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.
317 return;
321 AbiTagList TagList;
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());
336 llvm::sort(TagList);
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()),
354 UsedAbiTags.end());
355 return UsedAbiTags;
358 private:
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;
367 void pop() {
368 assert(LinkHead == this &&
369 "abi tag link head must point to us on destruction");
370 if (Parent) {
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());
377 LinkHead = Parent;
380 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
381 for (const auto &Tag : AbiTags) {
382 EmittedAbiTags.push_back(Tag);
383 Out << "B";
384 Out << Tag.size();
385 Out << 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);
410 public:
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_) {
441 NullOut = true;
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);
471 private:
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,
617 TemplateArgument A);
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() {
639 if (!StdNamespace) {
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();
647 return StdNamespace;
650 /// Retrieve the declaration context that should be used when mangling the given
651 /// declaration.
652 const DeclContext *
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)) {
661 if (RD->isLambda())
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))
692 if (VD->isExternC())
693 return getASTContext().getTranslationUnitDecl();
695 if (const auto *FD = getASTContext().getLangOpts().getClangABICompat() >
696 LangOptions::ClangABI::Ver19
697 ? D->getAsFunction()
698 : dyn_cast<FunctionDecl>(D)) {
699 if (FD->isExternC())
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())
717 return true;
718 return false;
721 // Check if this Function Decl needs a unique internal linkage name.
722 bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
723 const NamedDecl *ND) {
724 if (!NeedsUniqueInternalLinkageNames || !ND)
725 return false;
727 const auto *FD = dyn_cast<FunctionDecl>(ND);
728 if (!FD)
729 return false;
731 // For C functions without prototypes, return false as their
732 // names should not be mangled.
733 if (!FD->getType()->getAs<FunctionProtoType>())
734 return false;
736 if (isInternalLinkageDecl(ND))
737 return true;
739 return false;
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>())
747 return true;
749 // "main" is not mangled.
750 if (FD->isMain())
751 return false;
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())
763 return false;
765 // C++ functions and those whose names are not a simple identifier need
766 // mangling.
767 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
768 return true;
770 // C functions are not mangled.
771 if (L == CLanguageLinkage)
772 return false;
775 // Otherwise, no mangling is done outside C++ mode.
776 if (!getASTContext().getLangOpts().CPlusPlus)
777 return false;
779 if (const auto *VD = dyn_cast<VarDecl>(D)) {
780 // Decompositions are mangled.
781 if (isa<DecompositionDecl>(VD))
782 return true;
784 // C variables are not mangled.
785 if (VD->isExternC())
786 return false;
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())
799 return false;
802 return true;
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>
819 // ::= <data name>
820 // ::= <special-name>
821 Out << "_Z";
822 if (isa<FunctionDecl>(GD.getDecl()))
823 mangleFunctionEncoding(GD);
824 else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
825 BindingDecl>(GD.getDecl()))
826 mangleName(GD);
827 else if (const IndirectFieldDecl *IFD =
828 dyn_cast<IndirectFieldDecl>(GD.getDecl()))
829 mangleName(IFD->getAnonField());
830 else
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)) {
840 mangleName(GD);
841 return;
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();
855 mangleName(GD);
856 FunctionTypeDepth.pop(Saved);
857 mangleFunctionEncodingBareType(FD);
858 return;
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
879 // encoding.
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();
906 I != E; ++I) {
907 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
908 if (!EIA)
909 continue;
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
913 // <expr-primary>.
914 Out << 'X';
915 mangleExpression(EIA->getCond());
916 Out << 'E';
917 } else {
918 mangleTemplateArgExpr(EIA->getCond());
921 Out << 'E';
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
944 // 1. Constructors.
945 // 2. Destructors.
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())
964 return false;
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'
971 // namespace.
972 bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
973 if (!DC->isNamespace())
974 return false;
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);
1020 return;
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);
1041 } else {
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);
1051 D = cast<Decl>(DC);
1052 DC = Context.getEffectiveDeclContext(D);
1054 return nullptr;
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>
1063 // ::= <local-name>
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);
1078 return;
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);
1087 return;
1090 if (isLocalContainerContext(DC)) {
1091 mangleLocalName(GD, AdditionalAbiTags);
1092 return;
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);
1101 return;
1104 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1105 return;
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()) {
1126 Out << 'S';
1127 mangleSeqID(It->second);
1128 return;
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;
1136 else {
1137 mangleModuleNamePrefix(Parts.first, IsPartition);
1138 IsPartition = false;
1141 Out << 'W';
1142 if (IsPartition)
1143 Out << 'P';
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);
1155 } else {
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;
1178 return;
1183 Out << "St";
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))
1195 return;
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);
1204 } else {
1205 mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
1206 AdditionalAbiTags);
1209 addSubstitution(ND);
1212 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1213 // ABI:
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
1218 // on Itanium.
1219 // The 'without leading zeroes' thing seems to be an editorial
1220 // mistake; see the discussion on cxx-abi-dev beginning on
1221 // 2012-01-16.
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);
1241 hexDigit &= 0xF;
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) {
1255 Out << 'L';
1256 mangleType(T);
1257 mangleFloat(V);
1258 Out << 'E';
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
1270 Out << 'L';
1271 mangleType(T);
1272 Out << "0E";
1275 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1276 if (Value.isSigned() && Value.isNegative()) {
1277 Out << 'n';
1278 Value.abs().print(Out, /*signed*/ false);
1279 } else {
1280 Value.print(Out, /*signed*/ false);
1284 void CXXNameMangler::mangleNumber(int64_t Number) {
1285 // <number> ::= [n] <non-negative decimal integer>
1286 if (Number < 0) {
1287 Out << 'n';
1288 Number = -Number;
1291 Out << Number;
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
1300 if (!Virtual) {
1301 Out << 'h';
1302 mangleNumber(NonVirtual);
1303 Out << '_';
1304 return;
1307 Out << 'v';
1308 mangleNumber(NonVirtual);
1309 Out << '_';
1310 mangleNumber(Virtual);
1311 Out << '_';
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));
1338 } else {
1339 // We use the QualType mangle type variant here because it handles
1340 // substitutions.
1341 mangleType(type);
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,
1350 bool recursive) {
1352 // x, ::x
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:
1368 Out << "gs";
1370 // We want an 'sr' unless this is the entire NNS.
1371 if (recursive)
1372 Out << "sr";
1374 // We never want an 'E' here.
1375 return;
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);
1384 else
1385 Out << "sr";
1386 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1387 break;
1388 case NestedNameSpecifier::NamespaceAlias:
1389 if (qualifier->getPrefix())
1390 mangleUnresolvedPrefix(qualifier->getPrefix(),
1391 /*recursive*/ true);
1392 else
1393 Out << "sr";
1394 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1395 break;
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:
1402 // - a decltype
1403 // - a template type parameter
1404 // - a template template parameter with arguments
1405 // In all of these cases, we should have no prefix.
1406 if (qualifier->getPrefix()) {
1407 mangleUnresolvedPrefix(qualifier->getPrefix(),
1408 /*recursive*/ true);
1409 } else {
1410 // Otherwise, all the cases want this.
1411 Out << "sr";
1414 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1415 return;
1417 break;
1420 case NestedNameSpecifier::Identifier:
1421 // Member expressions can have these without prefixes.
1422 if (qualifier->getPrefix())
1423 mangleUnresolvedPrefix(qualifier->getPrefix(),
1424 /*recursive*/ true);
1425 else
1426 Out << "sr";
1428 mangleSourceName(qualifier->getAsIdentifier());
1429 // An Identifier has no type information, so we can't emit abi tags for it.
1430 break;
1433 // If this was the innermost part of the NNS, and we fell out to
1434 // here, append an 'E'.
1435 if (!recursive)
1436 Out << '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());
1450 break;
1451 // <base-unresolved-name> ::= dn <destructor-name>
1452 case DeclarationName::CXXDestructorName:
1453 Out << "dn";
1454 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1455 break;
1456 // <base-unresolved-name> ::= on <operator-name>
1457 case DeclarationName::CXXConversionFunctionName:
1458 case DeclarationName::CXXLiteralOperatorName:
1459 case DeclarationName::CXXOperatorName:
1460 Out << "on";
1461 mangleOperatorName(name, knownArity);
1462 break;
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
1476 // <template-args>.
1477 if (TemplateArgs)
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))
1500 Out << 'F';
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
1515 Out << "DC";
1516 for (auto *BD : DD->bindings())
1517 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1518 Out << 'E';
1519 writeAbiTags(ND, AdditionalAbiTags);
1520 break;
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;
1530 break;
1533 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1534 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1535 Out << "TA";
1536 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1537 TPO->getValue(), /*TopLevel=*/true);
1538 break;
1541 if (II) {
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
1546 // to DR426:
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))
1556 Out << 'L';
1558 bool IsRegCall = FD &&
1559 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1560 clang::CC_X86RegCall;
1561 bool IsDeviceStub =
1562 FD && FD->hasAttr<CUDAGlobalAttr>() &&
1563 GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1564 if (IsDeviceStub)
1565 mangleDeviceStubName(II);
1566 else if (IsRegCall)
1567 mangleRegCallName(II);
1568 else
1569 mangleSourceName(II);
1571 writeAbiTags(ND, AdditionalAbiTags);
1572 break;
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";
1582 break;
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.
1606 if (!FD) break;
1607 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1609 mangleSourceName(FD->getIdentifier());
1610 // Not emitting abi tags: internal name anyway.
1611 break;
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))
1621 break;
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
1633 // from typedef.
1634 writeAbiTags(TD, nullptr);
1635 break;
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
1650 // lambda.
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);
1657 break;
1661 if (TD->isExternallyVisible()) {
1662 unsigned UnnamedMangle =
1663 getASTContext().getManglingNumber(TD, Context.isAux());
1664 Out << "Ut";
1665 if (UnnamedMangle > 1)
1666 Out << UnnamedMangle - 2;
1667 Out << '_';
1668 writeAbiTags(TD, AdditionalAbiTags);
1669 break;
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 =
1675 NullOut ? 0
1676 : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));
1678 // Mangle it as a source name in the form
1679 // [n] $_<id>
1680 // where n is the length of the string.
1681 SmallString<8> Str;
1682 Str += "$_";
1683 Str += llvm::utostr(AnonStructId);
1685 Out << Str.size();
1686 Out << Str;
1687 break;
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();
1708 if (ND == Structor)
1709 // If the named decl is the C++ constructor we're mangling, use the type
1710 // we were given.
1711 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1712 else
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);
1723 break;
1726 case DeclarationName::CXXDestructorName:
1727 if (ND == Structor)
1728 // If the named decl is the C++ destructor we're mangling, use the type we
1729 // were given.
1730 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1731 else
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);
1735 assert(ND);
1736 writeAbiTags(ND, AdditionalAbiTags);
1737 break;
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())
1746 Arity++;
1748 [[fallthrough]];
1749 case DeclarationName::CXXConversionFunctionName:
1750 case DeclarationName::CXXLiteralOperatorName:
1751 mangleOperatorName(Name, Arity);
1752 writeAbiTags(ND, AdditionalAbiTags);
1753 break;
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__"
1769 << II->getName();
1770 else
1771 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1772 << II->getName();
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__"
1780 << II->getName();
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,
1793 bool NoFunction) {
1794 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1795 // <nested-name>
1796 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1797 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1798 // <template-args> E
1800 Out << 'N';
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())
1806 Out << 'H';
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);
1817 } else {
1818 manglePrefix(DC, NoFunction);
1819 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1822 Out << 'E';
1824 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1825 ArrayRef<TemplateArgument> Args) {
1826 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1828 Out << 'N';
1830 mangleTemplatePrefix(TD);
1831 mangleTemplateArgs(asTemplateName(TD), Args);
1833 Out << 'E';
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
1845 Out << 'N';
1847 mangleClosurePrefix(PrefixND);
1848 mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1850 Out << 'E';
1853 static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
1854 GlobalDecl GD;
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);
1863 else
1864 GD = GlobalDecl(cast<FunctionDecl>(DC));
1865 return GD;
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> ]
1874 // _ <entity name>
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);
1880 Out << 'Z';
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);
1889 else
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());
1897 Out << 'E';
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.
1902 if (RD) {
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())) {
1914 Out << 'd';
1915 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1916 if (Num > 1)
1917 mangleNumber(Num - 2);
1918 Out << '_';
1923 // Mangle the name relative to the closest enclosing function.
1924 // equality ok because RD derived from ND above
1925 if (D == RD) {
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*/);
1930 else
1931 manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
1932 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1933 mangleUnqualifiedBlock(BD);
1934 } else {
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
1941 // lambdas.
1942 if (const ParmVarDecl *Parm
1943 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1944 if (const FunctionDecl *Func
1945 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1946 Out << 'd';
1947 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1948 if (Num > 1)
1949 mangleNumber(Num - 2);
1950 Out << '_';
1954 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1955 mangleUnqualifiedBlock(BD);
1956 } else {
1957 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1960 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1961 unsigned disc;
1962 if (Context.getNextDiscriminator(ND, disc)) {
1963 if (disc < 10)
1964 Out << '_' << disc;
1965 else
1966 Out << "__" << disc << '_';
1971 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1972 if (GetLocalClassDecl(Block)) {
1973 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1974 return;
1976 const DeclContext *DC = Context.getEffectiveDeclContext(Block);
1977 if (isLocalContainerContext(DC)) {
1978 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1979 return;
1981 if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1982 mangleClosurePrefix(PrefixND);
1983 else
1984 manglePrefix(DC);
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);
1998 Out << 'M';
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.
2007 if (!Number)
2008 Number = Context.getBlockId(Block, false);
2009 else {
2010 // Stored mangling numbers are 1-based.
2011 --Number;
2013 Out << "Ub";
2014 if (Number > 0)
2015 Out << Number - 1;
2016 Out << '_';
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())
2030 Out << "Tp";
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.
2034 Out << "Tk";
2035 mangleTypeConstraint(Constraint);
2036 } else {
2037 Out << "Ty";
2039 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
2040 if (Tn->isExpandedParameterPack()) {
2041 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
2042 Out << "Tn";
2043 mangleType(Tn->getExpansionType(I));
2045 } else {
2046 QualType T = Tn->getType();
2047 if (Tn->isParameterPack()) {
2048 Out << "Tp";
2049 if (auto *PackExpansion = T->getAs<PackExpansionType>())
2050 T = PackExpansion->getPattern();
2052 Out << "Tn";
2053 mangleType(T);
2055 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
2056 if (Tt->isExpandedParameterPack()) {
2057 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
2058 ++I)
2059 mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I));
2060 } else {
2061 if (Tt->isParameterPack())
2062 Out << "Tp";
2063 mangleTemplateParameterList(Tt->getTemplateParameters());
2068 void CXXNameMangler::mangleTemplateParameterList(
2069 const TemplateParameterList *Params) {
2070 Out << "Tt";
2071 for (auto *Param : *Params)
2072 mangleTemplateParamDecl(Param);
2073 mangleRequiresClause(Params->getRequiresClause());
2074 Out << "E";
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);
2084 else
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)) {
2101 Out << 'Q';
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);
2119 Out << 'M';
2124 Out << "Ul";
2125 mangleLambdaSig(Lambda);
2126 Out << "E";
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);
2141 unsigned Number =
2142 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2144 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
2145 if (Number > 1)
2146 mangleNumber(Number - 2);
2147 Out << '_';
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());
2159 auto *Proto =
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:
2168 // nothing
2169 return;
2171 case NestedNameSpecifier::Super:
2172 llvm_unreachable("Can't mangle __super specifier");
2174 case NestedNameSpecifier::Namespace:
2175 mangleName(qualifier->getAsNamespace());
2176 return;
2178 case NestedNameSpecifier::NamespaceAlias:
2179 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
2180 return;
2182 case NestedNameSpecifier::TypeSpec:
2183 case NestedNameSpecifier::TypeSpecWithTemplate:
2184 manglePrefix(QualType(qualifier->getAsType(), 0));
2185 return;
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))
2191 return;
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());
2200 if (!Clang14Compat)
2201 addSubstitution(qualifier);
2202 return;
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>
2213 // ::= # empty
2214 // ::= <substitution>
2216 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
2218 if (DC->isTranslationUnit())
2219 return;
2221 if (NoFunction && isLocalContainerContext(DC))
2222 return;
2224 const NamedDecl *ND = cast<NamedDecl>(DC);
2225 if (mangleSubstitution(ND))
2226 return;
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);
2236 } else {
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))
2259 return;
2261 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
2262 manglePrefix(Qualifier);
2264 if (Clang11Compat && mangleSubstitution(Template))
2265 return;
2267 if (const IdentifierInfo *Id = Dependent->getIdentifier())
2268 mangleSourceName(Id);
2269 else
2270 mangleOperatorName(Dependent->getOperator(), UnknownArity);
2272 addSubstitution(Template);
2275 void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2276 bool NoFunction) {
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>
2282 // <substitution>
2284 if (mangleSubstitution(ND))
2285 return;
2287 // <template-template-param> ::= <template-param>
2288 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2289 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2290 } else {
2291 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2292 manglePrefix(DC, NoFunction);
2293 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
2294 mangleUnqualifiedName(GD, DC, nullptr);
2295 else
2296 mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
2297 nullptr);
2300 addSubstitution(ND);
2303 const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2304 if (isCompatibleWith(LangOptions::ClangABI::Ver12))
2305 return nullptr;
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)) {
2311 if (RD->isLambda())
2312 Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2314 if (!Context)
2315 return nullptr;
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))
2321 return Context;
2323 return nullptr;
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))
2330 return;
2332 const TemplateArgumentList *TemplateArgs = nullptr;
2333 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2334 mangleTemplatePrefix(TD, NoFunction);
2335 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2336 } else {
2337 const auto *DC = Context.getEffectiveDeclContext(ND);
2338 manglePrefix(DC, NoFunction);
2339 mangleUnqualifiedName(ND, DC, nullptr);
2342 Out << 'M';
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))
2354 return;
2356 TemplateDecl *TD = nullptr;
2358 switch (TN.getKind()) {
2359 case TemplateName::QualifiedTemplate:
2360 case TemplateName::UsingTemplate:
2361 case TemplateName::Template:
2362 TD = TN.getAsTemplateDecl();
2363 goto HaveDecl;
2365 HaveDecl:
2366 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2367 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2368 else
2369 mangleName(TD);
2370 break;
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());
2384 break;
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());
2395 return;
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...);
2402 // };
2403 Out << "_SUBSTPACK_";
2404 break;
2406 case TemplateName::DeducedTemplate:
2407 llvm_unreachable("Unexpected DeducedTemplate");
2410 addSubstitution(TN);
2413 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2414 StringRef Prefix) {
2415 // Only certain other types are valid as prefixes; enumerate them.
2416 switch (Ty->getTypeClass()) {
2417 case Type::Builtin:
2418 case Type::Complex:
2419 case Type::Adjusted:
2420 case Type::Decayed:
2421 case Type::ArrayParameter:
2422 case Type::Pointer:
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:
2434 case Type::Vector:
2435 case Type::ExtVector:
2436 case Type::ConstantMatrix:
2437 case Type::DependentSizedMatrix:
2438 case Type::FunctionProto:
2439 case Type::FunctionNoProto:
2440 case Type::Paren:
2441 case Type::Attributed:
2442 case Type::BTFTagAttributed:
2443 case Type::HLSLAttributedResource:
2444 case Type::Auto:
2445 case Type::DeducedTemplateSpecialization:
2446 case Type::PackExpansion:
2447 case Type::ObjCObject:
2448 case Type::ObjCInterface:
2449 case Type::ObjCObjectPointer:
2450 case Type::ObjCTypeParam:
2451 case Type::Atomic:
2452 case Type::Pipe:
2453 case Type::MacroQualified:
2454 case Type::BitInt:
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...);
2463 // };
2464 Out << "_SUBSTPACK_";
2465 break;
2467 // <unresolved-type> ::= <template-param>
2468 // ::= <decltype>
2469 // ::= <template-template-param> <template-args>
2470 // (this last is not official yet)
2471 case Type::TypeOfExpr:
2472 case Type::TypeOf:
2473 case Type::Decltype:
2474 case Type::PackIndexing:
2475 case Type::TemplateTypeParm:
2476 case Type::UnaryTransform:
2477 case Type::SubstTemplateTypeParm:
2478 unresolvedType:
2479 // Some callers want a prefix before the mangled type.
2480 Out << Prefix;
2482 // This seems to do everything we want. It's not really
2483 // sanctioned for a substituted template parameter, though.
2484 mangleType(Ty);
2486 // We never want to print 'E' directly after an unresolved-type,
2487 // so we return directly.
2488 return true;
2490 case Type::Typedef:
2491 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2492 break;
2494 case Type::UnresolvedUsing:
2495 mangleSourceNameWithAbiTags(
2496 cast<UnresolvedUsingType>(Ty)->getDecl());
2497 break;
2499 case Type::Enum:
2500 case Type::Record:
2501 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2502 break;
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
2514 // unresolved type.
2515 assert(TD && "no template for template specialization type");
2516 if (isa<TemplateTemplateParmDecl>(TD))
2517 goto unresolvedType;
2519 mangleSourceNameWithAbiTags(TD);
2520 break;
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());
2533 break;
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...);
2540 // };
2541 Out << "_SUBSTPACK_";
2542 break;
2544 case TemplateName::UsingTemplate: {
2545 TemplateDecl *TD = TN.getAsTemplateDecl();
2546 assert(TD && !isa<TemplateTemplateParmDecl>(TD));
2547 mangleSourceNameWithAbiTags(TD);
2548 break;
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());
2558 break;
2561 case Type::InjectedClassName:
2562 mangleSourceNameWithAbiTags(
2563 cast<InjectedClassNameType>(Ty)->getDecl());
2564 break;
2566 case Type::DependentName:
2567 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2568 break;
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());
2577 break;
2580 case Type::Using:
2581 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2582 Prefix);
2583 case Type::Elaborated:
2584 return mangleUnresolvedTypeOrSimpleId(
2585 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2588 return false;
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)
2605 Out << "cv";
2606 mangleType(Name.getCXXNameType());
2607 break;
2609 case DeclarationName::CXXLiteralOperatorName:
2610 Out << "li";
2611 mangleSourceName(Name.getCXXLiteralIdentifier());
2612 return;
2614 case DeclarationName::CXXOperatorName:
2615 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2616 break;
2620 void
2621 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2622 switch (OO) {
2623 // <operator-name> ::= nw # new
2624 case OO_New: Out << "nw"; break;
2625 // ::= na # new[]
2626 case OO_Array_New: Out << "na"; break;
2627 // ::= dl # delete
2628 case OO_Delete: Out << "dl"; break;
2629 // ::= da # delete[]
2630 case OO_Array_Delete: Out << "da"; break;
2631 // ::= ps # + (unary)
2632 // ::= pl # + (binary or unknown)
2633 case OO_Plus:
2634 Out << (Arity == 1? "ps" : "pl"); break;
2635 // ::= ng # - (unary)
2636 // ::= mi # - (binary or unknown)
2637 case OO_Minus:
2638 Out << (Arity == 1? "ng" : "mi"); break;
2639 // ::= ad # & (unary)
2640 // ::= an # & (binary or unknown)
2641 case OO_Amp:
2642 Out << (Arity == 1? "ad" : "an"); break;
2643 // ::= de # * (unary)
2644 // ::= ml # * (binary or unknown)
2645 case OO_Star:
2646 // Use binary when unknown.
2647 Out << (Arity == 1? "de" : "ml"); break;
2648 // ::= co # ~
2649 case OO_Tilde: Out << "co"; break;
2650 // ::= dv # /
2651 case OO_Slash: Out << "dv"; break;
2652 // ::= rm # %
2653 case OO_Percent: Out << "rm"; break;
2654 // ::= or # |
2655 case OO_Pipe: Out << "or"; break;
2656 // ::= eo # ^
2657 case OO_Caret: Out << "eo"; break;
2658 // ::= aS # =
2659 case OO_Equal: Out << "aS"; break;
2660 // ::= pL # +=
2661 case OO_PlusEqual: Out << "pL"; break;
2662 // ::= mI # -=
2663 case OO_MinusEqual: Out << "mI"; break;
2664 // ::= mL # *=
2665 case OO_StarEqual: Out << "mL"; break;
2666 // ::= dV # /=
2667 case OO_SlashEqual: Out << "dV"; break;
2668 // ::= rM # %=
2669 case OO_PercentEqual: Out << "rM"; break;
2670 // ::= aN # &=
2671 case OO_AmpEqual: Out << "aN"; break;
2672 // ::= oR # |=
2673 case OO_PipeEqual: Out << "oR"; break;
2674 // ::= eO # ^=
2675 case OO_CaretEqual: Out << "eO"; break;
2676 // ::= ls # <<
2677 case OO_LessLess: Out << "ls"; break;
2678 // ::= rs # >>
2679 case OO_GreaterGreater: Out << "rs"; break;
2680 // ::= lS # <<=
2681 case OO_LessLessEqual: Out << "lS"; break;
2682 // ::= rS # >>=
2683 case OO_GreaterGreaterEqual: Out << "rS"; break;
2684 // ::= eq # ==
2685 case OO_EqualEqual: Out << "eq"; break;
2686 // ::= ne # !=
2687 case OO_ExclaimEqual: Out << "ne"; break;
2688 // ::= lt # <
2689 case OO_Less: Out << "lt"; break;
2690 // ::= gt # >
2691 case OO_Greater: Out << "gt"; break;
2692 // ::= le # <=
2693 case OO_LessEqual: Out << "le"; break;
2694 // ::= ge # >=
2695 case OO_GreaterEqual: Out << "ge"; break;
2696 // ::= nt # !
2697 case OO_Exclaim: Out << "nt"; break;
2698 // ::= aa # &&
2699 case OO_AmpAmp: Out << "aa"; break;
2700 // ::= oo # ||
2701 case OO_PipePipe: Out << "oo"; break;
2702 // ::= pp # ++
2703 case OO_PlusPlus: Out << "pp"; break;
2704 // ::= mm # --
2705 case OO_MinusMinus: Out << "mm"; break;
2706 // ::= cm # ,
2707 case OO_Comma: Out << "cm"; break;
2708 // ::= pm # ->*
2709 case OO_ArrowStar: Out << "pm"; break;
2710 // ::= pt # ->
2711 case OO_Arrow: Out << "pt"; break;
2712 // ::= cl # ()
2713 case OO_Call: Out << "cl"; break;
2714 // ::= ix # []
2715 case OO_Subscript: Out << "ix"; break;
2717 // ::= qu # ?
2718 // The conditional operator can't be overloaded, but we still handle it when
2719 // mangling expressions.
2720 case OO_Conditional: Out << "qu"; break;
2721 // Proposal on cxx-abi-dev, 2015-10-21.
2722 // ::= aw # co_await
2723 case OO_Coawait: Out << "aw"; break;
2724 // Proposed in cxx-abi github issue 43.
2725 // ::= ss # <=>
2726 case OO_Spaceship: Out << "ss"; break;
2728 case OO_None:
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>
2739 if (DAST) {
2740 Out << "U2ASI";
2741 mangleExpression(DAST->getAddrSpaceExpr());
2742 Out << "E";
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);
2762 } else {
2763 switch (AS) {
2764 default: llvm_unreachable("Not a language specific address space");
2765 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2766 // "private"| "generic" | "device" |
2767 // "host" ]
2768 case LangAS::opencl_global:
2769 ASString = "CLglobal";
2770 break;
2771 case LangAS::opencl_global_device:
2772 ASString = "CLdevice";
2773 break;
2774 case LangAS::opencl_global_host:
2775 ASString = "CLhost";
2776 break;
2777 case LangAS::opencl_local:
2778 ASString = "CLlocal";
2779 break;
2780 case LangAS::opencl_constant:
2781 ASString = "CLconstant";
2782 break;
2783 case LangAS::opencl_private:
2784 ASString = "CLprivate";
2785 break;
2786 case LangAS::opencl_generic:
2787 ASString = "CLgeneric";
2788 break;
2789 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2790 // "device" | "host" ]
2791 case LangAS::sycl_global:
2792 ASString = "SYglobal";
2793 break;
2794 case LangAS::sycl_global_device:
2795 ASString = "SYdevice";
2796 break;
2797 case LangAS::sycl_global_host:
2798 ASString = "SYhost";
2799 break;
2800 case LangAS::sycl_local:
2801 ASString = "SYlocal";
2802 break;
2803 case LangAS::sycl_private:
2804 ASString = "SYprivate";
2805 break;
2806 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2807 case LangAS::cuda_device:
2808 ASString = "CUdevice";
2809 break;
2810 case LangAS::cuda_constant:
2811 ASString = "CUconstant";
2812 break;
2813 case LangAS::cuda_shared:
2814 ASString = "CUshared";
2815 break;
2816 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2817 case LangAS::ptr32_sptr:
2818 ASString = "ptr32_sptr";
2819 break;
2820 case LangAS::ptr32_uptr:
2821 // For z/OS, there are no special mangling rules applied to the ptr32
2822 // qualifier. Ex: void foo(int * __ptr32 p) -> _Z3f2Pi. The mangling for
2823 // "p" is treated the same as a regular integer pointer.
2824 if (!getASTContext().getTargetInfo().getTriple().isOSzOS())
2825 ASString = "ptr32_uptr";
2826 break;
2827 case LangAS::ptr64:
2828 ASString = "ptr64";
2829 break;
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:
2855 break;
2857 case Qualifiers::OCL_Weak:
2858 // Do nothing as we already handled this case above.
2859 break;
2861 case Qualifiers::OCL_Strong:
2862 mangleVendorQualifier("__strong");
2863 break;
2865 case Qualifiers::OCL_Autoreleasing:
2866 mangleVendorQualifier("__autoreleasing");
2867 break;
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.
2877 break;
2880 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2881 if (Quals.hasRestrict())
2882 Out << 'r';
2883 if (Quals.hasVolatile())
2884 Out << 'V';
2885 if (Quals.hasConst())
2886 Out << 'K';
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) {
2901 case RQ_None:
2902 break;
2904 case RQ_LValue:
2905 Out << 'R';
2906 break;
2908 case RQ_RValue:
2909 Out << 'O';
2910 break;
2914 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2915 Context.mangleObjCMethodNameAsSourceName(MD, Out);
2918 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2919 ASTContext &Ctx) {
2920 if (Quals)
2921 return true;
2922 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2923 return true;
2924 if (Ty->isOpenCLSpecificType())
2925 return true;
2926 // From Clang 18.0 we correctly treat SVE types as substitution candidates.
2927 if (Ty->isSVESizelessBuiltinType() &&
2928 Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)
2929 return true;
2930 if (Ty->isBuiltinType())
2931 return false;
2932 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2933 // substitution candidates.
2934 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2935 isa<AutoType>(Ty))
2936 return false;
2937 // A placeholder type for class template deduction is substitutable with
2938 // its corresponding template name; this is handled specially when mangling
2939 // the type.
2940 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2941 if (DeducedTST->getDeducedType().isNull())
2942 return false;
2943 return true;
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
2978 // dependent.
2979 if (!T->isInstantiationDependentType() || T->isDependentType())
2980 T = T.getCanonicalType();
2981 else {
2982 // Desugar any types that are purely sugar.
2983 do {
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())
2989 break;
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.
2995 QualType Desugared
2996 = T.getSingleStepDesugaredType(Context.getASTContext());
2997 if (Desugared == T)
2998 break;
3000 T = Desugared;
3001 } while (true);
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))
3010 return;
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));
3028 } else {
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));
3035 } else {
3036 switch (ty->getTypeClass()) {
3037 #define ABSTRACT_TYPE(CLASS, PARENT)
3038 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
3039 case Type::CLASS: \
3040 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
3041 return;
3042 #define TYPE(CLASS, PARENT) \
3043 case Type::CLASS: \
3044 mangleType(static_cast<const CLASS##Type*>(ty)); \
3045 break;
3046 #include "clang/AST/TypeNodes.inc"
3050 // Add the substitution.
3051 if (isSubstitutable)
3052 addSubstitution(T);
3055 void CXXNameMangler::mangleCXXRecordDecl(const CXXRecordDecl *Record) {
3056 if (mangleSubstitution(Record))
3057 return;
3058 mangleName(Record);
3059 if (isCompatibleWith(LangOptions::ClangABI::Ver19))
3060 return;
3061 addSubstitution(Record);
3064 void CXXNameMangler::mangleType(const BuiltinType *T) {
3065 // <type> ::= <builtin-type>
3066 // <builtin-type> ::= v # void
3067 // ::= w # wchar_t
3068 // ::= b # bool
3069 // ::= c # char
3070 // ::= a # signed char
3071 // ::= h # unsigned char
3072 // ::= s # short
3073 // ::= t # unsigned short
3074 // ::= i # int
3075 // ::= j # unsigned int
3076 // ::= l # long
3077 // ::= m # unsigned long
3078 // ::= x # long long, __int64
3079 // ::= y # unsigned long long, __int64
3080 // ::= n # __int128
3081 // ::= o # unsigned __int128
3082 // ::= f # float
3083 // ::= d # double
3084 // ::= e # long double, __float80
3085 // ::= g # __float128
3086 // ::= g # __ibm128
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>
3100 // ::= s # short
3101 // ::= t # unsigned short
3102 // ::= i # plain
3103 // ::= j # unsigned
3104 // ::= l # long
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)) {
3113 case 8:
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))
3117 break;
3118 Out << "u2i8";
3119 addSubstitution(BuiltinType::SChar);
3120 break;
3121 case 16:
3122 if (mangleSubstitution(BuiltinType::Short))
3123 break;
3124 Out << "u3i16";
3125 addSubstitution(BuiltinType::Short);
3126 break;
3127 case 32:
3128 if (mangleSubstitution(BuiltinType::Int))
3129 break;
3130 Out << "u3i32";
3131 addSubstitution(BuiltinType::Int);
3132 break;
3133 case 64:
3134 if (mangleSubstitution(BuiltinType::Long))
3135 break;
3136 Out << "u3i64";
3137 addSubstitution(BuiltinType::Long);
3138 break;
3139 case 128:
3140 if (mangleSubstitution(BuiltinType::Int128))
3141 break;
3142 Out << "u4i128";
3143 addSubstitution(BuiltinType::Int128);
3144 break;
3145 default:
3146 llvm_unreachable("Unknown integer size for normalization");
3148 } else {
3149 switch (getASTContext().getTypeSize(T)) {
3150 case 8:
3151 if (mangleSubstitution(BuiltinType::UChar))
3152 break;
3153 Out << "u2u8";
3154 addSubstitution(BuiltinType::UChar);
3155 break;
3156 case 16:
3157 if (mangleSubstitution(BuiltinType::UShort))
3158 break;
3159 Out << "u3u16";
3160 addSubstitution(BuiltinType::UShort);
3161 break;
3162 case 32:
3163 if (mangleSubstitution(BuiltinType::UInt))
3164 break;
3165 Out << "u3u32";
3166 addSubstitution(BuiltinType::UInt);
3167 break;
3168 case 64:
3169 if (mangleSubstitution(BuiltinType::ULong))
3170 break;
3171 Out << "u3u64";
3172 addSubstitution(BuiltinType::ULong);
3173 break;
3174 case 128:
3175 if (mangleSubstitution(BuiltinType::UInt128))
3176 break;
3177 Out << "u4u128";
3178 addSubstitution(BuiltinType::UInt128);
3179 break;
3180 default:
3181 llvm_unreachable("Unknown integer size for normalization");
3184 return;
3186 switch (T->getKind()) {
3187 case BuiltinType::Void:
3188 Out << 'v';
3189 break;
3190 case BuiltinType::Bool:
3191 Out << 'b';
3192 break;
3193 case BuiltinType::Char_U:
3194 case BuiltinType::Char_S:
3195 Out << 'c';
3196 break;
3197 case BuiltinType::UChar:
3198 Out << 'h';
3199 break;
3200 case BuiltinType::UShort:
3201 Out << 't';
3202 break;
3203 case BuiltinType::UInt:
3204 Out << 'j';
3205 break;
3206 case BuiltinType::ULong:
3207 Out << 'm';
3208 break;
3209 case BuiltinType::ULongLong:
3210 Out << 'y';
3211 break;
3212 case BuiltinType::UInt128:
3213 Out << 'o';
3214 break;
3215 case BuiltinType::SChar:
3216 Out << 'a';
3217 break;
3218 case BuiltinType::WChar_S:
3219 case BuiltinType::WChar_U:
3220 Out << 'w';
3221 break;
3222 case BuiltinType::Char8:
3223 Out << "Du";
3224 break;
3225 case BuiltinType::Char16:
3226 Out << "Ds";
3227 break;
3228 case BuiltinType::Char32:
3229 Out << "Di";
3230 break;
3231 case BuiltinType::Short:
3232 Out << 's';
3233 break;
3234 case BuiltinType::Int:
3235 Out << 'i';
3236 break;
3237 case BuiltinType::Long:
3238 Out << 'l';
3239 break;
3240 case BuiltinType::LongLong:
3241 Out << 'x';
3242 break;
3243 case BuiltinType::Int128:
3244 Out << 'n';
3245 break;
3246 case BuiltinType::Float16:
3247 Out << "DF16_";
3248 break;
3249 case BuiltinType::ShortAccum:
3250 Out << "DAs";
3251 break;
3252 case BuiltinType::Accum:
3253 Out << "DAi";
3254 break;
3255 case BuiltinType::LongAccum:
3256 Out << "DAl";
3257 break;
3258 case BuiltinType::UShortAccum:
3259 Out << "DAt";
3260 break;
3261 case BuiltinType::UAccum:
3262 Out << "DAj";
3263 break;
3264 case BuiltinType::ULongAccum:
3265 Out << "DAm";
3266 break;
3267 case BuiltinType::ShortFract:
3268 Out << "DRs";
3269 break;
3270 case BuiltinType::Fract:
3271 Out << "DRi";
3272 break;
3273 case BuiltinType::LongFract:
3274 Out << "DRl";
3275 break;
3276 case BuiltinType::UShortFract:
3277 Out << "DRt";
3278 break;
3279 case BuiltinType::UFract:
3280 Out << "DRj";
3281 break;
3282 case BuiltinType::ULongFract:
3283 Out << "DRm";
3284 break;
3285 case BuiltinType::SatShortAccum:
3286 Out << "DSDAs";
3287 break;
3288 case BuiltinType::SatAccum:
3289 Out << "DSDAi";
3290 break;
3291 case BuiltinType::SatLongAccum:
3292 Out << "DSDAl";
3293 break;
3294 case BuiltinType::SatUShortAccum:
3295 Out << "DSDAt";
3296 break;
3297 case BuiltinType::SatUAccum:
3298 Out << "DSDAj";
3299 break;
3300 case BuiltinType::SatULongAccum:
3301 Out << "DSDAm";
3302 break;
3303 case BuiltinType::SatShortFract:
3304 Out << "DSDRs";
3305 break;
3306 case BuiltinType::SatFract:
3307 Out << "DSDRi";
3308 break;
3309 case BuiltinType::SatLongFract:
3310 Out << "DSDRl";
3311 break;
3312 case BuiltinType::SatUShortFract:
3313 Out << "DSDRt";
3314 break;
3315 case BuiltinType::SatUFract:
3316 Out << "DSDRj";
3317 break;
3318 case BuiltinType::SatULongFract:
3319 Out << "DSDRm";
3320 break;
3321 case BuiltinType::Half:
3322 Out << "Dh";
3323 break;
3324 case BuiltinType::Float:
3325 Out << 'f';
3326 break;
3327 case BuiltinType::Double:
3328 Out << 'd';
3329 break;
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();
3337 break;
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();
3346 break;
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();
3356 break;
3358 case BuiltinType::Ibm128: {
3359 const TargetInfo *TI = &getASTContext().getTargetInfo();
3360 Out << TI->getIbm128Mangling();
3361 break;
3363 case BuiltinType::NullPtr:
3364 Out << "Dn";
3365 break;
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:
3372 if (!NullOut)
3373 llvm_unreachable("mangling a placeholder type");
3374 break;
3375 case BuiltinType::ObjCId:
3376 Out << "11objc_object";
3377 break;
3378 case BuiltinType::ObjCClass:
3379 Out << "10objc_class";
3380 break;
3381 case BuiltinType::ObjCSel:
3382 Out << "13objc_selector";
3383 break;
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; \
3388 break;
3389 #include "clang/Basic/OpenCLImageTypes.def"
3390 case BuiltinType::OCLSampler:
3391 Out << "11ocl_sampler";
3392 break;
3393 case BuiltinType::OCLEvent:
3394 Out << "9ocl_event";
3395 break;
3396 case BuiltinType::OCLClkEvent:
3397 Out << "12ocl_clkevent";
3398 break;
3399 case BuiltinType::OCLQueue:
3400 Out << "9ocl_queue";
3401 break;
3402 case BuiltinType::OCLReserveID:
3403 Out << "13ocl_reserveid";
3404 break;
3405 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3406 case BuiltinType::Id: \
3407 type_name = "ocl_" #ExtType; \
3408 Out << type_name.size() << type_name; \
3409 break;
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"); \
3420 } else { \
3421 type_name = MangledName; \
3422 Out << (type_name == Name ? "u" : "") << type_name.size() << type_name; \
3424 break;
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; \
3429 break;
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; \
3434 break;
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; \
3439 break;
3440 #include "clang/Basic/AArch64SVEACLETypes.def"
3441 #define PPC_VECTOR_TYPE(Name, Id, Size) \
3442 case BuiltinType::Id: \
3443 mangleVendorType(#Name); \
3444 break;
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); \
3450 break;
3451 #include "clang/Basic/RISCVVTypes.def"
3452 #define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \
3453 case BuiltinType::Id: \
3454 mangleVendorType(MangledName); \
3455 break;
3456 #include "clang/Basic/WebAssemblyReferenceTypes.def"
3457 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
3458 case BuiltinType::Id: \
3459 mangleVendorType(Name); \
3460 break;
3461 #include "clang/Basic/AMDGPUTypes.def"
3462 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3463 case BuiltinType::Id: \
3464 mangleVendorType(#Name); \
3465 break;
3466 #include "clang/Basic/HLSLIntangibleTypes.def"
3470 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3471 switch (CC) {
3472 case CC_C:
3473 return "";
3475 case CC_X86VectorCall:
3476 case CC_X86Pascal:
3477 case CC_X86RegCall:
3478 case CC_AAPCS:
3479 case CC_AAPCS_VFP:
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:
3488 case CC_M68kRTD:
3489 case CC_PreserveNone:
3490 case CC_RISCVVectorCall:
3491 // FIXME: we should be mangling all of the above.
3492 return "";
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
3499 // for now.
3500 return "";
3502 case CC_X86StdCall:
3503 return "stdcall";
3504 case CC_X86FastCall:
3505 return "fastcall";
3506 case CC_X86_64SysV:
3507 return "sysv_abi";
3508 case CC_Win64:
3509 return "ms_abi";
3510 case CC_Swift:
3511 return "swiftcall";
3512 case CC_SwiftAsync:
3513 return "swiftasynccall";
3515 llvm_unreachable("bad calling convention");
3518 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3519 // Fast path.
3520 if (T->getExtInfo() == FunctionType::ExtInfo())
3521 return;
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);
3531 // FIXME: regparm
3532 // FIXME: noreturn
3535 void
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:
3544 break;
3546 // HLSL parameter mangling.
3547 case ParameterABI::HLSLOut:
3548 case ParameterABI::HLSLInOut:
3549 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3550 break;
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()));
3558 break;
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())) {
3582 Out << "DO";
3583 mangleExpression(T->getNoexceptExpr());
3584 Out << "E";
3585 } else {
3586 assert(T->getExceptionSpecType() == EST_Dynamic);
3587 Out << "Dw";
3588 for (auto ExceptTy : T->exceptions())
3589 mangleType(ExceptTy);
3590 Out << "E";
3592 } else if (T->isNothrow()) {
3593 Out << "Do";
3596 Out << 'F';
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());
3605 Out << 'E';
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).
3612 Out << 'F';
3614 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3616 FunctionTypeDepth.enterResultType();
3617 mangleType(T->getReturnType());
3618 FunctionTypeDepth.leaveResultType();
3620 FunctionTypeDepth.pop(saved);
3621 Out << 'E';
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
3653 Out << 'v';
3654 } else {
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));
3662 // Mangle the type.
3663 QualType ParamTy = Proto->getParamType(I);
3664 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3666 if (FD) {
3667 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3668 // Attr can only take 1 character, so we can hardcode the length
3669 // below.
3670 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3671 if (Attr->isDynamic())
3672 Out << "U25pass_dynamic_object_size" << Attr->getType();
3673 else
3674 Out << "U17pass_object_size" << Attr->getType();
3679 // <builtin-type> ::= z # ellipsis
3680 if (Proto->isVariadic())
3681 Out << 'z';
3684 if (FD) {
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) {
3718 Out << 'A';
3719 // decayed vla types (size 0) will just be skipped.
3720 if (T->getSizeExpr())
3721 mangleExpression(T->getSizeExpr());
3722 Out << '_';
3723 mangleType(T->getElementType());
3725 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3726 Out << 'A';
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());
3732 Out << '_';
3733 mangleType(T->getElementType());
3735 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3736 Out << "A_";
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) {
3743 Out << 'M';
3744 mangleType(QualType(T->getClass(), 0));
3745 QualType PointeeType = T->getPointeeType();
3746 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3747 mangleType(FPT);
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
3758 // function.
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.
3765 ++SeqID;
3766 } else
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...);
3780 // };
3781 Out << "_SUBSTPACK_";
3784 // <type> ::= P <type> # pointer-to
3785 void CXXNameMangler::mangleType(const PointerType *T) {
3786 Out << 'P';
3787 mangleType(T->getPointeeType());
3789 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3790 Out << 'P';
3791 mangleType(T->getPointeeType());
3794 // <type> ::= R <type> # reference-to
3795 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3796 Out << 'R';
3797 mangleType(T->getPointeeType());
3800 // <type> ::= O <type> # rvalue reference-to (C++0x)
3801 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3802 Out << 'O';
3803 mangleType(T->getPointeeType());
3806 // <type> ::= C <type> # complex pair (C 2000)
3807 void CXXNameMangler::mangleType(const ComplexType *T) {
3808 Out << 'C';
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";
3824 break;
3825 case BuiltinType::Short:
3826 case BuiltinType::UShort:
3827 EltName = "poly16_t";
3828 break;
3829 case BuiltinType::LongLong:
3830 case BuiltinType::ULongLong:
3831 EltName = "poly64_t";
3832 break;
3833 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3835 } else {
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;
3849 default:
3850 llvm_unreachable("unexpected Neon vector element type");
3853 const char *BaseName = nullptr;
3854 unsigned BitSize = (T->getNumElements() *
3855 getASTContext().getTypeSize(EltType));
3856 if (BitSize == 64)
3857 BaseName = "__simd64_";
3858 else {
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:
3877 return "Int8";
3878 case BuiltinType::Short:
3879 return "Int16";
3880 case BuiltinType::Int:
3881 return "Int32";
3882 case BuiltinType::Long:
3883 case BuiltinType::LongLong:
3884 return "Int64";
3885 case BuiltinType::UChar:
3886 return "Uint8";
3887 case BuiltinType::UShort:
3888 return "Uint16";
3889 case BuiltinType::UInt:
3890 return "Uint32";
3891 case BuiltinType::ULong:
3892 case BuiltinType::ULongLong:
3893 return "Uint64";
3894 case BuiltinType::Half:
3895 return "Float16";
3896 case BuiltinType::Float:
3897 return "Float32";
3898 case BuiltinType::Double:
3899 return "Float64";
3900 case BuiltinType::BFloat16:
3901 return "Bfloat16";
3902 default:
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");
3913 unsigned BitSize =
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");
3920 StringRef EltName;
3921 if (T->getVectorKind() == VectorKind::NeonPoly) {
3922 switch (cast<BuiltinType>(EltType)->getKind()) {
3923 case BuiltinType::UChar:
3924 EltName = "Poly8";
3925 break;
3926 case BuiltinType::UShort:
3927 EltName = "Poly16";
3928 break;
3929 case BuiltinType::ULong:
3930 case BuiltinType::ULongLong:
3931 EltName = "Poly64";
3932 break;
3933 default:
3934 llvm_unreachable("unexpected Neon polynomial vector element type");
3936 } else
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).
3960 // For example:
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!");
3984 StringRef TypeName;
3985 switch (cast<BuiltinType>(EltType)->getKind()) {
3986 case BuiltinType::SChar:
3987 TypeName = "__SVInt8_t";
3988 break;
3989 case BuiltinType::UChar: {
3990 if (T->getVectorKind() == VectorKind::SveFixedLengthData)
3991 TypeName = "__SVUint8_t";
3992 else
3993 TypeName = "__SVBool_t";
3994 break;
3996 case BuiltinType::Short:
3997 TypeName = "__SVInt16_t";
3998 break;
3999 case BuiltinType::UShort:
4000 TypeName = "__SVUint16_t";
4001 break;
4002 case BuiltinType::Int:
4003 TypeName = "__SVInt32_t";
4004 break;
4005 case BuiltinType::UInt:
4006 TypeName = "__SVUint32_t";
4007 break;
4008 case BuiltinType::Long:
4009 TypeName = "__SVInt64_t";
4010 break;
4011 case BuiltinType::ULong:
4012 TypeName = "__SVUint64_t";
4013 break;
4014 case BuiltinType::Half:
4015 TypeName = "__SVFloat16_t";
4016 break;
4017 case BuiltinType::Float:
4018 TypeName = "__SVFloat32_t";
4019 break;
4020 case BuiltinType::Double:
4021 TypeName = "__SVFloat64_t";
4022 break;
4023 case BuiltinType::BFloat16:
4024 TypeName = "__SVBfloat16_t";
4025 break;
4026 default:
4027 llvm_unreachable("unexpected element type for fixed-length SVE vector!");
4030 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4032 if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)
4033 VecSizeInBits *= 8;
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";
4067 break;
4068 case BuiltinType::UChar:
4069 if (T->getVectorKind() == VectorKind::RVVFixedLengthData)
4070 TypeNameOS << "uint8";
4071 else
4072 TypeNameOS << "bool";
4073 break;
4074 case BuiltinType::Short:
4075 TypeNameOS << "int16";
4076 break;
4077 case BuiltinType::UShort:
4078 TypeNameOS << "uint16";
4079 break;
4080 case BuiltinType::Int:
4081 TypeNameOS << "int32";
4082 break;
4083 case BuiltinType::UInt:
4084 TypeNameOS << "uint32";
4085 break;
4086 case BuiltinType::Long:
4087 TypeNameOS << "int64";
4088 break;
4089 case BuiltinType::ULong:
4090 TypeNameOS << "uint64";
4091 break;
4092 case BuiltinType::Float16:
4093 TypeNameOS << "float16";
4094 break;
4095 case BuiltinType::Float:
4096 TypeNameOS << "float32";
4097 break;
4098 case BuiltinType::Double:
4099 TypeNameOS << "float64";
4100 break;
4101 default:
4102 llvm_unreachable("unexpected element type for fixed-length RVV vector!");
4105 unsigned VecSizeInBits;
4106 switch (T->getVectorKind()) {
4107 case VectorKind::RVVFixedLengthMask_1:
4108 VecSizeInBits = 1;
4109 break;
4110 case VectorKind::RVVFixedLengthMask_2:
4111 VecSizeInBits = 2;
4112 break;
4113 case VectorKind::RVVFixedLengthMask_4:
4114 VecSizeInBits = 4;
4115 break;
4116 default:
4117 VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4118 break;
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) {
4127 TypeNameOS << 'm';
4128 if (VecSizeInBits >= VLen)
4129 TypeNameOS << (VecSizeInBits / VLen);
4130 else
4131 TypeNameOS << 'f' << (VLen / VecSizeInBits);
4132 } else {
4133 TypeNameOS << (VLen / VecSizeInBits);
4135 TypeNameOS << "_t";
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);
4168 else
4169 mangleNeonVectorType(T);
4170 return;
4171 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4172 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4173 mangleAArch64FixedSveVectorType(T);
4174 return;
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);
4181 return;
4183 Out << "Dv" << T->getNumElements() << '_';
4184 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4185 Out << 'p';
4186 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4187 Out << 'b';
4188 else
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);
4201 else
4202 mangleNeonVectorType(T);
4203 return;
4204 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4205 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4206 mangleAArch64FixedSveVectorType(T);
4207 return;
4208 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4209 mangleRISCVFixedRVVVectorType(T);
4210 return;
4213 Out << "Dv";
4214 mangleExpression(T->getSizeExpr());
4215 Out << '_';
4216 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4217 Out << 'p';
4218 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4219 Out << 'b';
4220 else
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) {
4228 Out << "Dv";
4229 mangleExpression(T->getSizeExpr());
4230 Out << '_';
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");
4240 Out << "I";
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());
4250 Out << "E";
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");
4258 Out << "I";
4259 mangleTemplateArgExpr(T->getRowExpr());
4260 mangleTemplateArgExpr(T->getColumnExpr());
4261 mangleType(T->getElementType());
4262 Out << "E";
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)
4273 Out << "Dp";
4274 mangleType(T->getPattern());
4277 void CXXNameMangler::mangleType(const PackIndexingType *T) {
4278 if (!T->hasSelectedType())
4279 mangleType(T->getPattern());
4280 else
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
4309 Out << 'I';
4310 for (auto typeArg : T->getTypeArgs())
4311 mangleType(typeArg);
4312 Out << 'E';
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());
4331 } else {
4332 if (mangleSubstitution(QualType(T, 0)))
4333 return;
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
4349 // # 'typename'
4350 // ::= Ts <name> # dependent elaborated type specifier using
4351 // # 'struct' or 'class'
4352 // ::= Tu <name> # dependent elaborated type specifier using
4353 // # 'union'
4354 // ::= Te <name> # dependent elaborated type specifier using
4355 // # 'enum'
4356 switch (T->getKeyword()) {
4357 case ElaboratedTypeKeyword::None:
4358 case ElaboratedTypeKeyword::Typename:
4359 break;
4360 case ElaboratedTypeKeyword::Struct:
4361 case ElaboratedTypeKeyword::Class:
4362 case ElaboratedTypeKeyword::Interface:
4363 Out << "Ts";
4364 break;
4365 case ElaboratedTypeKeyword::Union:
4366 Out << "Tu";
4367 break;
4368 case ElaboratedTypeKeyword::Enum:
4369 Out << "Te";
4370 break;
4372 // Typename types are always nested
4373 Out << 'N';
4374 manglePrefix(T->getQualifier());
4375 mangleSourceName(T->getIdentifier());
4376 Out << 'E';
4379 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
4380 // Dependently-scoped template types are nested if they have a prefix.
4381 Out << 'N';
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());
4393 Out << 'E';
4396 void CXXNameMangler::mangleType(const TypeOfType *T) {
4397 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4398 // "extension with parameters" mangling.
4399 Out << "u6typeof";
4402 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
4403 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4404 // "extension with parameters" mangling.
4405 Out << "u6typeof";
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))
4425 Out << "Dt";
4426 else
4427 Out << "DT";
4428 mangleExpression(E);
4429 Out << '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; \
4441 break;
4442 #include "clang/Basic/TransformTypeTraits.def"
4444 mangleVendorType(BuiltinName);
4447 Out << "I";
4448 mangleType(T->getBaseType());
4449 Out << "E";
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());
4465 } else {
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");
4478 mangleType(TN);
4481 void CXXNameMangler::mangleType(const AtomicType *T) {
4482 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4483 // (Until there's a standardized mangling...)
4484 Out << "U7_Atomic";
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
4492 Out << "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());
4508 Out << "_";
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:
4521 Str += "_u";
4522 break;
4523 case llvm::dxil::ResourceClass::SRV:
4524 Str += "_t";
4525 break;
4526 case llvm::dxil::ResourceClass::CBuffer:
4527 Str += "_b";
4528 break;
4529 case llvm::dxil::ResourceClass::Sampler:
4530 Str += "_s";
4531 break;
4533 if (Attrs.IsROV)
4534 Str += "_ROV";
4535 if (Attrs.RawBuffer)
4536 Str += "_Raw";
4537 if (T->hasContainedType())
4538 Str += "_CT";
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
4550 Out << 'L';
4552 mangleType(T);
4553 if (T->isBooleanType()) {
4554 // Boolean values are encoded as 0/1.
4555 Out << (Value.getBoolValue() ? '1' : '0');
4556 } else {
4557 mangleNumber(Value);
4559 Out << 'E';
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())
4567 break;
4568 const auto *ME = dyn_cast<MemberExpr>(Base);
4569 if (!ME)
4570 break;
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.
4579 Out << "dtdefpT";
4580 } else {
4581 Out << (IsArrow ? "pt" : "dt");
4582 mangleExpression(Base);
4586 /// Mangles a member expression.
4587 void CXXNameMangler::mangleMemberExpr(const Expr *base,
4588 bool isArrow,
4589 NestedNameSpecifier *qualifier,
4590 NamedDecl *firstQualifierLookup,
4591 DeclarationName member,
4592 const TemplateArgumentLoc *TemplateArgs,
4593 unsigned NumTemplateArgs,
4594 unsigned arity) {
4595 // <expression> ::= dt <expression> <unresolved-name>
4596 // ::= pt <expression> <unresolved-name>
4597 if (base)
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
4604 /// otherwise.
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
4611 // parenthesized.
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())
4627 return false;
4629 // Otherwise, ADL would have been triggered.
4630 return true;
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);
4661 Out << 'F';
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);
4671 Out << 'T';
4672 mangleType(TR->getType()->getType());
4673 break;
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);
4683 Out << 'X';
4684 mangleExpression(ER->getExpr());
4686 if (ER->hasNoexceptRequirement())
4687 Out << 'N';
4689 if (!ER->getReturnTypeRequirement().isEmpty()) {
4690 if (ER->getReturnTypeRequirement().isSubstitutionFailure())
4691 return HandleSubstitutionFailure(ER->getReturnTypeRequirement()
4692 .getSubstitutionDiagnostic()
4693 ->DiagLoc);
4695 Out << 'R';
4696 mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());
4698 break;
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
4705 // keyword.
4706 return HandleSubstitutionFailure(RequiresExprLoc);
4709 Out << 'Q';
4710 mangleExpression(NR->getConstraintExpr());
4711 break;
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)
4752 Out << 'X';
4753 IsPrimaryExpr = false;
4756 auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4757 switch (D->getKind()) {
4758 default:
4759 // <expr-primary> ::= L <mangled-name> E # external name
4760 Out << 'L';
4761 mangle(D);
4762 Out << 'E';
4763 break;
4765 case Decl::ParmVar:
4766 NotPrimaryExpr();
4767 mangleFunctionParam(cast<ParmVarDecl>(D));
4768 break;
4770 case Decl::EnumConstant: {
4771 // <expr-primary>
4772 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4773 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4774 break;
4777 case Decl::NonTypeTemplateParm:
4778 NotPrimaryExpr();
4779 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4780 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4781 break;
4785 // 'goto recurse' is used when handling a simple "unwrapping" node which
4786 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4787 // to be preserved.
4788 recurse:
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"
4796 // fallthrough
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();
4821 goto recurse;
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:
4859 NotPrimaryExpr();
4860 if (!NullOut) {
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();
4867 return;
4869 break;
4872 case Expr::CXXUuidofExprClass: {
4873 NotPrimaryExpr();
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()));
4881 else
4882 mangleTemplateArgExpr(UE->getExprOperand());
4883 Out << 'E';
4884 } else {
4885 if (UE->isTypeOperand()) {
4886 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
4887 Out << "u8__uuidoft";
4888 mangleType(UuidT);
4889 } else {
4890 Expr *UuidExp = UE->getExprOperand();
4891 Out << "u8__uuidofz";
4892 mangleExpression(UuidExp);
4895 break;
4898 // Even gcc-4.5 doesn't mangle this.
4899 case Expr::BinaryConditionalOperatorClass: {
4900 NotPrimaryExpr();
4901 DiagnosticsEngine &Diags = Context.getDiags();
4902 unsigned DiagID =
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();
4907 return;
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: {
4915 NotPrimaryExpr();
4916 Out << "il";
4917 mangleInitListElements(cast<InitListExpr>(E));
4918 Out << "E";
4919 break;
4922 case Expr::DesignatedInitExprClass: {
4923 NotPrimaryExpr();
4924 auto *DIE = cast<DesignatedInitExpr>(E);
4925 for (const auto &Designator : DIE->designators()) {
4926 if (Designator.isFieldDesignator()) {
4927 Out << "di";
4928 mangleSourceName(Designator.getFieldName());
4929 } else if (Designator.isArrayDesignator()) {
4930 Out << "dx";
4931 mangleExpression(DIE->getArrayIndex(Designator));
4932 } else {
4933 assert(Designator.isArrayRangeDesignator() &&
4934 "unknown designator kind");
4935 Out << "dX";
4936 mangleExpression(DIE->getArrayRangeStart(Designator));
4937 mangleExpression(DIE->getArrayRangeEnd(Designator));
4940 mangleExpression(DIE->getInit());
4941 break;
4944 case Expr::CXXDefaultArgExprClass:
4945 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4946 goto recurse;
4948 case Expr::CXXDefaultInitExprClass:
4949 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4950 goto recurse;
4952 case Expr::CXXStdInitializerListExprClass:
4953 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
4954 goto recurse;
4956 case Expr::SubstNonTypeTemplateParmExprClass: {
4957 // Mangle a substituted parameter the same way we mangle the template
4958 // argument.
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);
4966 break;
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();
4971 goto recurse;
4974 case Expr::UserDefinedLiteralClass:
4975 // We follow g++'s approach of mangling a UDL as a call to the literal
4976 // operator.
4977 case Expr::CXXMemberCallExprClass: // fallthrough
4978 case Expr::CallExprClass: {
4979 NotPrimaryExpr();
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)) {
4987 Out << "cp";
4988 // The callee here is a parenthesized UnresolvedLookupExpr with
4989 // no qualifier and should always get mangled as a <simple-id>
4990 // anyway.
4992 // <expression> ::= cl <expression>* E
4993 } else {
4994 Out << "cl";
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);
5005 Out << 'E';
5006 break;
5009 case Expr::CXXNewExprClass: {
5010 NotPrimaryExpr();
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);
5017 Out << '_';
5018 mangleType(New->getAllocatedType());
5019 if (New->hasInitializer()) {
5020 if (New->getInitializationStyle() == CXXNewInitializationStyle::Braces)
5021 Out << "il";
5022 else
5023 Out << "pi";
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(),
5028 E = CCE->arg_end();
5029 I != E; ++I)
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));
5039 } else
5040 mangleExpression(Init);
5042 Out << 'E';
5043 break;
5046 case Expr::CXXPseudoDestructorExprClass: {
5047 NotPrimaryExpr();
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()) {
5053 if (Qualifier) {
5054 mangleUnresolvedPrefix(Qualifier,
5055 /*recursive=*/true);
5056 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
5057 Out << 'E';
5058 } else {
5059 Out << "sr";
5060 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
5061 Out << 'E';
5063 } else if (Qualifier) {
5064 mangleUnresolvedPrefix(Qualifier);
5066 // <base-unresolved-name> ::= dn <destructor-name>
5067 Out << "dn";
5068 QualType DestroyedType = PDE->getDestroyedType();
5069 mangleUnresolvedTypeOrSimpleId(DestroyedType);
5070 break;
5073 case Expr::MemberExprClass: {
5074 NotPrimaryExpr();
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(),
5080 Arity);
5081 break;
5084 case Expr::UnresolvedMemberExprClass: {
5085 NotPrimaryExpr();
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(),
5091 Arity);
5092 break;
5095 case Expr::CXXDependentScopeMemberExprClass: {
5096 NotPrimaryExpr();
5097 const CXXDependentScopeMemberExpr *ME
5098 = cast<CXXDependentScopeMemberExpr>(E);
5099 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
5100 ME->isArrow(), ME->getQualifier(),
5101 ME->getFirstQualifierFoundInScope(),
5102 ME->getMember(),
5103 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
5104 Arity);
5105 break;
5108 case Expr::UnresolvedLookupExprClass: {
5109 NotPrimaryExpr();
5110 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
5111 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
5112 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
5113 Arity);
5114 break;
5117 case Expr::CXXUnresolvedConstructExprClass: {
5118 NotPrimaryExpr();
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));
5125 Out << "tl";
5126 mangleType(CE->getType());
5127 mangleInitListElements(IL);
5128 Out << "E";
5129 break;
5132 Out << "cv";
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';
5137 break;
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()) {
5144 assert(
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);
5149 goto recurse;
5151 NotPrimaryExpr();
5152 Out << "il";
5153 for (auto *E : CE->arguments())
5154 mangleExpression(E);
5155 Out << "E";
5156 break;
5159 case Expr::CXXTemporaryObjectExprClass: {
5160 NotPrimaryExpr();
5161 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
5162 unsigned N = CE->getNumArgs();
5163 bool List = CE->isListInitialization();
5165 if (List)
5166 Out << "tl";
5167 else
5168 Out << "cv";
5169 mangleType(CE->getType());
5170 if (!List && N != 1)
5171 Out << '_';
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.
5176 auto *SILE =
5177 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
5178 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
5179 mangleInitListElements(ILE);
5180 } else {
5181 for (auto *E : CE->arguments())
5182 mangleExpression(E);
5184 if (List || N != 1)
5185 Out << 'E';
5186 break;
5189 case Expr::CXXScalarValueInitExprClass:
5190 NotPrimaryExpr();
5191 Out << "cv";
5192 mangleType(E->getType());
5193 Out << "_E";
5194 break;
5196 case Expr::CXXNoexceptExprClass:
5197 NotPrimaryExpr();
5198 Out << "nx";
5199 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
5200 break;
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()) {
5207 // Itanium C++ ABI:
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);
5224 break;
5227 NotPrimaryExpr(); // But otherwise, they are not.
5229 auto MangleAlignofSizeofArg = [&] {
5230 if (SAE->isArgumentType()) {
5231 Out << 't';
5232 mangleType(SAE->getArgumentType());
5233 } else {
5234 Out << 'z';
5235 mangleExpression(SAE->getArgumentExpr());
5239 switch(SAE->getKind()) {
5240 case UETT_SizeOf:
5241 Out << 's';
5242 MangleAlignofSizeofArg();
5243 break;
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
5247 // same.)
5248 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
5249 Out << "u11__alignof__";
5250 if (SAE->isArgumentType())
5251 mangleType(SAE->getArgumentType());
5252 else
5253 mangleTemplateArgExpr(SAE->getArgumentExpr());
5254 Out << 'E';
5255 break;
5257 [[fallthrough]];
5258 case UETT_AlignOf:
5259 Out << 'a';
5260 MangleAlignofSizeofArg();
5261 break;
5262 case UETT_DataSizeOf: {
5263 DiagnosticsEngine &Diags = Context.getDiags();
5264 unsigned DiagID =
5265 Diags.getCustomDiagID(DiagnosticsEngine::Error,
5266 "cannot yet mangle __datasizeof expression");
5267 Diags.Report(DiagID);
5268 return;
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);
5276 return;
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);
5283 return;
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);
5291 return;
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);
5299 return;
5302 break;
5305 case Expr::TypeTraitExprClass: {
5306 // <expression> ::= u <source-name> <template-arg>* E # vendor extension
5307 const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);
5308 NotPrimaryExpr();
5309 llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());
5310 mangleVendorType(Spelling);
5311 for (TypeSourceInfo *TSI : TTE->getArgs()) {
5312 mangleType(TSI->getType());
5314 Out << 'E';
5315 break;
5318 case Expr::CXXThrowExprClass: {
5319 NotPrimaryExpr();
5320 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
5321 // <expression> ::= tw <expression> # throw expression
5322 // ::= tr # rethrow
5323 if (TE->getSubExpr()) {
5324 Out << "tw";
5325 mangleExpression(TE->getSubExpr());
5326 } else {
5327 Out << "tr";
5329 break;
5332 case Expr::CXXTypeidExprClass: {
5333 NotPrimaryExpr();
5334 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
5335 // <expression> ::= ti <type> # typeid (type)
5336 // ::= te <expression> # typeid (expression)
5337 if (TIE->isTypeOperand()) {
5338 Out << "ti";
5339 mangleType(TIE->getTypeOperand(Context.getASTContext()));
5340 } else {
5341 Out << "te";
5342 mangleExpression(TIE->getExprOperand());
5344 break;
5347 case Expr::CXXDeleteExprClass: {
5348 NotPrimaryExpr();
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());
5355 break;
5358 case Expr::UnaryOperatorClass: {
5359 NotPrimaryExpr();
5360 const UnaryOperator *UO = cast<UnaryOperator>(E);
5361 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
5362 /*Arity=*/1);
5363 mangleExpression(UO->getSubExpr());
5364 break;
5367 case Expr::ArraySubscriptExprClass: {
5368 NotPrimaryExpr();
5369 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
5371 // Array subscript is treated as a syntactically weird form of
5372 // binary operator.
5373 Out << "ix";
5374 mangleExpression(AE->getLHS());
5375 mangleExpression(AE->getRHS());
5376 break;
5379 case Expr::MatrixSubscriptExprClass: {
5380 NotPrimaryExpr();
5381 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
5382 Out << "ixix";
5383 mangleExpression(ME->getBase());
5384 mangleExpression(ME->getRowIdx());
5385 mangleExpression(ME->getColumnIdx());
5386 break;
5389 case Expr::CompoundAssignOperatorClass: // fallthrough
5390 case Expr::BinaryOperatorClass: {
5391 NotPrimaryExpr();
5392 const BinaryOperator *BO = cast<BinaryOperator>(E);
5393 if (BO->getOpcode() == BO_PtrMemD)
5394 Out << "ds";
5395 else
5396 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
5397 /*Arity=*/2);
5398 mangleExpression(BO->getLHS());
5399 mangleExpression(BO->getRHS());
5400 break;
5403 case Expr::CXXRewrittenBinaryOperatorClass: {
5404 NotPrimaryExpr();
5405 // The mangled form represents the original syntax.
5406 CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
5407 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
5408 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
5409 /*Arity=*/2);
5410 mangleExpression(Decomposed.LHS);
5411 mangleExpression(Decomposed.RHS);
5412 break;
5415 case Expr::ConditionalOperatorClass: {
5416 NotPrimaryExpr();
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);
5422 break;
5425 case Expr::ImplicitCastExprClass: {
5426 ImplicitlyConvertedToType = E->getType();
5427 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5428 goto recurse;
5431 case Expr::ObjCBridgedCastExprClass: {
5432 NotPrimaryExpr();
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");
5438 break;
5441 case Expr::CStyleCastExprClass:
5442 NotPrimaryExpr();
5443 mangleCastExpression(E, "cv");
5444 break;
5446 case Expr::CXXFunctionalCastExprClass: {
5447 NotPrimaryExpr();
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)) {
5456 Out << "tl";
5457 mangleType(E->getType());
5458 mangleInitListElements(IL);
5459 Out << "E";
5460 } else {
5461 mangleCastExpression(E, "cv");
5463 break;
5466 case Expr::CXXStaticCastExprClass:
5467 NotPrimaryExpr();
5468 mangleCastExpression(E, "sc");
5469 break;
5470 case Expr::CXXDynamicCastExprClass:
5471 NotPrimaryExpr();
5472 mangleCastExpression(E, "dc");
5473 break;
5474 case Expr::CXXReinterpretCastExprClass:
5475 NotPrimaryExpr();
5476 mangleCastExpression(E, "rc");
5477 break;
5478 case Expr::CXXConstCastExprClass:
5479 NotPrimaryExpr();
5480 mangleCastExpression(E, "cc");
5481 break;
5482 case Expr::CXXAddrspaceCastExprClass:
5483 NotPrimaryExpr();
5484 mangleCastExpression(E, "ac");
5485 break;
5487 case Expr::CXXOperatorCallExprClass: {
5488 NotPrimaryExpr();
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));
5498 break;
5501 case Expr::ParenExprClass:
5502 E = cast<ParenExpr>(E)->getSubExpr();
5503 goto recurse;
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
5510 // work.
5511 Out << "L_Z";
5512 mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
5513 Out << 'E';
5514 break;
5516 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5517 NotPrimaryExpr();
5518 mangleUnresolvedName(
5519 CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
5520 CSE->getConceptNameInfo().getName(),
5521 CSE->getTemplateArgsAsWritten()->getTemplateArgs(),
5522 CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());
5523 break;
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').
5531 NotPrimaryExpr();
5532 if (RE->getLParenLoc().isValid()) {
5533 Out << "rQ";
5534 FunctionTypeDepthState saved = FunctionTypeDepth.push();
5535 if (RE->getLocalParameters().empty()) {
5536 Out << 'v';
5537 } else {
5538 for (ParmVarDecl *Param : RE->getLocalParameters()) {
5539 mangleType(Context.getASTContext().getSignatureParameterType(
5540 Param->getType()));
5543 Out << '_';
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);
5550 Out << 'E';
5551 } else {
5552 Out << "rq";
5553 for (const concepts::Requirement *Req : RE->getRequirements())
5554 mangleRequirement(RE->getExprLoc(), Req);
5555 Out << 'E';
5557 break;
5560 case Expr::DeclRefExprClass:
5561 // MangleDeclRefExpr helper handles primary-vs-nonprimary
5562 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
5563 break;
5565 case Expr::SubstNonTypeTemplateParmPackExprClass:
5566 NotPrimaryExpr();
5567 // FIXME: not clear how to mangle this!
5568 // template <unsigned N...> class A {
5569 // template <class U...> void foo(U (&x)[N]...);
5570 // };
5571 Out << "_SUBSTPACK_";
5572 break;
5574 case Expr::FunctionParmPackExprClass: {
5575 NotPrimaryExpr();
5576 // FIXME: not clear how to mangle this!
5577 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
5578 Out << "v110_SUBSTPACK";
5579 MangleDeclRefExpr(FPPE->getParameterPack());
5580 break;
5583 case Expr::DependentScopeDeclRefExprClass: {
5584 NotPrimaryExpr();
5585 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
5586 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
5587 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
5588 Arity);
5589 break;
5592 case Expr::CXXBindTemporaryExprClass:
5593 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
5594 goto recurse;
5596 case Expr::ExprWithCleanupsClass:
5597 E = cast<ExprWithCleanups>(E)->getSubExpr();
5598 goto recurse;
5600 case Expr::FloatingLiteralClass: {
5601 // <expr-primary>
5602 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
5603 mangleFloatLiteral(FL->getType(), FL->getValue());
5604 break;
5607 case Expr::FixedPointLiteralClass:
5608 // Currently unimplemented -- might be <expr-primary> in future?
5609 mangleFixedPointLiteral();
5610 break;
5612 case Expr::CharacterLiteralClass:
5613 // <expr-primary>
5614 Out << 'L';
5615 mangleType(E->getType());
5616 Out << cast<CharacterLiteral>(E)->getValue();
5617 Out << 'E';
5618 break;
5620 // FIXME. __objc_yes/__objc_no are mangled same as true/false
5621 case Expr::ObjCBoolLiteralExprClass:
5622 // <expr-primary>
5623 Out << "Lb";
5624 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5625 Out << 'E';
5626 break;
5628 case Expr::CXXBoolLiteralExprClass:
5629 // <expr-primary>
5630 Out << "Lb";
5631 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5632 Out << 'E';
5633 break;
5635 case Expr::IntegerLiteralClass: {
5636 // <expr-primary>
5637 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
5638 if (E->getType()->isSignedIntegerType())
5639 Value.setIsSigned(true);
5640 mangleIntegerLiteral(E->getType(), Value);
5641 break;
5644 case Expr::ImaginaryLiteralClass: {
5645 // <expr-primary>
5646 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
5647 // Mangle as if a complex literal.
5648 // Proposal from David Vandevoorde, 2010.06.30.
5649 Out << 'L';
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()));
5655 Out << '_';
5656 mangleFloat(Imag->getValue());
5657 } else {
5658 Out << "0_";
5659 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
5660 if (IE->getSubExpr()->getType()->isSignedIntegerType())
5661 Value.setIsSigned(true);
5662 mangleNumber(Value);
5664 Out << 'E';
5665 break;
5668 case Expr::StringLiteralClass: {
5669 // <expr-primary>
5670 // Revised proposal from David Vandervoorde, 2010.07.15.
5671 Out << 'L';
5672 assert(isa<ConstantArrayType>(E->getType()));
5673 mangleType(E->getType());
5674 Out << 'E';
5675 break;
5678 case Expr::GNUNullExprClass:
5679 // <expr-primary>
5680 // Mangle as if an integer literal 0.
5681 mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
5682 break;
5684 case Expr::CXXNullPtrLiteralExprClass: {
5685 // <expr-primary>
5686 Out << "LDnE";
5687 break;
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.
5694 Out << "L";
5695 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
5696 Out << "E";
5697 break;
5700 case Expr::PackExpansionExprClass:
5701 NotPrimaryExpr();
5702 Out << "sp";
5703 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
5704 break;
5706 case Expr::SizeOfPackExprClass: {
5707 NotPrimaryExpr();
5708 auto *SPE = cast<SizeOfPackExpr>(E);
5709 if (SPE->isPartiallySubstituted()) {
5710 Out << "sP";
5711 for (const auto &A : SPE->getPartialArguments())
5712 mangleTemplateArg(A, false);
5713 Out << "E";
5714 break;
5717 Out << "sZ";
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());
5727 else
5728 mangleFunctionParam(cast<ParmVarDecl>(Pack));
5729 break;
5732 case Expr::MaterializeTemporaryExprClass:
5733 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5734 goto recurse;
5736 case Expr::CXXFoldExprClass: {
5737 NotPrimaryExpr();
5738 auto *FE = cast<CXXFoldExpr>(E);
5739 if (FE->isLeftFold())
5740 Out << (FE->getInit() ? "fL" : "fl");
5741 else
5742 Out << (FE->getInit() ? "fR" : "fr");
5744 if (FE->getOperator() == BO_PtrMemD)
5745 Out << "ds";
5746 else
5747 mangleOperatorName(
5748 BinaryOperator::getOverloadedOperator(FE->getOperator()),
5749 /*Arity=*/2);
5751 if (FE->getLHS())
5752 mangleExpression(FE->getLHS());
5753 if (FE->getRHS())
5754 mangleExpression(FE->getRHS());
5755 break;
5758 case Expr::CXXThisExprClass:
5759 NotPrimaryExpr();
5760 Out << "fpT";
5761 break;
5763 case Expr::CoawaitExprClass:
5764 // FIXME: Propose a non-vendor mangling.
5765 NotPrimaryExpr();
5766 Out << "v18co_await";
5767 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5768 break;
5770 case Expr::DependentCoawaitExprClass:
5771 // FIXME: Propose a non-vendor mangling.
5772 NotPrimaryExpr();
5773 Out << "v18co_await";
5774 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
5775 break;
5777 case Expr::CoyieldExprClass:
5778 // FIXME: Propose a non-vendor mangling.
5779 NotPrimaryExpr();
5780 Out << "v18co_yield";
5781 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5782 break;
5783 case Expr::SYCLUniqueStableNameExprClass: {
5784 const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
5785 NotPrimaryExpr();
5787 Out << "u33__builtin_sycl_unique_stable_name";
5788 mangleType(USN->getTypeSourceInfo()->getType());
5790 Out << "E";
5791 break;
5793 case Expr::HLSLOutArgExprClass:
5794 llvm_unreachable(
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);
5803 return;
5807 if (AsTemplateArg && !IsPrimaryExpr)
5808 Out << 'E';
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
5834 /// manglings.
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();
5843 // Compute 'L'.
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())
5849 nestingDepth--;
5851 if (nestingDepth == 0) {
5852 Out << "fp";
5853 } else {
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);
5867 } else {
5868 mangleQualifiers(parm->getType().getQualifiers());
5871 // Parameter index.
5872 if (parmIndex != 0) {
5873 Out << (parmIndex - 1);
5875 Out << '_';
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.
5886 Out << 'C';
5887 if (InheritedFrom)
5888 Out << 'I';
5889 switch (T) {
5890 case Ctor_Complete:
5891 Out << '1';
5892 break;
5893 case Ctor_Base:
5894 Out << '2';
5895 break;
5896 case Ctor_Comdat:
5897 Out << '5';
5898 break;
5899 case Ctor_DefaultClosure:
5900 case Ctor_CopyingClosure:
5901 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
5903 if (InheritedFrom)
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.
5913 switch (T) {
5914 case Dtor_Deleting:
5915 Out << "D0";
5916 break;
5917 case Dtor_Complete:
5918 Out << "D1";
5919 break;
5920 case Dtor_Base:
5921 Out << "D2";
5922 break;
5923 case Dtor_Comdat:
5924 Out << "D5";
5925 break;
5929 // Helper to provide ancillary information on a template used to mangle its
5930 // arguments.
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.
5944 struct Info {
5945 /// Do we need to mangle the template argument with an exactly correct type?
5946 bool NeedExactType;
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())
5961 return true;
5964 // All other templates are not overloadable. Partial specializations would
5965 // be, but we never mangle them.
5966 return false;
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)
5982 return true;
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);
6006 if (!ArgTemplate)
6007 return 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
6027 // properly.
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
6036 /// order.
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;
6045 if (!Param) {
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
6077 // type.
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())
6092 return nullptr;
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
6101 Out << 'I';
6102 TemplateArgManglingInfo Info(*this, TN);
6103 for (unsigned i = 0; i != NumTemplateArgs; ++i) {
6104 mangleTemplateArg(Info, i, TemplateArgs[i].getArgument());
6106 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
6107 Out << 'E';
6110 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6111 const TemplateArgumentList &AL) {
6112 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6113 Out << 'I';
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());
6119 Out << 'E';
6122 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6123 ArrayRef<TemplateArgument> Args) {
6124 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6125 Out << 'I';
6126 TemplateArgManglingInfo Info(*this, TN);
6127 for (unsigned i = 0; i != Args.size(); ++i) {
6128 mangleTemplateArg(Info, i, Args[i]);
6130 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
6131 Out << 'E';
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
6142 // ambiguous.
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());
6167 break;
6168 case TemplateArgument::Template:
6169 // This is mangled as <type>.
6170 mangleType(A.getAsTemplate());
6171 break;
6172 case TemplateArgument::TemplateExpansion:
6173 // <type> ::= Dp <type> # pack expansion (C++0x)
6174 Out << "Dp";
6175 mangleType(A.getAsTemplateOrTemplatePattern());
6176 break;
6177 case TemplateArgument::Expression:
6178 mangleTemplateArgExpr(A.getAsExpr());
6179 break;
6180 case TemplateArgument::Integral:
6181 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
6182 break;
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,
6193 NeedExactType);
6194 break;
6197 ASTContext &Ctx = Context.getASTContext();
6198 APValue Value;
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);
6210 else
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,
6216 NeedExactType);
6217 break;
6219 case TemplateArgument::NullPtr: {
6220 mangleNullPointer(A.getNullPtrType());
6221 break;
6223 case TemplateArgument::StructuralValue:
6224 mangleValueInTemplateArg(A.getStructuralValueType(),
6225 A.getAsStructuralValue(),
6226 /*TopLevel=*/true, NeedExactType);
6227 break;
6228 case TemplateArgument::Pack: {
6229 // <template-arg> ::= J <template-arg>* E
6230 Out << 'J';
6231 for (const auto &P : A.pack_elements())
6232 mangleTemplateArg(P, NeedExactType);
6233 Out << 'E';
6238 void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
6239 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6240 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
6241 return;
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
6248 // 'Li0E'.
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)) {
6258 Out << 'L';
6259 mangle(D);
6260 Out << 'E';
6261 return;
6264 Out << 'X';
6265 mangleExpression(E);
6266 Out << '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()) {
6279 case APValue::None:
6280 case APValue::Indeterminate:
6281 case APValue::AddrLabelDiff:
6282 return false;
6284 case APValue::Struct: {
6285 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6286 assert(RD && "unexpected type for record value");
6287 unsigned I = 0;
6288 for (const CXXBaseSpecifier &BS : RD->bases()) {
6289 if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
6290 return false;
6291 ++I;
6293 I = 0;
6294 for (const FieldDecl *FD : RD->fields()) {
6295 if (!FD->isUnnamedBitField() &&
6296 !isZeroInitialized(FD->getType(), V.getStructField(I)))
6297 return false;
6298 ++I;
6300 return true;
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.
6314 return true;
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)))
6321 return false;
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)))
6329 return false;
6330 return true;
6333 case APValue::Int:
6334 return !V.getInt();
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()))
6366 T = FD->getType();
6367 else
6368 T = Ctx.getRecordType(
6369 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
6371 return T;
6374 static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,
6375 DiagnosticsEngine &Diags,
6376 const FieldDecl *FD) {
6377 // According to:
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
6382 // union.
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())
6392 return nullptr;
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))
6401 return II;
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);
6412 return nullptr;
6415 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
6416 bool TopLevel,
6417 bool NeedExactType) {
6418 // Ignore all top-level cv-qualifiers, to match GCC.
6419 Qualifiers Quals;
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)
6426 Out << 'X';
6427 IsPrimaryExpr = false;
6430 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
6431 switch (V.getKind()) {
6432 case APValue::None:
6433 case APValue::Indeterminate:
6434 Out << 'L';
6435 mangleType(T);
6436 Out << 'E';
6437 break;
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());
6448 while (
6449 !Fields.empty() &&
6450 (Fields.back()->isUnnamedBitField() ||
6451 isZeroInitialized(Fields.back()->getType(),
6452 V.getStructField(Fields.back()->getFieldIndex())))) {
6453 Fields.pop_back();
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
6464 NotPrimaryExpr();
6465 Out << "tl";
6466 mangleType(T);
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())
6471 continue;
6472 mangleValueInTemplateArg(Fields[I]->getType(),
6473 V.getStructField(Fields[I]->getFieldIndex()),
6474 false);
6476 Out << 'E';
6477 break;
6480 case APValue::Union: {
6481 assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
6482 const FieldDecl *FD = V.getUnionField();
6484 if (!FD) {
6485 Out << 'L';
6486 mangleType(T);
6487 Out << 'E';
6488 break;
6491 // <braced-expression> ::= di <field source-name> <braced-expression>
6492 NotPrimaryExpr();
6493 Out << "tl";
6494 mangleType(T);
6495 if (!isZeroInitialized(T, V)) {
6496 Out << "di";
6497 IdentifierInfo *II = (getUnionInitName(
6498 T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
6499 if (II)
6500 mangleSourceName(II);
6501 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
6503 Out << 'E';
6504 break;
6507 case APValue::Array: {
6508 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6510 NotPrimaryExpr();
6511 Out << "tl";
6512 mangleType(T);
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)))
6519 --N;
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);
6528 Out << 'E';
6529 break;
6532 case APValue::Vector: {
6533 const VectorType *VT = T->castAs<VectorType>();
6535 NotPrimaryExpr();
6536 Out << "tl";
6537 mangleType(T);
6538 unsigned N = V.getVectorLength();
6539 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
6540 --N;
6541 for (unsigned I = 0; I != N; ++I)
6542 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
6543 Out << 'E';
6544 break;
6547 case APValue::Int:
6548 mangleIntegerLiteral(T, V.getInt());
6549 break;
6551 case APValue::Float:
6552 mangleFloatLiteral(T, V.getFloat());
6553 break;
6555 case APValue::FixedPoint:
6556 mangleFixedPointLiteral();
6557 break;
6559 case APValue::ComplexFloat: {
6560 const ComplexType *CT = T->castAs<ComplexType>();
6561 NotPrimaryExpr();
6562 Out << "tl";
6563 mangleType(T);
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());
6569 Out << 'E';
6570 break;
6573 case APValue::ComplexInt: {
6574 const ComplexType *CT = T->castAs<ComplexType>();
6575 NotPrimaryExpr();
6576 Out << "tl";
6577 mangleType(T);
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());
6583 Out << 'E';
6584 break;
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);
6594 break;
6597 APValue::LValueBase B = V.getLValueBase();
6598 if (!B) {
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.
6605 NotPrimaryExpr();
6606 Out << "rc";
6607 mangleType(T);
6608 Out << "Li0E";
6609 if (TopLevel)
6610 Out << 'E';
6611 } else {
6612 Out << "L";
6613 mangleType(T);
6614 Out << Offset.getQuantity() << 'E';
6616 break;
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()) {
6625 NotPrimaryExpr();
6626 Out << "decvP";
6627 mangleType(T->getPointeeType());
6628 } else {
6629 NotPrimaryExpr();
6630 Out << "cv";
6631 mangleType(T);
6633 Out << "plcvPcad";
6634 Kind = Offset;
6635 } else {
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) {
6650 NotPrimaryExpr();
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()) {
6655 Out << "cv";
6656 mangleType(T);
6658 if (T->isPointerType())
6659 Out << "ad";
6660 Out << "so";
6661 mangleType(T->isVoidPointerType()
6662 ? getLValueType(Ctx, V).getUnqualifiedType()
6663 : T->getPointeeType());
6664 Kind = Path;
6665 } else {
6666 if (NeedExactType &&
6667 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
6668 !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6669 NotPrimaryExpr();
6670 Out << "cv";
6671 mangleType(T);
6673 if (T->isPointerType()) {
6674 NotPrimaryExpr();
6675 Out << "ad";
6677 Kind = Base;
6681 QualType TypeSoFar = B.getType();
6682 if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
6683 Out << 'L';
6684 mangle(VD);
6685 Out << 'E';
6686 } else if (auto *E = B.dyn_cast<const Expr*>()) {
6687 NotPrimaryExpr();
6688 mangleExpression(E);
6689 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
6690 NotPrimaryExpr();
6691 Out << "ti";
6692 mangleType(QualType(TI.getType(), 0));
6693 } else {
6694 // We should never see dynamic allocations here.
6695 llvm_unreachable("unexpected lvalue base kind in template argument");
6698 switch (Kind) {
6699 case Base:
6700 break;
6702 case Offset:
6703 Out << 'L';
6704 mangleType(Ctx.getPointerDiffType());
6705 mangleNumber(V.getLValueOffset().getQuantity());
6706 Out << 'E';
6707 break;
6709 case Path:
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();
6724 } else {
6725 const Decl *D = E.getAsBaseOrMember().getPointer();
6726 if (auto *FD = dyn_cast<FieldDecl>(D)) {
6727 // <union-selector> ::= _ <number>
6728 if (FD->getParent()->isUnion()) {
6729 Out << '_';
6730 if (FD->getFieldIndex())
6731 Out << (FD->getFieldIndex() - 1);
6733 TypeSoFar = FD->getType();
6734 } else {
6735 TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));
6740 if (OnePastTheEnd)
6741 Out << 'p';
6742 Out << 'E';
6743 break;
6746 break;
6749 case APValue::MemberPointer:
6750 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6751 if (!V.getMemberPointerDecl()) {
6752 mangleNullPointer(T);
6753 break;
6756 ASTContext &Ctx = Context.getASTContext();
6758 NotPrimaryExpr();
6759 if (!V.getMemberPointerPath().empty()) {
6760 Out << "mc";
6761 mangleType(T);
6762 } else if (NeedExactType &&
6763 !Ctx.hasSameType(
6764 T->castAs<MemberPointerType>()->getPointeeType(),
6765 V.getMemberPointerDecl()->getType()) &&
6766 !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6767 Out << "cv";
6768 mangleType(T);
6770 Out << "adL";
6771 mangle(V.getMemberPointerDecl());
6772 Out << 'E';
6773 if (!V.getMemberPointerPath().empty()) {
6774 CharUnits Offset =
6775 Context.getASTContext().getMemberPointerPathAdjustment(V);
6776 if (!Offset.isZero())
6777 mangleNumber(Offset.getQuantity());
6778 Out << 'E';
6780 break;
6783 if (TopLevel && !IsPrimaryExpr)
6784 Out << 'E';
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
6796 Out << 'T';
6797 Depth += TemplateDepthOffset;
6798 if (Depth != 0)
6799 Out << 'L' << (Depth - 1) << '_';
6800 if (Index != 0)
6801 Out << (Index - 1);
6802 Out << '_';
6805 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
6806 if (SeqID == 0) {
6807 // Nothing.
6808 } else if (SeqID == 1) {
6809 Out << '0';
6810 } else {
6811 SeqID--;
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());
6825 Out << '_';
6828 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
6829 bool result = mangleSubstitution(tname);
6830 assert(result && "no existing substitution for template name");
6831 (void) result;
6834 // <substitution> ::= S <seq-id> _
6835 // ::= S_
6836 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
6837 // Try one of the standard substitutions first.
6838 if (mangleStandardSubstitution(ND))
6839 return true;
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
6854 /// substitutions.
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())
6883 return false;
6885 unsigned SeqID = I->second;
6886 Out << 'S';
6887 mangleSeqID(SeqID);
6889 return true;
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,
6895 QualType A) {
6896 if (S.isNull())
6897 return false;
6899 const RecordType *RT = S->getAs<RecordType>();
6900 if (!RT)
6901 return false;
6903 const ClassTemplateSpecializationDecl *SD =
6904 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6905 if (!SD || !SD->getIdentifier()->isStr(Name))
6906 return false;
6908 if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6909 return false;
6911 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6912 if (TemplateArgs.size() != 1)
6913 return false;
6915 if (TemplateArgs[0].getAsType() != A)
6916 return false;
6918 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6919 return false;
6921 return true;
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))
6931 return false;
6933 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6934 if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
6935 return false;
6937 QualType A = TemplateArgs[0].getAsType();
6938 if (A.isNull())
6939 return false;
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))
6943 return false;
6945 if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))
6946 return false;
6948 if (HasAllocator &&
6949 !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))
6950 return false;
6952 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6953 return false;
6955 return true;
6958 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
6959 // <substitution> ::= St # ::std::
6960 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
6961 if (isStd(NS)) {
6962 Out << "St";
6963 return true;
6965 return false;
6968 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
6969 if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))
6970 return false;
6972 if (TD->getOwningModuleForLinkage())
6973 return false;
6975 // <substitution> ::= Sa # ::std::allocator
6976 if (TD->getIdentifier()->isStr("allocator")) {
6977 Out << "Sa";
6978 return true;
6981 // <<substitution> ::= Sb # ::std::basic_string
6982 if (TD->getIdentifier()->isStr("basic_string")) {
6983 Out << "Sb";
6984 return true;
6986 return false;
6989 if (const ClassTemplateSpecializationDecl *SD =
6990 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
6991 if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6992 return false;
6994 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6995 return false;
6997 // <substitution> ::= Ss # ::std::basic_string<char,
6998 // ::std::char_traits<char>,
6999 // ::std::allocator<char> >
7000 if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {
7001 Out << "Ss";
7002 return true;
7005 // <substitution> ::= Si # ::std::basic_istream<char,
7006 // ::std::char_traits<char> >
7007 if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {
7008 Out << "Si";
7009 return true;
7012 // <substitution> ::= So # ::std::basic_ostream<char,
7013 // ::std::char_traits<char> >
7014 if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {
7015 Out << "So";
7016 return true;
7019 // <substitution> ::= Sd # ::std::basic_iostream<char,
7020 // ::std::char_traits<char> >
7021 if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {
7022 Out << "Sd";
7023 return true;
7025 return false;
7028 return false;
7031 void CXXNameMangler::addSubstitution(QualType T) {
7032 if (!hasMangledSubstitutionQualifiers(T)) {
7033 if (const RecordType *RT = T->getAs<RecordType>()) {
7034 addSubstitution(RT->getDecl());
7035 return;
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
7111 /// output stream.
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
7117 /// name.
7118 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
7119 raw_ostream &Out) {
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);
7141 Mangler.mangle(GD);
7144 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
7145 raw_ostream &Out) {
7146 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
7147 Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
7150 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
7151 raw_ostream &Out) {
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
7162 /// <key>
7163 /// <addressDiscriminated>
7164 /// <extraDiscriminator>
7165 /// E
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
7170 /// type name.
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;
7190 else
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;
7199 else
7200 ManglerStream << "Lj" << 0;
7201 break;
7203 case VTablePointerAuthenticationAttr::TypeDiscrimination:
7204 ManglerStream << "Lj" << TypedDiscriminator;
7205 break;
7206 case VTablePointerAuthenticationAttr::CustomDiscrimination:
7207 ManglerStream << "Lj" << ExplicitAuth->getCustomDiscriminationValue();
7208 break;
7209 case VTablePointerAuthenticationAttr::NoExtraDiscrimination:
7210 ManglerStream << "Lj" << 0;
7211 break;
7213 } else {
7214 ManglerStream << "Lj"
7215 << (unsigned)VTablePointerAuthenticationAttr::DefaultKey;
7216 ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;
7217 if (LangOpts.PointerAuthVTPtrTypeDiscrimination)
7218 ManglerStream << "Lj" << TypedDiscriminator;
7219 else
7220 ManglerStream << "Lj" << 0;
7222 ManglerStream << "E";
7225 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
7226 const ThunkInfo &Thunk,
7227 bool ElideOverrideInfo,
7228 raw_ostream &Out) {
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,
7258 CXXDtorType Type,
7259 const ThunkInfo &Thunk,
7260 bool ElideOverrideInfo,
7261 raw_ostream &Out) {
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,
7279 raw_ostream &Out) {
7280 // <special-name> ::= GV <object name> # Guard variable for one-time
7281 // # initialization
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,
7290 raw_ostream &Out) {
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,
7298 raw_ostream &Out) {
7299 // Prefix the mangling of D with __dtor_.
7300 CXXNameMangler Mangler(*this, Out);
7301 Mangler.getStream() << "__dtor_";
7302 if (shouldMangleDeclName(D))
7303 Mangler.mangle(D);
7304 else
7305 Mangler.getStream() << D->getName();
7308 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
7309 raw_ostream &Out) {
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))
7315 Mangler.mangle(D);
7316 else
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);
7327 else
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);
7338 else
7339 Mangler.getStream() << EnclosingFD->getName();
7342 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
7343 raw_ostream &Out) {
7344 // <special-name> ::= TH <object name>
7345 CXXNameMangler Mangler(*this, Out);
7346 Mangler.getStream() << "_ZTH";
7347 Mangler.mangleName(D);
7350 void
7351 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
7352 raw_ostream &Out) {
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,
7361 raw_ostream &Out) {
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,
7372 raw_ostream &Out) {
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,
7380 raw_ostream &Out) {
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,
7388 int64_t Offset,
7389 const CXXRecordDecl *Type,
7390 raw_ostream &Out) {
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,
7426 raw_ostream &Out) {
7427 CXXNameMangler Mangler(*this, Out);
7428 Mangler.mangleLambdaSig(Lambda);
7431 void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
7432 raw_ostream &Out) {
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,
7448 bool IsAux) {
7449 return new ItaniumMangleContextImpl(
7450 Context, Diags,
7451 [](ASTContext &, const NamedDecl *) -> std::optional<unsigned> {
7452 return std::nullopt;
7454 IsAux);
7457 ItaniumMangleContext *
7458 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,
7459 DiscriminatorOverrideTy DiscriminatorOverride,
7460 bool IsAux) {
7461 return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,
7462 IsAux);