clang 20.0.0git
ItaniumMangle.cpp
Go to the documentation of this file.
1//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implements C++ name mangling according to the Itanium C++ ABI,
10// which is used in GCC 3.2 and newer (and many compilers that are
11// ABI-compatible with GCC):
12//
13// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
14//
15//===----------------------------------------------------------------------===//
16
18#include "clang/AST/Attr.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.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"
32#include "clang/Basic/Module.h"
35#include "clang/Basic/Thunk.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/TargetParser/RISCVTargetParser.h"
40#include <optional>
41
42using namespace clang;
43
44namespace {
45
46static bool isLocalContainerContext(const DeclContext *DC) {
47 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
48}
49
50static const FunctionDecl *getStructor(const FunctionDecl *fn) {
51 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
52 return ftd->getTemplatedDecl();
53
54 return fn;
55}
56
57static const NamedDecl *getStructor(const NamedDecl *decl) {
58 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
59 return (fn ? getStructor(fn) : decl);
60}
61
62static bool isLambda(const NamedDecl *ND) {
63 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
64 if (!Record)
65 return false;
66
67 return Record->isLambda();
68}
69
70static const unsigned UnknownArity = ~0U;
71
72class ItaniumMangleContextImpl : public ItaniumMangleContext {
73 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
74 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
75 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
76 const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
77 NamespaceDecl *StdNamespace = nullptr;
78
79 bool NeedsUniqueInternalLinkageNames = false;
80
81public:
82 explicit ItaniumMangleContextImpl(
83 ASTContext &Context, DiagnosticsEngine &Diags,
84 DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
85 : ItaniumMangleContext(Context, Diags, IsAux),
86 DiscriminatorOverride(DiscriminatorOverride) {}
87
88 /// @name Mangler Entry Points
89 /// @{
90
91 bool shouldMangleCXXName(const NamedDecl *D) override;
92 bool shouldMangleStringLiteral(const StringLiteral *) override {
93 return false;
94 }
95
96 bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
97 void needsUniqueInternalLinkageNames() override {
98 NeedsUniqueInternalLinkageNames = true;
99 }
100
101 void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
102 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, bool,
103 raw_ostream &) override;
105 const ThunkInfo &Thunk, bool, raw_ostream &) override;
106 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
107 raw_ostream &) override;
108 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
109 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
110 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
111 const CXXRecordDecl *Type, raw_ostream &) override;
112 void mangleCXXRTTI(QualType T, raw_ostream &) override;
113 void mangleCXXRTTIName(QualType T, raw_ostream &,
114 bool NormalizeIntegers) override;
115 void mangleCanonicalTypeName(QualType T, raw_ostream &,
116 bool NormalizeIntegers) override;
117
118 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
119 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
120 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
121 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
123 raw_ostream &Out) override;
124 void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
125 void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
126 raw_ostream &Out) override;
127 void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
128 raw_ostream &Out) override;
129 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
131 raw_ostream &) override;
132
133 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
134
135 void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
136
137 void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
138
139 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
140 // Lambda closure types are already numbered.
141 if (isLambda(ND))
142 return false;
143
144 // Anonymous tags are already numbered.
145 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
146 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
147 return false;
148 }
149
150 // Use the canonical number for externally visible decls.
151 if (ND->isExternallyVisible()) {
152 unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
153 if (discriminator == 1)
154 return false;
155 disc = discriminator - 2;
156 return true;
157 }
158
159 // Make up a reasonable number for internal decls.
160 unsigned &discriminator = Uniquifier[ND];
161 if (!discriminator) {
162 const DeclContext *DC = getEffectiveDeclContext(ND);
163 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
164 }
165 if (discriminator == 1)
166 return false;
167 disc = discriminator-2;
168 return true;
169 }
170
171 std::string getLambdaString(const CXXRecordDecl *Lambda) override {
172 // This function matches the one in MicrosoftMangle, which returns
173 // the string that is used in lambda mangled names.
174 assert(Lambda->isLambda() && "RD must be a lambda!");
175 std::string Name("<lambda");
176 Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
177 unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
178 unsigned LambdaId;
179 const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
180 const FunctionDecl *Func =
181 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
182
183 if (Func) {
184 unsigned DefaultArgNo =
185 Func->getNumParams() - Parm->getFunctionScopeIndex();
186 Name += llvm::utostr(DefaultArgNo);
187 Name += "_";
188 }
189
190 if (LambdaManglingNumber)
191 LambdaId = LambdaManglingNumber;
192 else
193 LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
194
195 Name += llvm::utostr(LambdaId);
196 Name += '>';
197 return Name;
198 }
199
200 DiscriminatorOverrideTy getDiscriminatorOverride() const override {
201 return DiscriminatorOverride;
202 }
203
204 NamespaceDecl *getStdNamespace();
205
206 const DeclContext *getEffectiveDeclContext(const Decl *D);
207 const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
208 return getEffectiveDeclContext(cast<Decl>(DC));
209 }
210
211 bool isInternalLinkageDecl(const NamedDecl *ND);
212
213 /// @}
214};
215
216/// Manage the mangling of a single name.
217class CXXNameMangler {
218 ItaniumMangleContextImpl &Context;
219 raw_ostream &Out;
220 /// Normalize integer types for cross-language CFI support with other
221 /// languages that can't represent and encode C/C++ integer types.
222 bool NormalizeIntegers = false;
223
224 bool NullOut = false;
225 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
226 /// This mode is used when mangler creates another mangler recursively to
227 /// calculate ABI tags for the function return value or the variable type.
228 /// Also it is required to avoid infinite recursion in some cases.
229 bool DisableDerivedAbiTags = false;
230
231 /// The "structor" is the top-level declaration being mangled, if
232 /// that's not a template specialization; otherwise it's the pattern
233 /// for that specialization.
234 const NamedDecl *Structor;
235 unsigned StructorType = 0;
236
237 // An offset to add to all template parameter depths while mangling. Used
238 // when mangling a template parameter list to see if it matches a template
239 // template parameter exactly.
240 unsigned TemplateDepthOffset = 0;
241
242 /// The next substitution sequence number.
243 unsigned SeqID = 0;
244
245 class FunctionTypeDepthState {
246 unsigned Bits = 0;
247
248 enum { InResultTypeMask = 1 };
249
250 public:
251 FunctionTypeDepthState() = default;
252
253 /// The number of function types we're inside.
254 unsigned getDepth() const {
255 return Bits >> 1;
256 }
257
258 /// True if we're in the return type of the innermost function type.
259 bool isInResultType() const {
260 return Bits & InResultTypeMask;
261 }
262
263 FunctionTypeDepthState push() {
264 FunctionTypeDepthState tmp = *this;
265 Bits = (Bits & ~InResultTypeMask) + 2;
266 return tmp;
267 }
268
269 void enterResultType() {
270 Bits |= InResultTypeMask;
271 }
272
273 void leaveResultType() {
274 Bits &= ~InResultTypeMask;
275 }
276
277 void pop(FunctionTypeDepthState saved) {
278 assert(getDepth() == saved.getDepth() + 1);
279 Bits = saved.Bits;
280 }
281
282 } FunctionTypeDepth;
283
284 // abi_tag is a gcc attribute, taking one or more strings called "tags".
285 // The goal is to annotate against which version of a library an object was
286 // built and to be able to provide backwards compatibility ("dual abi").
287 // For more information see docs/ItaniumMangleAbiTags.rst.
288 typedef SmallVector<StringRef, 4> AbiTagList;
289
290 // State to gather all implicit and explicit tags used in a mangled name.
291 // Must always have an instance of this while emitting any name to keep
292 // track.
293 class AbiTagState final {
294 public:
295 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
296 Parent = LinkHead;
297 LinkHead = this;
298 }
299
300 // No copy, no move.
301 AbiTagState(const AbiTagState &) = delete;
302 AbiTagState &operator=(const AbiTagState &) = delete;
303
304 ~AbiTagState() { pop(); }
305
306 void write(raw_ostream &Out, const NamedDecl *ND,
307 const AbiTagList *AdditionalAbiTags) {
308 ND = cast<NamedDecl>(ND->getCanonicalDecl());
309 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
310 assert(
311 !AdditionalAbiTags &&
312 "only function and variables need a list of additional abi tags");
313 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
314 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
315 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
316 AbiTag->tags().end());
317 }
318 // Don't emit abi tags for namespaces.
319 return;
320 }
321 }
322
323 AbiTagList TagList;
324 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
325 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
326 AbiTag->tags().end());
327 TagList.insert(TagList.end(), AbiTag->tags().begin(),
328 AbiTag->tags().end());
329 }
330
331 if (AdditionalAbiTags) {
332 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
333 AdditionalAbiTags->end());
334 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
335 AdditionalAbiTags->end());
336 }
337
338 llvm::sort(TagList);
339 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
340
341 writeSortedUniqueAbiTags(Out, TagList);
342 }
343
344 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
345 void setUsedAbiTags(const AbiTagList &AbiTags) {
346 UsedAbiTags = AbiTags;
347 }
348
349 const AbiTagList &getEmittedAbiTags() const {
350 return EmittedAbiTags;
351 }
352
353 const AbiTagList &getSortedUniqueUsedAbiTags() {
354 llvm::sort(UsedAbiTags);
355 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
356 UsedAbiTags.end());
357 return UsedAbiTags;
358 }
359
360 private:
361 //! All abi tags used implicitly or explicitly.
362 AbiTagList UsedAbiTags;
363 //! All explicit abi tags (i.e. not from namespace).
364 AbiTagList EmittedAbiTags;
365
366 AbiTagState *&LinkHead;
367 AbiTagState *Parent = nullptr;
368
369 void pop() {
370 assert(LinkHead == this &&
371 "abi tag link head must point to us on destruction");
372 if (Parent) {
373 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
374 UsedAbiTags.begin(), UsedAbiTags.end());
375 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
376 EmittedAbiTags.begin(),
377 EmittedAbiTags.end());
378 }
379 LinkHead = Parent;
380 }
381
382 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
383 for (const auto &Tag : AbiTags) {
384 EmittedAbiTags.push_back(Tag);
385 Out << "B";
386 Out << Tag.size();
387 Out << Tag;
388 }
389 }
390 };
391
392 AbiTagState *AbiTags = nullptr;
393 AbiTagState AbiTagsRoot;
394
395 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
396 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
397
398 ASTContext &getASTContext() const { return Context.getASTContext(); }
399
400 bool isCompatibleWith(LangOptions::ClangABI Ver) {
401 return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver;
402 }
403
404 bool isStd(const NamespaceDecl *NS);
405 bool isStdNamespace(const DeclContext *DC);
406
407 const RecordDecl *GetLocalClassDecl(const Decl *D);
408 bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
409 bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
410 llvm::StringRef Name, bool HasAllocator);
411
412public:
413 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
414 const NamedDecl *D = nullptr, bool NullOut_ = false)
415 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
416 AbiTagsRoot(AbiTags) {
417 // These can't be mangled without a ctor type or dtor type.
418 assert(!D || (!isa<CXXDestructorDecl>(D) &&
419 !isa<CXXConstructorDecl>(D)));
420 }
421 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
423 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
424 AbiTagsRoot(AbiTags) {}
425 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
427 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
428 AbiTagsRoot(AbiTags) {}
429
430 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
431 bool NormalizeIntegers_)
432 : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),
433 NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}
434 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
435 : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
436 StructorType(Outer.StructorType), SeqID(Outer.SeqID),
437 FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
438 Substitutions(Outer.Substitutions),
439 ModuleSubstitutions(Outer.ModuleSubstitutions) {}
440
441 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
442 : CXXNameMangler(Outer, (raw_ostream &)Out_) {
443 NullOut = true;
444 }
445
446 struct WithTemplateDepthOffset { unsigned Offset; };
447 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out,
448 WithTemplateDepthOffset Offset)
449 : CXXNameMangler(C, Out) {
450 TemplateDepthOffset = Offset.Offset;
451 }
452
453 raw_ostream &getStream() { return Out; }
454
455 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
456 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
457
458 void mangle(GlobalDecl GD);
459 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
460 void mangleNumber(const llvm::APSInt &I);
461 void mangleNumber(int64_t Number);
462 void mangleFloat(const llvm::APFloat &F);
463 void mangleFunctionEncoding(GlobalDecl GD);
464 void mangleSeqID(unsigned SeqID);
465 void mangleName(GlobalDecl GD);
466 void mangleType(QualType T);
467 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
468 void mangleLambdaSig(const CXXRecordDecl *Lambda);
469 void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
470 void mangleVendorQualifier(StringRef Name);
471
472private:
473
474 bool mangleSubstitution(const NamedDecl *ND);
475 bool mangleSubstitution(NestedNameSpecifier *NNS);
476 bool mangleSubstitution(QualType T);
477 bool mangleSubstitution(TemplateName Template);
478 bool mangleSubstitution(uintptr_t Ptr);
479
480 void mangleExistingSubstitution(TemplateName name);
481
482 bool mangleStandardSubstitution(const NamedDecl *ND);
483
484 void addSubstitution(const NamedDecl *ND) {
485 ND = cast<NamedDecl>(ND->getCanonicalDecl());
486
487 addSubstitution(reinterpret_cast<uintptr_t>(ND));
488 }
489 void addSubstitution(NestedNameSpecifier *NNS) {
490 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
491
492 addSubstitution(reinterpret_cast<uintptr_t>(NNS));
493 }
494 void addSubstitution(QualType T);
495 void addSubstitution(TemplateName Template);
496 void addSubstitution(uintptr_t Ptr);
497 // Destructive copy substitutions from other mangler.
498 void extendSubstitutions(CXXNameMangler* Other);
499
500 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
501 bool recursive = false);
502 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
503 DeclarationName name,
504 const TemplateArgumentLoc *TemplateArgs,
505 unsigned NumTemplateArgs,
506 unsigned KnownArity = UnknownArity);
507
508 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
509
510 void mangleNameWithAbiTags(GlobalDecl GD,
511 const AbiTagList *AdditionalAbiTags);
512 void mangleModuleName(const NamedDecl *ND);
513 void mangleTemplateName(const TemplateDecl *TD,
515 void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
516 const AbiTagList *AdditionalAbiTags) {
517 mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
518 UnknownArity, AdditionalAbiTags);
519 }
520 void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
521 const DeclContext *DC, unsigned KnownArity,
522 const AbiTagList *AdditionalAbiTags);
523 void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
524 const AbiTagList *AdditionalAbiTags);
525 void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
526 const AbiTagList *AdditionalAbiTags);
527 void mangleSourceName(const IdentifierInfo *II);
528 void mangleRegCallName(const IdentifierInfo *II);
529 void mangleDeviceStubName(const IdentifierInfo *II);
530 void mangleSourceNameWithAbiTags(
531 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
532 void mangleLocalName(GlobalDecl GD,
533 const AbiTagList *AdditionalAbiTags);
534 void mangleBlockForPrefix(const BlockDecl *Block);
535 void mangleUnqualifiedBlock(const BlockDecl *Block);
536 void mangleTemplateParamDecl(const NamedDecl *Decl);
537 void mangleTemplateParameterList(const TemplateParameterList *Params);
538 void mangleTypeConstraint(const ConceptDecl *Concept,
540 void mangleTypeConstraint(const TypeConstraint *Constraint);
541 void mangleRequiresClause(const Expr *RequiresClause);
542 void mangleLambda(const CXXRecordDecl *Lambda);
543 void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
544 const AbiTagList *AdditionalAbiTags,
545 bool NoFunction=false);
546 void mangleNestedName(const TemplateDecl *TD,
548 void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
549 const NamedDecl *PrefixND,
550 const AbiTagList *AdditionalAbiTags);
551 void manglePrefix(NestedNameSpecifier *qualifier);
552 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
553 void manglePrefix(QualType type);
554 void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
555 void mangleTemplatePrefix(TemplateName Template);
556 const NamedDecl *getClosurePrefix(const Decl *ND);
557 void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
558 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
559 StringRef Prefix = "");
560 void mangleOperatorName(DeclarationName Name, unsigned Arity);
561 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
562 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
563 void mangleRefQualifier(RefQualifierKind RefQualifier);
564
565 void mangleObjCMethodName(const ObjCMethodDecl *MD);
566
567 // Declare manglers for every type class.
568#define ABSTRACT_TYPE(CLASS, PARENT)
569#define NON_CANONICAL_TYPE(CLASS, PARENT)
570#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
571#include "clang/AST/TypeNodes.inc"
572
573 void mangleType(const TagType*);
574 void mangleType(TemplateName);
575 static StringRef getCallingConvQualifierName(CallingConv CC);
576 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
577 void mangleExtFunctionInfo(const FunctionType *T);
578 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
579 const FunctionDecl *FD = nullptr);
580 void mangleNeonVectorType(const VectorType *T);
581 void mangleNeonVectorType(const DependentVectorType *T);
582 void mangleAArch64NeonVectorType(const VectorType *T);
583 void mangleAArch64NeonVectorType(const DependentVectorType *T);
584 void mangleAArch64FixedSveVectorType(const VectorType *T);
585 void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
586 void mangleRISCVFixedRVVVectorType(const VectorType *T);
587 void mangleRISCVFixedRVVVectorType(const DependentVectorType *T);
588
589 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
590 void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
591 void mangleFixedPointLiteral();
592 void mangleNullPointer(QualType T);
593
594 void mangleMemberExprBase(const Expr *base, bool isArrow);
595 void mangleMemberExpr(const Expr *base, bool isArrow,
596 NestedNameSpecifier *qualifier,
597 NamedDecl *firstQualifierLookup,
598 DeclarationName name,
599 const TemplateArgumentLoc *TemplateArgs,
600 unsigned NumTemplateArgs,
601 unsigned knownArity);
602 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
603 void mangleInitListElements(const InitListExpr *InitList);
604 void mangleRequirement(SourceLocation RequiresExprLoc,
605 const concepts::Requirement *Req);
606 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
607 bool AsTemplateArg = false);
608 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
609 void mangleCXXDtorType(CXXDtorType T);
610
611 struct TemplateArgManglingInfo;
612 void mangleTemplateArgs(TemplateName TN,
613 const TemplateArgumentLoc *TemplateArgs,
614 unsigned NumTemplateArgs);
615 void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);
616 void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
617 void mangleTemplateArg(TemplateArgManglingInfo &Info, unsigned Index,
619 void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
620 void mangleTemplateArgExpr(const Expr *E);
621 void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
622 bool NeedExactType = false);
623
624 void mangleTemplateParameter(unsigned Depth, unsigned Index);
625
626 void mangleFunctionParam(const ParmVarDecl *parm);
627
628 void writeAbiTags(const NamedDecl *ND,
629 const AbiTagList *AdditionalAbiTags);
630
631 // Returns sorted unique list of ABI tags.
632 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
633 // Returns sorted unique list of ABI tags.
634 AbiTagList makeVariableTypeTags(const VarDecl *VD);
635};
636
637}
638
639NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
640 if (!StdNamespace) {
641 StdNamespace = NamespaceDecl::Create(
642 getASTContext(), getASTContext().getTranslationUnitDecl(),
643 /*Inline=*/false, SourceLocation(), SourceLocation(),
644 &getASTContext().Idents.get("std"),
645 /*PrevDecl=*/nullptr, /*Nested=*/false);
646 StdNamespace->setImplicit();
647 }
648 return StdNamespace;
649}
650
651/// Retrieve the declaration context that should be used when mangling the given
652/// declaration.
653const DeclContext *
654ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
655 // The ABI assumes that lambda closure types that occur within
656 // default arguments live in the context of the function. However, due to
657 // the way in which Clang parses and creates function declarations, this is
658 // not the case: the lambda closure type ends up living in the context
659 // where the function itself resides, because the function declaration itself
660 // had not yet been created. Fix the context here.
661 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
662 if (RD->isLambda())
663 if (ParmVarDecl *ContextParam =
664 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
665 return ContextParam->getDeclContext();
666 }
667
668 // Perform the same check for block literals.
669 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
670 if (ParmVarDecl *ContextParam =
671 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
672 return ContextParam->getDeclContext();
673 }
674
675 // On ARM and AArch64, the va_list tag is always mangled as if in the std
676 // namespace. We do not represent va_list as actually being in the std
677 // namespace in C because this would result in incorrect debug info in C,
678 // among other things. It is important for both languages to have the same
679 // mangling in order for -fsanitize=cfi-icall to work.
680 if (D == getASTContext().getVaListTagDecl()) {
681 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
682 if (T.isARM() || T.isThumb() || T.isAArch64())
683 return getStdNamespace();
684 }
685
686 const DeclContext *DC = D->getDeclContext();
687 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
688 isa<OMPDeclareMapperDecl>(DC)) {
689 return getEffectiveDeclContext(cast<Decl>(DC));
690 }
691
692 if (const auto *VD = dyn_cast<VarDecl>(D))
693 if (VD->isExternC())
694 return getASTContext().getTranslationUnitDecl();
695
696 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
697 if (FD->isExternC())
698 return getASTContext().getTranslationUnitDecl();
699 // Member-like constrained friends are mangled as if they were members of
700 // the enclosing class.
701 if (FD->isMemberLikeConstrainedFriend() &&
702 getASTContext().getLangOpts().getClangABICompat() >
703 LangOptions::ClangABI::Ver17)
705 }
706
707 return DC->getRedeclContext();
708}
709
710bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
711 if (ND && ND->getFormalLinkage() == Linkage::Internal &&
712 !ND->isExternallyVisible() &&
713 getEffectiveDeclContext(ND)->isFileContext() &&
715 return true;
716 return false;
717}
718
719// Check if this Function Decl needs a unique internal linkage name.
720bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
721 const NamedDecl *ND) {
722 if (!NeedsUniqueInternalLinkageNames || !ND)
723 return false;
724
725 const auto *FD = dyn_cast<FunctionDecl>(ND);
726 if (!FD)
727 return false;
728
729 // For C functions without prototypes, return false as their
730 // names should not be mangled.
731 if (!FD->getType()->getAs<FunctionProtoType>())
732 return false;
733
734 if (isInternalLinkageDecl(ND))
735 return true;
736
737 return false;
738}
739
740bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
741 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
742 LanguageLinkage L = FD->getLanguageLinkage();
743 // Overloadable functions need mangling.
744 if (FD->hasAttr<OverloadableAttr>())
745 return true;
746
747 // "main" is not mangled.
748 if (FD->isMain())
749 return false;
750
751 // The Windows ABI expects that we would never mangle "typical"
752 // user-defined entry points regardless of visibility or freestanding-ness.
753 //
754 // N.B. This is distinct from asking about "main". "main" has a lot of
755 // special rules associated with it in the standard while these
756 // user-defined entry points are outside of the purview of the standard.
757 // For example, there can be only one definition for "main" in a standards
758 // compliant program; however nothing forbids the existence of wmain and
759 // WinMain in the same translation unit.
760 if (FD->isMSVCRTEntryPoint())
761 return false;
762
763 // C++ functions and those whose names are not a simple identifier need
764 // mangling.
765 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
766 return true;
767
768 // C functions are not mangled.
769 if (L == CLanguageLinkage)
770 return false;
771 }
772
773 // Otherwise, no mangling is done outside C++ mode.
774 if (!getASTContext().getLangOpts().CPlusPlus)
775 return false;
776
777 if (const auto *VD = dyn_cast<VarDecl>(D)) {
778 // Decompositions are mangled.
779 if (isa<DecompositionDecl>(VD))
780 return true;
781
782 // C variables are not mangled.
783 if (VD->isExternC())
784 return false;
785
786 // Variables at global scope are not mangled unless they have internal
787 // linkage or are specializations or are attached to a named module.
788 const DeclContext *DC = getEffectiveDeclContext(D);
789 // Check for extern variable declared locally.
790 if (DC->isFunctionOrMethod() && D->hasLinkage())
791 while (!DC->isFileContext())
792 DC = getEffectiveParentContext(DC);
793 if (DC->isTranslationUnit() && D->getFormalLinkage() != Linkage::Internal &&
794 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
795 !isa<VarTemplateSpecializationDecl>(VD) &&
797 return false;
798 }
799
800 return true;
801}
802
803void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
804 const AbiTagList *AdditionalAbiTags) {
805 assert(AbiTags && "require AbiTagState");
806 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
807}
808
809void CXXNameMangler::mangleSourceNameWithAbiTags(
810 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
811 mangleSourceName(ND->getIdentifier());
812 writeAbiTags(ND, AdditionalAbiTags);
813}
814
815void CXXNameMangler::mangle(GlobalDecl GD) {
816 // <mangled-name> ::= _Z <encoding>
817 // ::= <data name>
818 // ::= <special-name>
819 Out << "_Z";
820 if (isa<FunctionDecl>(GD.getDecl()))
821 mangleFunctionEncoding(GD);
823 BindingDecl>(GD.getDecl()))
824 mangleName(GD);
825 else if (const IndirectFieldDecl *IFD =
826 dyn_cast<IndirectFieldDecl>(GD.getDecl()))
827 mangleName(IFD->getAnonField());
828 else
829 llvm_unreachable("unexpected kind of global decl");
830}
831
832void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
833 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
834 // <encoding> ::= <function name> <bare-function-type>
835
836 // Don't mangle in the type if this isn't a decl we should typically mangle.
837 if (!Context.shouldMangleDeclName(FD)) {
838 mangleName(GD);
839 return;
840 }
841
842 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
843 if (ReturnTypeAbiTags.empty()) {
844 // There are no tags for return type, the simplest case. Enter the function
845 // parameter scope before mangling the name, because a template using
846 // constrained `auto` can have references to its parameters within its
847 // template argument list:
848 //
849 // template<typename T> void f(T x, C<decltype(x)> auto)
850 // ... is mangled as ...
851 // template<typename T, C<decltype(param 1)> U> void f(T, U)
852 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
853 mangleName(GD);
854 FunctionTypeDepth.pop(Saved);
855 mangleFunctionEncodingBareType(FD);
856 return;
857 }
858
859 // Mangle function name and encoding to temporary buffer.
860 // We have to output name and encoding to the same mangler to get the same
861 // substitution as it will be in final mangling.
862 SmallString<256> FunctionEncodingBuf;
863 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
864 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
865 // Output name of the function.
866 FunctionEncodingMangler.disableDerivedAbiTags();
867
868 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
869 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
870 FunctionTypeDepth.pop(Saved);
871
872 // Remember length of the function name in the buffer.
873 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
874 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
875
876 // Get tags from return type that are not present in function name or
877 // encoding.
878 const AbiTagList &UsedAbiTags =
879 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
880 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
881 AdditionalAbiTags.erase(
882 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
883 UsedAbiTags.begin(), UsedAbiTags.end(),
884 AdditionalAbiTags.begin()),
885 AdditionalAbiTags.end());
886
887 // Output name with implicit tags and function encoding from temporary buffer.
888 Saved = FunctionTypeDepth.push();
889 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
890 FunctionTypeDepth.pop(Saved);
891 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
892
893 // Function encoding could create new substitutions so we have to add
894 // temp mangled substitutions to main mangler.
895 extendSubstitutions(&FunctionEncodingMangler);
896}
897
898void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
899 if (FD->hasAttr<EnableIfAttr>()) {
900 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
901 Out << "Ua9enable_ifI";
902 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
903 E = FD->getAttrs().end();
904 I != E; ++I) {
905 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
906 if (!EIA)
907 continue;
908 if (isCompatibleWith(LangOptions::ClangABI::Ver11)) {
909 // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
910 // even though <template-arg> should not include an X/E around
911 // <expr-primary>.
912 Out << 'X';
913 mangleExpression(EIA->getCond());
914 Out << 'E';
915 } else {
916 mangleTemplateArgExpr(EIA->getCond());
917 }
918 }
919 Out << 'E';
920 FunctionTypeDepth.pop(Saved);
921 }
922
923 // When mangling an inheriting constructor, the bare function type used is
924 // that of the inherited constructor.
925 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
926 if (auto Inherited = CD->getInheritedConstructor())
927 FD = Inherited.getConstructor();
928
929 // Whether the mangling of a function type includes the return type depends on
930 // the context and the nature of the function. The rules for deciding whether
931 // the return type is included are:
932 //
933 // 1. Template functions (names or types) have return types encoded, with
934 // the exceptions listed below.
935 // 2. Function types not appearing as part of a function name mangling,
936 // e.g. parameters, pointer types, etc., have return type encoded, with the
937 // exceptions listed below.
938 // 3. Non-template function names do not have return types encoded.
939 //
940 // The exceptions mentioned in (1) and (2) above, for which the return type is
941 // never included, are
942 // 1. Constructors.
943 // 2. Destructors.
944 // 3. Conversion operator functions, e.g. operator int.
945 bool MangleReturnType = false;
946 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
947 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
948 isa<CXXConversionDecl>(FD)))
949 MangleReturnType = true;
950
951 // Mangle the type of the primary template.
952 FD = PrimaryTemplate->getTemplatedDecl();
953 }
954
955 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
956 MangleReturnType, FD);
957}
958
959/// Return whether a given namespace is the 'std' namespace.
960bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
961 if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
962 return false;
963
964 const IdentifierInfo *II = NS->getFirstDecl()->getIdentifier();
965 return II && II->isStr("std");
966}
967
968// isStdNamespace - Return whether a given decl context is a toplevel 'std'
969// namespace.
970bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
971 if (!DC->isNamespace())
972 return false;
973
974 return isStd(cast<NamespaceDecl>(DC));
975}
976
977static const GlobalDecl
978isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
979 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
980 // Check if we have a function template.
981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
982 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
983 TemplateArgs = FD->getTemplateSpecializationArgs();
984 return GD.getWithDecl(TD);
985 }
986 }
987
988 // Check if we have a class template.
989 if (const ClassTemplateSpecializationDecl *Spec =
990 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
991 TemplateArgs = &Spec->getTemplateArgs();
992 return GD.getWithDecl(Spec->getSpecializedTemplate());
993 }
994
995 // Check if we have a variable template.
996 if (const VarTemplateSpecializationDecl *Spec =
997 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
998 TemplateArgs = &Spec->getTemplateArgs();
999 return GD.getWithDecl(Spec->getSpecializedTemplate());
1000 }
1001
1002 return GlobalDecl();
1003}
1004
1006 const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
1007 return TemplateName(const_cast<TemplateDecl*>(TD));
1008}
1009
1010void CXXNameMangler::mangleName(GlobalDecl GD) {
1011 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1012 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1013 // Variables should have implicit tags from its type.
1014 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
1015 if (VariableTypeAbiTags.empty()) {
1016 // Simple case no variable type tags.
1017 mangleNameWithAbiTags(VD, nullptr);
1018 return;
1019 }
1020
1021 // Mangle variable name to null stream to collect tags.
1022 llvm::raw_null_ostream NullOutStream;
1023 CXXNameMangler VariableNameMangler(*this, NullOutStream);
1024 VariableNameMangler.disableDerivedAbiTags();
1025 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
1026
1027 // Get tags from variable type that are not present in its name.
1028 const AbiTagList &UsedAbiTags =
1029 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
1030 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
1031 AdditionalAbiTags.erase(
1032 std::set_difference(VariableTypeAbiTags.begin(),
1033 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
1034 UsedAbiTags.end(), AdditionalAbiTags.begin()),
1035 AdditionalAbiTags.end());
1036
1037 // Output name with implicit tags.
1038 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
1039 } else {
1040 mangleNameWithAbiTags(GD, nullptr);
1041 }
1042}
1043
1044const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
1045 const DeclContext *DC = Context.getEffectiveDeclContext(D);
1046 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
1047 if (isLocalContainerContext(DC))
1048 return dyn_cast<RecordDecl>(D);
1049 D = cast<Decl>(DC);
1050 DC = Context.getEffectiveDeclContext(D);
1051 }
1052 return nullptr;
1053}
1054
1055void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
1056 const AbiTagList *AdditionalAbiTags) {
1057 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1058 // <name> ::= [<module-name>] <nested-name>
1059 // ::= [<module-name>] <unscoped-name>
1060 // ::= [<module-name>] <unscoped-template-name> <template-args>
1061 // ::= <local-name>
1062 //
1063 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
1064 bool IsLambda = isLambda(ND);
1065
1066 // If this is an extern variable declared locally, the relevant DeclContext
1067 // is that of the containing namespace, or the translation unit.
1068 // FIXME: This is a hack; extern variables declared locally should have
1069 // a proper semantic declaration context!
1070 if (isLocalContainerContext(DC) && ND->hasLinkage() && !IsLambda)
1071 while (!DC->isNamespace() && !DC->isTranslationUnit())
1072 DC = Context.getEffectiveParentContext(DC);
1073 else if (GetLocalClassDecl(ND) &&
1074 (!IsLambda || isCompatibleWith(LangOptions::ClangABI::Ver18))) {
1075 mangleLocalName(GD, AdditionalAbiTags);
1076 return;
1077 }
1078
1079 assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");
1080
1081 // Closures can require a nested-name mangling even if they're semantically
1082 // in the global namespace.
1083 if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
1084 mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
1085 return;
1086 }
1087
1088 if (isLocalContainerContext(DC)) {
1089 mangleLocalName(GD, AdditionalAbiTags);
1090 return;
1091 }
1092
1093 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1094 // Check if we have a template.
1095 const TemplateArgumentList *TemplateArgs = nullptr;
1096 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1097 mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
1098 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1099 return;
1100 }
1101
1102 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1103 return;
1104 }
1105
1106 mangleNestedName(GD, DC, AdditionalAbiTags);
1107}
1108
1109void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
1110 if (ND->isExternallyVisible())
1111 if (Module *M = ND->getOwningModuleForLinkage())
1112 mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
1113}
1114
1115// <module-name> ::= <module-subname>
1116// ::= <module-name> <module-subname>
1117// ::= <substitution>
1118// <module-subname> ::= W <source-name>
1119// ::= W P <source-name>
1120void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
1121 // <substitution> ::= S <seq-id> _
1122 auto It = ModuleSubstitutions.find(Name);
1123 if (It != ModuleSubstitutions.end()) {
1124 Out << 'S';
1125 mangleSeqID(It->second);
1126 return;
1127 }
1128
1129 // FIXME: Preserve hierarchy in module names rather than flattening
1130 // them to strings; use Module*s as substitution keys.
1131 auto Parts = Name.rsplit('.');
1132 if (Parts.second.empty())
1133 Parts.second = Parts.first;
1134 else {
1135 mangleModuleNamePrefix(Parts.first, IsPartition);
1136 IsPartition = false;
1137 }
1138
1139 Out << 'W';
1140 if (IsPartition)
1141 Out << 'P';
1142 Out << Parts.second.size() << Parts.second;
1143 ModuleSubstitutions.insert({Name, SeqID++});
1144}
1145
1146void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
1148 const DeclContext *DC = Context.getEffectiveDeclContext(TD);
1149
1150 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1151 mangleUnscopedTemplateName(TD, DC, nullptr);
1152 mangleTemplateArgs(asTemplateName(TD), Args);
1153 } else {
1154 mangleNestedName(TD, Args);
1155 }
1156}
1157
1158void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
1159 const AbiTagList *AdditionalAbiTags) {
1160 // <unscoped-name> ::= <unqualified-name>
1161 // ::= St <unqualified-name> # ::std::
1162
1163 assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");
1164 if (isStdNamespace(DC))
1165 Out << "St";
1166
1167 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1168}
1169
1170void CXXNameMangler::mangleUnscopedTemplateName(
1171 GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
1172 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
1173 // <unscoped-template-name> ::= <unscoped-name>
1174 // ::= <substitution>
1175 if (mangleSubstitution(ND))
1176 return;
1177
1178 // <template-template-param> ::= <template-param>
1179 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1180 assert(!AdditionalAbiTags &&
1181 "template template param cannot have abi tags");
1182 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1183 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
1184 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1185 } else {
1186 mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
1187 AdditionalAbiTags);
1188 }
1189
1190 addSubstitution(ND);
1191}
1192
1193void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1194 // ABI:
1195 // Floating-point literals are encoded using a fixed-length
1196 // lowercase hexadecimal string corresponding to the internal
1197 // representation (IEEE on Itanium), high-order bytes first,
1198 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1199 // on Itanium.
1200 // The 'without leading zeroes' thing seems to be an editorial
1201 // mistake; see the discussion on cxx-abi-dev beginning on
1202 // 2012-01-16.
1203
1204 // Our requirements here are just barely weird enough to justify
1205 // using a custom algorithm instead of post-processing APInt::toString().
1206
1207 llvm::APInt valueBits = f.bitcastToAPInt();
1208 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1209 assert(numCharacters != 0);
1210
1211 // Allocate a buffer of the right number of characters.
1212 SmallVector<char, 20> buffer(numCharacters);
1213
1214 // Fill the buffer left-to-right.
1215 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1216 // The bit-index of the next hex digit.
1217 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1218
1219 // Project out 4 bits starting at 'digitIndex'.
1220 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1221 hexDigit >>= (digitBitIndex % 64);
1222 hexDigit &= 0xF;
1223
1224 // Map that over to a lowercase hex digit.
1225 static const char charForHex[16] = {
1226 '0', '1', '2', '3', '4', '5', '6', '7',
1227 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1228 };
1229 buffer[stringIndex] = charForHex[hexDigit];
1230 }
1231
1232 Out.write(buffer.data(), numCharacters);
1233}
1234
1235void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1236 Out << 'L';
1237 mangleType(T);
1238 mangleFloat(V);
1239 Out << 'E';
1240}
1241
1242void CXXNameMangler::mangleFixedPointLiteral() {
1243 DiagnosticsEngine &Diags = Context.getDiags();
1244 unsigned DiagID = Diags.getCustomDiagID(
1245 DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1246 Diags.Report(DiagID);
1247}
1248
1249void CXXNameMangler::mangleNullPointer(QualType T) {
1250 // <expr-primary> ::= L <type> 0 E
1251 Out << 'L';
1252 mangleType(T);
1253 Out << "0E";
1254}
1255
1256void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1257 if (Value.isSigned() && Value.isNegative()) {
1258 Out << 'n';
1259 Value.abs().print(Out, /*signed*/ false);
1260 } else {
1261 Value.print(Out, /*signed*/ false);
1262 }
1263}
1264
1265void CXXNameMangler::mangleNumber(int64_t Number) {
1266 // <number> ::= [n] <non-negative decimal integer>
1267 if (Number < 0) {
1268 Out << 'n';
1269 Number = -Number;
1270 }
1271
1272 Out << Number;
1273}
1274
1275void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1276 // <call-offset> ::= h <nv-offset> _
1277 // ::= v <v-offset> _
1278 // <nv-offset> ::= <offset number> # non-virtual base override
1279 // <v-offset> ::= <offset number> _ <virtual offset number>
1280 // # virtual base override, with vcall offset
1281 if (!Virtual) {
1282 Out << 'h';
1283 mangleNumber(NonVirtual);
1284 Out << '_';
1285 return;
1286 }
1287
1288 Out << 'v';
1289 mangleNumber(NonVirtual);
1290 Out << '_';
1291 mangleNumber(Virtual);
1292 Out << '_';
1293}
1294
1295void CXXNameMangler::manglePrefix(QualType type) {
1296 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1297 if (!mangleSubstitution(QualType(TST, 0))) {
1298 mangleTemplatePrefix(TST->getTemplateName());
1299
1300 // FIXME: GCC does not appear to mangle the template arguments when
1301 // the template in question is a dependent template name. Should we
1302 // emulate that badness?
1303 mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());
1304 addSubstitution(QualType(TST, 0));
1305 }
1306 } else if (const auto *DTST =
1308 if (!mangleSubstitution(QualType(DTST, 0))) {
1309 TemplateName Template = getASTContext().getDependentTemplateName(
1310 DTST->getQualifier(), DTST->getIdentifier());
1311 mangleTemplatePrefix(Template);
1312
1313 // FIXME: GCC does not appear to mangle the template arguments when
1314 // the template in question is a dependent template name. Should we
1315 // emulate that badness?
1316 mangleTemplateArgs(Template, DTST->template_arguments());
1317 addSubstitution(QualType(DTST, 0));
1318 }
1319 } else {
1320 // We use the QualType mangle type variant here because it handles
1321 // substitutions.
1322 mangleType(type);
1323 }
1324}
1325
1326/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1327///
1328/// \param recursive - true if this is being called recursively,
1329/// i.e. if there is more prefix "to the right".
1330void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1331 bool recursive) {
1332
1333 // x, ::x
1334 // <unresolved-name> ::= [gs] <base-unresolved-name>
1335
1336 // T::x / decltype(p)::x
1337 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1338
1339 // T::N::x /decltype(p)::N::x
1340 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1341 // <base-unresolved-name>
1342
1343 // A::x, N::y, A<T>::z; "gs" means leading "::"
1344 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1345 // <base-unresolved-name>
1346
1347 switch (qualifier->getKind()) {
1349 Out << "gs";
1350
1351 // We want an 'sr' unless this is the entire NNS.
1352 if (recursive)
1353 Out << "sr";
1354
1355 // We never want an 'E' here.
1356 return;
1357
1359 llvm_unreachable("Can't mangle __super specifier");
1360
1362 if (qualifier->getPrefix())
1363 mangleUnresolvedPrefix(qualifier->getPrefix(),
1364 /*recursive*/ true);
1365 else
1366 Out << "sr";
1367 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1368 break;
1370 if (qualifier->getPrefix())
1371 mangleUnresolvedPrefix(qualifier->getPrefix(),
1372 /*recursive*/ true);
1373 else
1374 Out << "sr";
1375 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1376 break;
1377
1380 const Type *type = qualifier->getAsType();
1381
1382 // We only want to use an unresolved-type encoding if this is one of:
1383 // - a decltype
1384 // - a template type parameter
1385 // - a template template parameter with arguments
1386 // In all of these cases, we should have no prefix.
1387 if (qualifier->getPrefix()) {
1388 mangleUnresolvedPrefix(qualifier->getPrefix(),
1389 /*recursive*/ true);
1390 } else {
1391 // Otherwise, all the cases want this.
1392 Out << "sr";
1393 }
1394
1395 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1396 return;
1397
1398 break;
1399 }
1400
1402 // Member expressions can have these without prefixes.
1403 if (qualifier->getPrefix())
1404 mangleUnresolvedPrefix(qualifier->getPrefix(),
1405 /*recursive*/ true);
1406 else
1407 Out << "sr";
1408
1409 mangleSourceName(qualifier->getAsIdentifier());
1410 // An Identifier has no type information, so we can't emit abi tags for it.
1411 break;
1412 }
1413
1414 // If this was the innermost part of the NNS, and we fell out to
1415 // here, append an 'E'.
1416 if (!recursive)
1417 Out << 'E';
1418}
1419
1420/// Mangle an unresolved-name, which is generally used for names which
1421/// weren't resolved to specific entities.
1422void CXXNameMangler::mangleUnresolvedName(
1423 NestedNameSpecifier *qualifier, DeclarationName name,
1424 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1425 unsigned knownArity) {
1426 if (qualifier) mangleUnresolvedPrefix(qualifier);
1427 switch (name.getNameKind()) {
1428 // <base-unresolved-name> ::= <simple-id>
1430 mangleSourceName(name.getAsIdentifierInfo());
1431 break;
1432 // <base-unresolved-name> ::= dn <destructor-name>
1434 Out << "dn";
1435 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1436 break;
1437 // <base-unresolved-name> ::= on <operator-name>
1441 Out << "on";
1442 mangleOperatorName(name, knownArity);
1443 break;
1445 llvm_unreachable("Can't mangle a constructor name!");
1447 llvm_unreachable("Can't mangle a using directive name!");
1449 llvm_unreachable("Can't mangle a deduction guide name!");
1453 llvm_unreachable("Can't mangle Objective-C selector names here!");
1454 }
1455
1456 // The <simple-id> and on <operator-name> productions end in an optional
1457 // <template-args>.
1458 if (TemplateArgs)
1459 mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
1460}
1461
1462void CXXNameMangler::mangleUnqualifiedName(
1463 GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
1464 unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
1465 const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
1466 // <unqualified-name> ::= [<module-name>] [F] <operator-name>
1467 // ::= <ctor-dtor-name>
1468 // ::= [<module-name>] [F] <source-name>
1469 // ::= [<module-name>] DC <source-name>* E
1470
1471 if (ND && DC && DC->isFileContext())
1472 mangleModuleName(ND);
1473
1474 // A member-like constrained friend is mangled with a leading 'F'.
1475 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
1476 auto *FD = dyn_cast<FunctionDecl>(ND);
1477 auto *FTD = dyn_cast<FunctionTemplateDecl>(ND);
1478 if ((FD && FD->isMemberLikeConstrainedFriend()) ||
1479 (FTD && FTD->getTemplatedDecl()->isMemberLikeConstrainedFriend())) {
1480 if (!isCompatibleWith(LangOptions::ClangABI::Ver17))
1481 Out << 'F';
1482 }
1483
1484 unsigned Arity = KnownArity;
1485 switch (Name.getNameKind()) {
1487 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1488
1489 // We mangle decomposition declarations as the names of their bindings.
1490 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1491 // FIXME: Non-standard mangling for decomposition declarations:
1492 //
1493 // <unqualified-name> ::= DC <source-name>* E
1494 //
1495 // Proposed on cxx-abi-dev on 2016-08-12
1496 Out << "DC";
1497 for (auto *BD : DD->bindings())
1498 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1499 Out << 'E';
1500 writeAbiTags(ND, AdditionalAbiTags);
1501 break;
1502 }
1503
1504 if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
1505 // We follow MSVC in mangling GUID declarations as if they were variables
1506 // with a particular reserved name. Continue the pretense here.
1507 SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1508 llvm::raw_svector_ostream GUIDOS(GUID);
1509 Context.mangleMSGuidDecl(GD, GUIDOS);
1510 Out << GUID.size() << GUID;
1511 break;
1512 }
1513
1514 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1515 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1516 Out << "TA";
1517 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1518 TPO->getValue(), /*TopLevel=*/true);
1519 break;
1520 }
1521
1522 if (II) {
1523 // Match GCC's naming convention for internal linkage symbols, for
1524 // symbols that are not actually visible outside of this TU. GCC
1525 // distinguishes between internal and external linkage symbols in
1526 // its mangling, to support cases like this that were valid C++ prior
1527 // to DR426:
1528 //
1529 // void test() { extern void foo(); }
1530 // static void foo();
1531 //
1532 // Don't bother with the L marker for names in anonymous namespaces; the
1533 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1534 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1535 // implying internal linkage.
1536 if (Context.isInternalLinkageDecl(ND))
1537 Out << 'L';
1538
1539 bool IsRegCall = FD &&
1540 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1542 bool IsDeviceStub =
1543 FD && FD->hasAttr<CUDAGlobalAttr>() &&
1544 GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1545 if (IsDeviceStub)
1546 mangleDeviceStubName(II);
1547 else if (IsRegCall)
1548 mangleRegCallName(II);
1549 else
1550 mangleSourceName(II);
1551
1552 writeAbiTags(ND, AdditionalAbiTags);
1553 break;
1554 }
1555
1556 // Otherwise, an anonymous entity. We must have a declaration.
1557 assert(ND && "mangling empty name without declaration");
1558
1559 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1560 if (NS->isAnonymousNamespace()) {
1561 // This is how gcc mangles these names.
1562 Out << "12_GLOBAL__N_1";
1563 break;
1564 }
1565 }
1566
1567 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1568 // We must have an anonymous union or struct declaration.
1569 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1570
1571 // Itanium C++ ABI 5.1.2:
1572 //
1573 // For the purposes of mangling, the name of an anonymous union is
1574 // considered to be the name of the first named data member found by a
1575 // pre-order, depth-first, declaration-order walk of the data members of
1576 // the anonymous union. If there is no such data member (i.e., if all of
1577 // the data members in the union are unnamed), then there is no way for
1578 // a program to refer to the anonymous union, and there is therefore no
1579 // need to mangle its name.
1580 assert(RD->isAnonymousStructOrUnion()
1581 && "Expected anonymous struct or union!");
1582 const FieldDecl *FD = RD->findFirstNamedDataMember();
1583
1584 // It's actually possible for various reasons for us to get here
1585 // with an empty anonymous struct / union. Fortunately, it
1586 // doesn't really matter what name we generate.
1587 if (!FD) break;
1588 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1589
1590 mangleSourceName(FD->getIdentifier());
1591 // Not emitting abi tags: internal name anyway.
1592 break;
1593 }
1594
1595 // Class extensions have no name as a category, and it's possible
1596 // for them to be the semantic parent of certain declarations
1597 // (primarily, tag decls defined within declarations). Such
1598 // declarations will always have internal linkage, so the name
1599 // doesn't really matter, but we shouldn't crash on them. For
1600 // safety, just handle all ObjC containers here.
1601 if (isa<ObjCContainerDecl>(ND))
1602 break;
1603
1604 // We must have an anonymous struct.
1605 const TagDecl *TD = cast<TagDecl>(ND);
1606 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1607 assert(TD->getDeclContext() == D->getDeclContext() &&
1608 "Typedef should not be in another decl context!");
1609 assert(D->getDeclName().getAsIdentifierInfo() &&
1610 "Typedef was not named!");
1611 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1612 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1613 // Explicit abi tags are still possible; take from underlying type, not
1614 // from typedef.
1615 writeAbiTags(TD, nullptr);
1616 break;
1617 }
1618
1619 // <unnamed-type-name> ::= <closure-type-name>
1620 //
1621 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1622 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1623 // # Parameter types or 'v' for 'void'.
1624 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1625 std::optional<unsigned> DeviceNumber =
1626 Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
1627
1628 // If we have a device-number via the discriminator, use that to mangle
1629 // the lambda, otherwise use the typical lambda-mangling-number. In either
1630 // case, a '0' should be mangled as a normal unnamed class instead of as a
1631 // lambda.
1632 if (Record->isLambda() &&
1633 ((DeviceNumber && *DeviceNumber > 0) ||
1634 (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
1635 assert(!AdditionalAbiTags &&
1636 "Lambda type cannot have additional abi tags");
1637 mangleLambda(Record);
1638 break;
1639 }
1640 }
1641
1642 if (TD->isExternallyVisible()) {
1643 unsigned UnnamedMangle =
1644 getASTContext().getManglingNumber(TD, Context.isAux());
1645 Out << "Ut";
1646 if (UnnamedMangle > 1)
1647 Out << UnnamedMangle - 2;
1648 Out << '_';
1649 writeAbiTags(TD, AdditionalAbiTags);
1650 break;
1651 }
1652
1653 // Get a unique id for the anonymous struct. If it is not a real output
1654 // ID doesn't matter so use fake one.
1655 unsigned AnonStructId =
1656 NullOut ? 0
1657 : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));
1658
1659 // Mangle it as a source name in the form
1660 // [n] $_<id>
1661 // where n is the length of the string.
1662 SmallString<8> Str;
1663 Str += "$_";
1664 Str += llvm::utostr(AnonStructId);
1665
1666 Out << Str.size();
1667 Out << Str;
1668 break;
1669 }
1670
1674 llvm_unreachable("Can't mangle Objective-C selector names here!");
1675
1677 const CXXRecordDecl *InheritedFrom = nullptr;
1678 TemplateName InheritedTemplateName;
1679 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1680 if (auto Inherited =
1681 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1682 InheritedFrom = Inherited.getConstructor()->getParent();
1683 InheritedTemplateName =
1684 TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
1685 InheritedTemplateArgs =
1686 Inherited.getConstructor()->getTemplateSpecializationArgs();
1687 }
1688
1689 if (ND == Structor)
1690 // If the named decl is the C++ constructor we're mangling, use the type
1691 // we were given.
1692 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1693 else
1694 // Otherwise, use the complete constructor name. This is relevant if a
1695 // class with a constructor is declared within a constructor.
1696 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1697
1698 // FIXME: The template arguments are part of the enclosing prefix or
1699 // nested-name, but it's more convenient to mangle them here.
1700 if (InheritedTemplateArgs)
1701 mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
1702
1703 writeAbiTags(ND, AdditionalAbiTags);
1704 break;
1705 }
1706
1708 if (ND == Structor)
1709 // If the named decl is the C++ destructor we're mangling, use the type we
1710 // were given.
1711 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1712 else
1713 // Otherwise, use the complete destructor name. This is relevant if a
1714 // class with a destructor is declared within a destructor.
1715 mangleCXXDtorType(Dtor_Complete);
1716 assert(ND);
1717 writeAbiTags(ND, AdditionalAbiTags);
1718 break;
1719
1721 if (ND && Arity == UnknownArity) {
1722 Arity = cast<FunctionDecl>(ND)->getNumParams();
1723
1724 // If we have a member function, we need to include the 'this' pointer.
1725 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1726 if (MD->isImplicitObjectMemberFunction())
1727 Arity++;
1728 }
1729 [[fallthrough]];
1732 mangleOperatorName(Name, Arity);
1733 writeAbiTags(ND, AdditionalAbiTags);
1734 break;
1735
1737 llvm_unreachable("Can't mangle a deduction guide name!");
1738
1740 llvm_unreachable("Can't mangle a using directive name!");
1741 }
1742}
1743
1744void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1745 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1746 // <number> ::= [n] <non-negative decimal integer>
1747 // <identifier> ::= <unqualified source code identifier>
1748 if (getASTContext().getLangOpts().RegCall4)
1749 Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"
1750 << II->getName();
1751 else
1752 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1753 << II->getName();
1754}
1755
1756void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1757 // <source-name> ::= <positive length number> __device_stub__ <identifier>
1758 // <number> ::= [n] <non-negative decimal integer>
1759 // <identifier> ::= <unqualified source code identifier>
1760 Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1761 << II->getName();
1762}
1763
1764void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1765 // <source-name> ::= <positive length number> <identifier>
1766 // <number> ::= [n] <non-negative decimal integer>
1767 // <identifier> ::= <unqualified source code identifier>
1768 Out << II->getLength() << II->getName();
1769}
1770
1771void CXXNameMangler::mangleNestedName(GlobalDecl GD,
1772 const DeclContext *DC,
1773 const AbiTagList *AdditionalAbiTags,
1774 bool NoFunction) {
1775 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1776 // <nested-name>
1777 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1778 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1779 // <template-args> E
1780
1781 Out << 'N';
1782 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1783 Qualifiers MethodQuals = Method->getMethodQualifiers();
1784 // We do not consider restrict a distinguishing attribute for overloading
1785 // purposes so we must not mangle it.
1786 if (Method->isExplicitObjectMemberFunction())
1787 Out << 'H';
1788 MethodQuals.removeRestrict();
1789 mangleQualifiers(MethodQuals);
1790 mangleRefQualifier(Method->getRefQualifier());
1791 }
1792
1793 // Check if we have a template.
1794 const TemplateArgumentList *TemplateArgs = nullptr;
1795 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1796 mangleTemplatePrefix(TD, NoFunction);
1797 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1798 } else {
1799 manglePrefix(DC, NoFunction);
1800 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1801 }
1802
1803 Out << 'E';
1804}
1805void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1807 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1808
1809 Out << 'N';
1810
1811 mangleTemplatePrefix(TD);
1812 mangleTemplateArgs(asTemplateName(TD), Args);
1813
1814 Out << 'E';
1815}
1816
1817void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1818 GlobalDecl GD, const NamedDecl *PrefixND,
1819 const AbiTagList *AdditionalAbiTags) {
1820 // A <closure-prefix> represents a variable or field, not a regular
1821 // DeclContext, so needs special handling. In this case we're mangling a
1822 // limited form of <nested-name>:
1823 //
1824 // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1825
1826 Out << 'N';
1827
1828 mangleClosurePrefix(PrefixND);
1829 mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1830
1831 Out << 'E';
1832}
1833
1835 GlobalDecl GD;
1836 // The Itanium spec says:
1837 // For entities in constructors and destructors, the mangling of the
1838 // complete object constructor or destructor is used as the base function
1839 // name, i.e. the C1 or D1 version.
1840 if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
1841 GD = GlobalDecl(CD, Ctor_Complete);
1842 else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
1843 GD = GlobalDecl(DD, Dtor_Complete);
1844 else
1845 GD = GlobalDecl(cast<FunctionDecl>(DC));
1846 return GD;
1847}
1848
1849void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1850 const AbiTagList *AdditionalAbiTags) {
1851 const Decl *D = GD.getDecl();
1852 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1853 // := Z <function encoding> E s [<discriminator>]
1854 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1855 // _ <entity name>
1856 // <discriminator> := _ <non-negative number>
1857 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1858 const RecordDecl *RD = GetLocalClassDecl(D);
1859 const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
1860
1861 Out << 'Z';
1862
1863 {
1864 AbiTagState LocalAbiTags(AbiTags);
1865
1866 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1867 mangleObjCMethodName(MD);
1868 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1869 mangleBlockForPrefix(BD);
1870 else
1871 mangleFunctionEncoding(getParentOfLocalEntity(DC));
1872
1873 // Implicit ABI tags (from namespace) are not available in the following
1874 // entity; reset to actually emitted tags, which are available.
1875 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1876 }
1877
1878 Out << 'E';
1879
1880 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1881 // be a bug that is fixed in trunk.
1882
1883 if (RD) {
1884 // The parameter number is omitted for the last parameter, 0 for the
1885 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1886 // <entity name> will of course contain a <closure-type-name>: Its
1887 // numbering will be local to the particular argument in which it appears
1888 // -- other default arguments do not affect its encoding.
1889 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1890 if (CXXRD && CXXRD->isLambda()) {
1891 if (const ParmVarDecl *Parm
1892 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1893 if (const FunctionDecl *Func
1894 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1895 Out << 'd';
1896 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1897 if (Num > 1)
1898 mangleNumber(Num - 2);
1899 Out << '_';
1900 }
1901 }
1902 }
1903
1904 // Mangle the name relative to the closest enclosing function.
1905 // equality ok because RD derived from ND above
1906 if (D == RD) {
1907 mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
1908 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1909 if (const NamedDecl *PrefixND = getClosurePrefix(BD))
1910 mangleClosurePrefix(PrefixND, true /*NoFunction*/);
1911 else
1912 manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
1913 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1914 mangleUnqualifiedBlock(BD);
1915 } else {
1916 const NamedDecl *ND = cast<NamedDecl>(D);
1917 mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
1918 AdditionalAbiTags, true /*NoFunction*/);
1919 }
1920 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1921 // Mangle a block in a default parameter; see above explanation for
1922 // lambdas.
1923 if (const ParmVarDecl *Parm
1924 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1925 if (const FunctionDecl *Func
1926 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1927 Out << 'd';
1928 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1929 if (Num > 1)
1930 mangleNumber(Num - 2);
1931 Out << '_';
1932 }
1933 }
1934
1935 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1936 mangleUnqualifiedBlock(BD);
1937 } else {
1938 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1939 }
1940
1941 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1942 unsigned disc;
1943 if (Context.getNextDiscriminator(ND, disc)) {
1944 if (disc < 10)
1945 Out << '_' << disc;
1946 else
1947 Out << "__" << disc << '_';
1948 }
1949 }
1950}
1951
1952void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1953 if (GetLocalClassDecl(Block)) {
1954 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1955 return;
1956 }
1957 const DeclContext *DC = Context.getEffectiveDeclContext(Block);
1958 if (isLocalContainerContext(DC)) {
1959 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1960 return;
1961 }
1962 if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1963 mangleClosurePrefix(PrefixND);
1964 else
1965 manglePrefix(DC);
1966 mangleUnqualifiedBlock(Block);
1967}
1968
1969void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1970 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1971 // <data-member-prefix> now, with no substitutions and no <template-args>.
1972 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1973 if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
1974 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1975 Context->getDeclContext()->isRecord()) {
1976 const auto *ND = cast<NamedDecl>(Context);
1977 if (ND->getIdentifier()) {
1978 mangleSourceNameWithAbiTags(ND);
1979 Out << 'M';
1980 }
1981 }
1982 }
1983
1984 // If we have a block mangling number, use it.
1985 unsigned Number = Block->getBlockManglingNumber();
1986 // Otherwise, just make up a number. It doesn't matter what it is because
1987 // the symbol in question isn't externally visible.
1988 if (!Number)
1989 Number = Context.getBlockId(Block, false);
1990 else {
1991 // Stored mangling numbers are 1-based.
1992 --Number;
1993 }
1994 Out << "Ub";
1995 if (Number > 0)
1996 Out << Number - 1;
1997 Out << '_';
1998}
1999
2000// <template-param-decl>
2001// ::= Ty # template type parameter
2002// ::= Tk <concept name> [<template-args>] # constrained type parameter
2003// ::= Tn <type> # template non-type parameter
2004// ::= Tt <template-param-decl>* E [Q <requires-clause expr>]
2005// # template template parameter
2006// ::= Tp <template-param-decl> # template parameter pack
2007void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
2008 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
2009 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
2010 if (Ty->isParameterPack())
2011 Out << "Tp";
2012 const TypeConstraint *Constraint = Ty->getTypeConstraint();
2013 if (Constraint && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2014 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2015 Out << "Tk";
2016 mangleTypeConstraint(Constraint);
2017 } else {
2018 Out << "Ty";
2019 }
2020 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
2021 if (Tn->isExpandedParameterPack()) {
2022 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
2023 Out << "Tn";
2024 mangleType(Tn->getExpansionType(I));
2025 }
2026 } else {
2027 QualType T = Tn->getType();
2028 if (Tn->isParameterPack()) {
2029 Out << "Tp";
2030 if (auto *PackExpansion = T->getAs<PackExpansionType>())
2031 T = PackExpansion->getPattern();
2032 }
2033 Out << "Tn";
2034 mangleType(T);
2035 }
2036 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
2037 if (Tt->isExpandedParameterPack()) {
2038 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
2039 ++I)
2040 mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I));
2041 } else {
2042 if (Tt->isParameterPack())
2043 Out << "Tp";
2044 mangleTemplateParameterList(Tt->getTemplateParameters());
2045 }
2046 }
2047}
2048
2049void CXXNameMangler::mangleTemplateParameterList(
2050 const TemplateParameterList *Params) {
2051 Out << "Tt";
2052 for (auto *Param : *Params)
2053 mangleTemplateParamDecl(Param);
2054 mangleRequiresClause(Params->getRequiresClause());
2055 Out << "E";
2056}
2057
2058void CXXNameMangler::mangleTypeConstraint(
2059 const ConceptDecl *Concept, ArrayRef<TemplateArgument> Arguments) {
2060 const DeclContext *DC = Context.getEffectiveDeclContext(Concept);
2061 if (!Arguments.empty())
2062 mangleTemplateName(Concept, Arguments);
2063 else if (DC->isTranslationUnit() || isStdNamespace(DC))
2064 mangleUnscopedName(Concept, DC, nullptr);
2065 else
2066 mangleNestedName(Concept, DC, nullptr);
2067}
2068
2069void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) {
2071 if (Constraint->getTemplateArgsAsWritten()) {
2072 for (const TemplateArgumentLoc &ArgLoc :
2073 Constraint->getTemplateArgsAsWritten()->arguments())
2074 Args.push_back(ArgLoc.getArgument());
2075 }
2076 return mangleTypeConstraint(Constraint->getNamedConcept(), Args);
2077}
2078
2079void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) {
2080 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2081 if (RequiresClause && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2082 Out << 'Q';
2083 mangleExpression(RequiresClause);
2084 }
2085}
2086
2087void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
2088 // When trying to be ABI-compatibility with clang 12 and before, mangle a
2089 // <data-member-prefix> now, with no substitutions.
2090 if (Decl *Context = Lambda->getLambdaContextDecl()) {
2091 if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
2092 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
2093 !isa<ParmVarDecl>(Context)) {
2094 if (const IdentifierInfo *Name
2095 = cast<NamedDecl>(Context)->getIdentifier()) {
2096 mangleSourceName(Name);
2097 const TemplateArgumentList *TemplateArgs = nullptr;
2098 if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
2099 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2100 Out << 'M';
2101 }
2102 }
2103 }
2104
2105 Out << "Ul";
2106 mangleLambdaSig(Lambda);
2107 Out << "E";
2108
2109 // The number is omitted for the first closure type with a given
2110 // <lambda-sig> in a given context; it is n-2 for the nth closure type
2111 // (in lexical order) with that same <lambda-sig> and context.
2112 //
2113 // The AST keeps track of the number for us.
2114 //
2115 // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2116 // and host-side compilations, an extra device mangle context may be created
2117 // if the host-side CXX ABI has different numbering for lambda. In such case,
2118 // if the mangle context is that device-side one, use the device-side lambda
2119 // mangling number for this lambda.
2120 std::optional<unsigned> DeviceNumber =
2121 Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
2122 unsigned Number =
2123 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2124
2125 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
2126 if (Number > 1)
2127 mangleNumber(Number - 2);
2128 Out << '_';
2129}
2130
2131void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
2132 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.
2133 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2134 mangleTemplateParamDecl(D);
2135
2136 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2137 if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList())
2138 mangleRequiresClause(TPL->getRequiresClause());
2139
2140 auto *Proto =
2142 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
2143 Lambda->getLambdaStaticInvoker());
2144}
2145
2146void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
2147 switch (qualifier->getKind()) {
2149 // nothing
2150 return;
2151
2153 llvm_unreachable("Can't mangle __super specifier");
2154
2156 mangleName(qualifier->getAsNamespace());
2157 return;
2158
2160 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
2161 return;
2162
2165 manglePrefix(QualType(qualifier->getAsType(), 0));
2166 return;
2167
2169 // Clang 14 and before did not consider this substitutable.
2170 bool Clang14Compat = isCompatibleWith(LangOptions::ClangABI::Ver14);
2171 if (!Clang14Compat && mangleSubstitution(qualifier))
2172 return;
2173
2174 // Member expressions can have these without prefixes, but that
2175 // should end up in mangleUnresolvedPrefix instead.
2176 assert(qualifier->getPrefix());
2177 manglePrefix(qualifier->getPrefix());
2178
2179 mangleSourceName(qualifier->getAsIdentifier());
2180
2181 if (!Clang14Compat)
2182 addSubstitution(qualifier);
2183 return;
2184 }
2185
2186 llvm_unreachable("unexpected nested name specifier");
2187}
2188
2189void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
2190 // <prefix> ::= <prefix> <unqualified-name>
2191 // ::= <template-prefix> <template-args>
2192 // ::= <closure-prefix>
2193 // ::= <template-param>
2194 // ::= # empty
2195 // ::= <substitution>
2196
2197 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
2198
2199 if (DC->isTranslationUnit())
2200 return;
2201
2202 if (NoFunction && isLocalContainerContext(DC))
2203 return;
2204
2205 const NamedDecl *ND = cast<NamedDecl>(DC);
2206 if (mangleSubstitution(ND))
2207 return;
2208
2209 // Check if we have a template-prefix or a closure-prefix.
2210 const TemplateArgumentList *TemplateArgs = nullptr;
2211 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2212 mangleTemplatePrefix(TD);
2213 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2214 } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2215 mangleClosurePrefix(PrefixND, NoFunction);
2216 mangleUnqualifiedName(ND, nullptr, nullptr);
2217 } else {
2218 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2219 manglePrefix(DC, NoFunction);
2220 mangleUnqualifiedName(ND, DC, nullptr);
2221 }
2222
2223 addSubstitution(ND);
2224}
2225
2226void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
2227 // <template-prefix> ::= <prefix> <template unqualified-name>
2228 // ::= <template-param>
2229 // ::= <substitution>
2230 if (TemplateDecl *TD = Template.getAsTemplateDecl())
2231 return mangleTemplatePrefix(TD);
2232
2234 assert(Dependent && "unexpected template name kind");
2235
2236 // Clang 11 and before mangled the substitution for a dependent template name
2237 // after already having emitted (a substitution for) the prefix.
2238 bool Clang11Compat = isCompatibleWith(LangOptions::ClangABI::Ver11);
2239 if (!Clang11Compat && mangleSubstitution(Template))
2240 return;
2241
2242 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
2243 manglePrefix(Qualifier);
2244
2245 if (Clang11Compat && mangleSubstitution(Template))
2246 return;
2247
2248 if (const IdentifierInfo *Id = Dependent->getIdentifier())
2249 mangleSourceName(Id);
2250 else
2251 mangleOperatorName(Dependent->getOperator(), UnknownArity);
2252
2253 addSubstitution(Template);
2254}
2255
2256void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2257 bool NoFunction) {
2258 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
2259 // <template-prefix> ::= <prefix> <template unqualified-name>
2260 // ::= <template-param>
2261 // ::= <substitution>
2262 // <template-template-param> ::= <template-param>
2263 // <substitution>
2264
2265 if (mangleSubstitution(ND))
2266 return;
2267
2268 // <template-template-param> ::= <template-param>
2269 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2270 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2271 } else {
2272 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2273 manglePrefix(DC, NoFunction);
2274 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
2275 mangleUnqualifiedName(GD, DC, nullptr);
2276 else
2277 mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
2278 nullptr);
2279 }
2280
2281 addSubstitution(ND);
2282}
2283
2284const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2285 if (isCompatibleWith(LangOptions::ClangABI::Ver12))
2286 return nullptr;
2287
2288 const NamedDecl *Context = nullptr;
2289 if (auto *Block = dyn_cast<BlockDecl>(ND)) {
2290 Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
2291 } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
2292 if (RD->isLambda())
2293 Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2294 }
2295 if (!Context)
2296 return nullptr;
2297
2298 // Only lambdas within the initializer of a non-local variable or non-static
2299 // data member get a <closure-prefix>.
2300 if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
2301 isa<FieldDecl>(Context))
2302 return Context;
2303
2304 return nullptr;
2305}
2306
2307void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2308 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2309 // ::= <template-prefix> <template-args> M
2310 if (mangleSubstitution(ND))
2311 return;
2312
2313 const TemplateArgumentList *TemplateArgs = nullptr;
2314 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2315 mangleTemplatePrefix(TD, NoFunction);
2316 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2317 } else {
2318 const auto *DC = Context.getEffectiveDeclContext(ND);
2319 manglePrefix(DC, NoFunction);
2320 mangleUnqualifiedName(ND, DC, nullptr);
2321 }
2322
2323 Out << 'M';
2324
2325 addSubstitution(ND);
2326}
2327
2328/// Mangles a template name under the production <type>. Required for
2329/// template template arguments.
2330/// <type> ::= <class-enum-type>
2331/// ::= <template-param>
2332/// ::= <substitution>
2333void CXXNameMangler::mangleType(TemplateName TN) {
2334 if (mangleSubstitution(TN))
2335 return;
2336
2337 TemplateDecl *TD = nullptr;
2338
2339 switch (TN.getKind()) {
2343 TD = TN.getAsTemplateDecl();
2344 goto HaveDecl;
2345
2346 HaveDecl:
2347 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2348 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2349 else
2350 mangleName(TD);
2351 break;
2352
2355 llvm_unreachable("can't mangle an overloaded template name as a <type>");
2356
2359 assert(Dependent->isIdentifier());
2360
2361 // <class-enum-type> ::= <name>
2362 // <name> ::= <nested-name>
2363 mangleUnresolvedPrefix(Dependent->getQualifier());
2364 mangleSourceName(Dependent->getIdentifier());
2365 break;
2366 }
2367
2369 // Substituted template parameters are mangled as the substituted
2370 // template. This will check for the substitution twice, which is
2371 // fine, but we have to return early so that we don't try to *add*
2372 // the substitution twice.
2375 mangleType(subst->getReplacement());
2376 return;
2377 }
2378
2380 // FIXME: not clear how to mangle this!
2381 // template <template <class> class T...> class A {
2382 // template <template <class> class U...> void foo(B<T,U> x...);
2383 // };
2384 Out << "_SUBSTPACK_";
2385 break;
2386 }
2387 }
2388
2389 addSubstitution(TN);
2390}
2391
2392bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2393 StringRef Prefix) {
2394 // Only certain other types are valid as prefixes; enumerate them.
2395 switch (Ty->getTypeClass()) {
2396 case Type::Builtin:
2397 case Type::Complex:
2398 case Type::Adjusted:
2399 case Type::Decayed:
2400 case Type::ArrayParameter:
2401 case Type::Pointer:
2402 case Type::BlockPointer:
2403 case Type::LValueReference:
2404 case Type::RValueReference:
2405 case Type::MemberPointer:
2406 case Type::ConstantArray:
2407 case Type::IncompleteArray:
2408 case Type::VariableArray:
2409 case Type::DependentSizedArray:
2410 case Type::DependentAddressSpace:
2411 case Type::DependentVector:
2412 case Type::DependentSizedExtVector:
2413 case Type::Vector:
2414 case Type::ExtVector:
2415 case Type::ConstantMatrix:
2416 case Type::DependentSizedMatrix:
2417 case Type::FunctionProto:
2418 case Type::FunctionNoProto:
2419 case Type::Paren:
2420 case Type::Attributed:
2421 case Type::BTFTagAttributed:
2422 case Type::Auto:
2423 case Type::DeducedTemplateSpecialization:
2424 case Type::PackExpansion:
2425 case Type::ObjCObject:
2426 case Type::ObjCInterface:
2427 case Type::ObjCObjectPointer:
2428 case Type::ObjCTypeParam:
2429 case Type::Atomic:
2430 case Type::Pipe:
2431 case Type::MacroQualified:
2432 case Type::BitInt:
2433 case Type::DependentBitInt:
2434 case Type::CountAttributed:
2435 llvm_unreachable("type is illegal as a nested name specifier");
2436
2437 case Type::SubstTemplateTypeParmPack:
2438 // FIXME: not clear how to mangle this!
2439 // template <class T...> class A {
2440 // template <class U...> void foo(decltype(T::foo(U())) x...);
2441 // };
2442 Out << "_SUBSTPACK_";
2443 break;
2444
2445 // <unresolved-type> ::= <template-param>
2446 // ::= <decltype>
2447 // ::= <template-template-param> <template-args>
2448 // (this last is not official yet)
2449 case Type::TypeOfExpr:
2450 case Type::TypeOf:
2451 case Type::Decltype:
2452 case Type::PackIndexing:
2453 case Type::TemplateTypeParm:
2454 case Type::UnaryTransform:
2455 case Type::SubstTemplateTypeParm:
2456 unresolvedType:
2457 // Some callers want a prefix before the mangled type.
2458 Out << Prefix;
2459
2460 // This seems to do everything we want. It's not really
2461 // sanctioned for a substituted template parameter, though.
2462 mangleType(Ty);
2463
2464 // We never want to print 'E' directly after an unresolved-type,
2465 // so we return directly.
2466 return true;
2467
2468 case Type::Typedef:
2469 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2470 break;
2471
2472 case Type::UnresolvedUsing:
2473 mangleSourceNameWithAbiTags(
2474 cast<UnresolvedUsingType>(Ty)->getDecl());
2475 break;
2476
2477 case Type::Enum:
2478 case Type::Record:
2479 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2480 break;
2481
2482 case Type::TemplateSpecialization: {
2483 const TemplateSpecializationType *TST =
2484 cast<TemplateSpecializationType>(Ty);
2485 TemplateName TN = TST->getTemplateName();
2486 switch (TN.getKind()) {
2490
2491 // If the base is a template template parameter, this is an
2492 // unresolved type.
2493 assert(TD && "no template for template specialization type");
2494 if (isa<TemplateTemplateParmDecl>(TD))
2495 goto unresolvedType;
2496
2497 mangleSourceNameWithAbiTags(TD);
2498 break;
2499 }
2500
2504 llvm_unreachable("invalid base for a template specialization type");
2505
2509 mangleExistingSubstitution(subst->getReplacement());
2510 break;
2511 }
2512
2514 // FIXME: not clear how to mangle this!
2515 // template <template <class U> class T...> class A {
2516 // template <class U...> void foo(decltype(T<U>::foo) x...);
2517 // };
2518 Out << "_SUBSTPACK_";
2519 break;
2520 }
2523 assert(TD && !isa<TemplateTemplateParmDecl>(TD));
2524 mangleSourceNameWithAbiTags(TD);
2525 break;
2526 }
2527 }
2528
2529 // Note: we don't pass in the template name here. We are mangling the
2530 // original source-level template arguments, so we shouldn't consider
2531 // conversions to the corresponding template parameter.
2532 // FIXME: Other compilers mangle partially-resolved template arguments in
2533 // unresolved-qualifier-levels.
2534 mangleTemplateArgs(TemplateName(), TST->template_arguments());
2535 break;
2536 }
2537
2538 case Type::InjectedClassName:
2539 mangleSourceNameWithAbiTags(
2540 cast<InjectedClassNameType>(Ty)->getDecl());
2541 break;
2542
2543 case Type::DependentName:
2544 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2545 break;
2546
2547 case Type::DependentTemplateSpecialization: {
2549 cast<DependentTemplateSpecializationType>(Ty);
2550 TemplateName Template = getASTContext().getDependentTemplateName(
2551 DTST->getQualifier(), DTST->getIdentifier());
2552 mangleSourceName(DTST->getIdentifier());
2553 mangleTemplateArgs(Template, DTST->template_arguments());
2554 break;
2555 }
2556
2557 case Type::Using:
2558 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2559 Prefix);
2560 case Type::Elaborated:
2561 return mangleUnresolvedTypeOrSimpleId(
2562 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2563 }
2564
2565 return false;
2566}
2567
2568void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2569 switch (Name.getNameKind()) {
2578 llvm_unreachable("Not an operator name");
2579
2581 // <operator-name> ::= cv <type> # (cast)
2582 Out << "cv";
2583 mangleType(Name.getCXXNameType());
2584 break;
2585
2587 Out << "li";
2588 mangleSourceName(Name.getCXXLiteralIdentifier());
2589 return;
2590
2592 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2593 break;
2594 }
2595}
2596
2597void
2598CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2599 switch (OO) {
2600 // <operator-name> ::= nw # new
2601 case OO_New: Out << "nw"; break;
2602 // ::= na # new[]
2603 case OO_Array_New: Out << "na"; break;
2604 // ::= dl # delete
2605 case OO_Delete: Out << "dl"; break;
2606 // ::= da # delete[]
2607 case OO_Array_Delete: Out << "da"; break;
2608 // ::= ps # + (unary)
2609 // ::= pl # + (binary or unknown)
2610 case OO_Plus:
2611 Out << (Arity == 1? "ps" : "pl"); break;
2612 // ::= ng # - (unary)
2613 // ::= mi # - (binary or unknown)
2614 case OO_Minus:
2615 Out << (Arity == 1? "ng" : "mi"); break;
2616 // ::= ad # & (unary)
2617 // ::= an # & (binary or unknown)
2618 case OO_Amp:
2619 Out << (Arity == 1? "ad" : "an"); break;
2620 // ::= de # * (unary)
2621 // ::= ml # * (binary or unknown)
2622 case OO_Star:
2623 // Use binary when unknown.
2624 Out << (Arity == 1? "de" : "ml"); break;
2625 // ::= co # ~
2626 case OO_Tilde: Out << "co"; break;
2627 // ::= dv # /
2628 case OO_Slash: Out << "dv"; break;
2629 // ::= rm # %
2630 case OO_Percent: Out << "rm"; break;
2631 // ::= or # |
2632 case OO_Pipe: Out << "or"; break;
2633 // ::= eo # ^
2634 case OO_Caret: Out << "eo"; break;
2635 // ::= aS # =
2636 case OO_Equal: Out << "aS"; break;
2637 // ::= pL # +=
2638 case OO_PlusEqual: Out << "pL"; break;
2639 // ::= mI # -=
2640 case OO_MinusEqual: Out << "mI"; break;
2641 // ::= mL # *=
2642 case OO_StarEqual: Out << "mL"; break;
2643 // ::= dV # /=
2644 case OO_SlashEqual: Out << "dV"; break;
2645 // ::= rM # %=
2646 case OO_PercentEqual: Out << "rM"; break;
2647 // ::= aN # &=
2648 case OO_AmpEqual: Out << "aN"; break;
2649 // ::= oR # |=
2650 case OO_PipeEqual: Out << "oR"; break;
2651 // ::= eO # ^=
2652 case OO_CaretEqual: Out << "eO"; break;
2653 // ::= ls # <<
2654 case OO_LessLess: Out << "ls"; break;
2655 // ::= rs # >>
2656 case OO_GreaterGreater: Out << "rs"; break;
2657 // ::= lS # <<=
2658 case OO_LessLessEqual: Out << "lS"; break;
2659 // ::= rS # >>=
2660 case OO_GreaterGreaterEqual: Out << "rS"; break;
2661 // ::= eq # ==
2662 case OO_EqualEqual: Out << "eq"; break;
2663 // ::= ne # !=
2664 case OO_ExclaimEqual: Out << "ne"; break;
2665 // ::= lt # <
2666 case OO_Less: Out << "lt"; break;
2667 // ::= gt # >
2668 case OO_Greater: Out << "gt"; break;
2669 // ::= le # <=
2670 case OO_LessEqual: Out << "le"; break;
2671 // ::= ge # >=
2672 case OO_GreaterEqual: Out << "ge"; break;
2673 // ::= nt # !
2674 case OO_Exclaim: Out << "nt"; break;
2675 // ::= aa # &&
2676 case OO_AmpAmp: Out << "aa"; break;
2677 // ::= oo # ||
2678 case OO_PipePipe: Out << "oo"; break;
2679 // ::= pp # ++
2680 case OO_PlusPlus: Out << "pp"; break;
2681 // ::= mm # --
2682 case OO_MinusMinus: Out << "mm"; break;
2683 // ::= cm # ,
2684 case OO_Comma: Out << "cm"; break;
2685 // ::= pm # ->*
2686 case OO_ArrowStar: Out << "pm"; break;
2687 // ::= pt # ->
2688 case OO_Arrow: Out << "pt"; break;
2689 // ::= cl # ()
2690 case OO_Call: Out << "cl"; break;
2691 // ::= ix # []
2692 case OO_Subscript: Out << "ix"; break;
2693
2694 // ::= qu # ?
2695 // The conditional operator can't be overloaded, but we still handle it when
2696 // mangling expressions.
2697 case OO_Conditional: Out << "qu"; break;
2698 // Proposal on cxx-abi-dev, 2015-10-21.
2699 // ::= aw # co_await
2700 case OO_Coawait: Out << "aw"; break;
2701 // Proposed in cxx-abi github issue 43.
2702 // ::= ss # <=>
2703 case OO_Spaceship: Out << "ss"; break;
2704
2705 case OO_None:
2707 llvm_unreachable("Not an overloaded operator");
2708 }
2709}
2710
2711void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2712 // Vendor qualifiers come first and if they are order-insensitive they must
2713 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2714
2715 // <type> ::= U <addrspace-expr>
2716 if (DAST) {
2717 Out << "U2ASI";
2718 mangleExpression(DAST->getAddrSpaceExpr());
2719 Out << "E";
2720 }
2721
2722 // Address space qualifiers start with an ordinary letter.
2723 if (Quals.hasAddressSpace()) {
2724 // Address space extension:
2725 //
2726 // <type> ::= U <target-addrspace>
2727 // <type> ::= U <OpenCL-addrspace>
2728 // <type> ::= U <CUDA-addrspace>
2729
2730 SmallString<64> ASString;
2731 LangAS AS = Quals.getAddressSpace();
2732
2733 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2734 // <target-addrspace> ::= "AS" <address-space-number>
2735 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2736 if (TargetAS != 0 ||
2737 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
2738 ASString = "AS" + llvm::utostr(TargetAS);
2739 } else {
2740 switch (AS) {
2741 default: llvm_unreachable("Not a language specific address space");
2742 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2743 // "private"| "generic" | "device" |
2744 // "host" ]
2745 case LangAS::opencl_global:
2746 ASString = "CLglobal";
2747 break;
2748 case LangAS::opencl_global_device:
2749 ASString = "CLdevice";
2750 break;
2751 case LangAS::opencl_global_host:
2752 ASString = "CLhost";
2753 break;
2754 case LangAS::opencl_local:
2755 ASString = "CLlocal";
2756 break;
2757 case LangAS::opencl_constant:
2758 ASString = "CLconstant";
2759 break;
2760 case LangAS::opencl_private:
2761 ASString = "CLprivate";
2762 break;
2763 case LangAS::opencl_generic:
2764 ASString = "CLgeneric";
2765 break;
2766 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2767 // "device" | "host" ]
2768 case LangAS::sycl_global:
2769 ASString = "SYglobal";
2770 break;
2771 case LangAS::sycl_global_device:
2772 ASString = "SYdevice";
2773 break;
2774 case LangAS::sycl_global_host:
2775 ASString = "SYhost";
2776 break;
2777 case LangAS::sycl_local:
2778 ASString = "SYlocal";
2779 break;
2780 case LangAS::sycl_private:
2781 ASString = "SYprivate";
2782 break;
2783 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2784 case LangAS::cuda_device:
2785 ASString = "CUdevice";
2786 break;
2787 case LangAS::cuda_constant:
2788 ASString = "CUconstant";
2789 break;
2790 case LangAS::cuda_shared:
2791 ASString = "CUshared";
2792 break;
2793 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2794 case LangAS::ptr32_sptr:
2795 ASString = "ptr32_sptr";
2796 break;
2797 case LangAS::ptr32_uptr:
2798 // For z/OS, there are no special mangling rules applied to the ptr32
2799 // qualifier. Ex: void foo(int * __ptr32 p) -> _Z3f2Pi. The mangling for
2800 // "p" is treated the same as a regular integer pointer.
2801 if (!getASTContext().getTargetInfo().getTriple().isOSzOS())
2802 ASString = "ptr32_uptr";
2803 break;
2804 case LangAS::ptr64:
2805 ASString = "ptr64";
2806 break;
2807 }
2808 }
2809 if (!ASString.empty())
2810 mangleVendorQualifier(ASString);
2811 }
2812
2813 // The ARC ownership qualifiers start with underscores.
2814 // Objective-C ARC Extension:
2815 //
2816 // <type> ::= U "__strong"
2817 // <type> ::= U "__weak"
2818 // <type> ::= U "__autoreleasing"
2819 //
2820 // Note: we emit __weak first to preserve the order as
2821 // required by the Itanium ABI.
2823 mangleVendorQualifier("__weak");
2824
2825 // __unaligned (from -fms-extensions)
2826 if (Quals.hasUnaligned())
2827 mangleVendorQualifier("__unaligned");
2828
2829 // Remaining ARC ownership qualifiers.
2830 switch (Quals.getObjCLifetime()) {
2832 break;
2833
2835 // Do nothing as we already handled this case above.
2836 break;
2837
2839 mangleVendorQualifier("__strong");
2840 break;
2841
2843 mangleVendorQualifier("__autoreleasing");
2844 break;
2845
2847 // The __unsafe_unretained qualifier is *not* mangled, so that
2848 // __unsafe_unretained types in ARC produce the same manglings as the
2849 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2850 // better ABI compatibility.
2851 //
2852 // It's safe to do this because unqualified 'id' won't show up
2853 // in any type signatures that need to be mangled.
2854 break;
2855 }
2856
2857 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2858 if (Quals.hasRestrict())
2859 Out << 'r';
2860 if (Quals.hasVolatile())
2861 Out << 'V';
2862 if (Quals.hasConst())
2863 Out << 'K';
2864}
2865
2866void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2867 Out << 'U' << name.size() << name;
2868}
2869
2870void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2871 // <ref-qualifier> ::= R # lvalue reference
2872 // ::= O # rvalue-reference
2873 switch (RefQualifier) {
2874 case RQ_None:
2875 break;
2876
2877 case RQ_LValue:
2878 Out << 'R';
2879 break;
2880
2881 case RQ_RValue:
2882 Out << 'O';
2883 break;
2884 }
2885}
2886
2887void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2888 Context.mangleObjCMethodNameAsSourceName(MD, Out);
2889}
2890
2891static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2892 ASTContext &Ctx) {
2893 if (Quals)
2894 return true;
2895 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2896 return true;
2897 if (Ty->isOpenCLSpecificType())
2898 return true;
2899 // From Clang 18.0 we correctly treat SVE types as substitution candidates.
2900 if (Ty->isSVESizelessBuiltinType() &&
2901 Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)
2902 return true;
2903 if (Ty->isBuiltinType())
2904 return false;
2905 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2906 // substitution candidates.
2907 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2908 isa<AutoType>(Ty))
2909 return false;
2910 // A placeholder type for class template deduction is substitutable with
2911 // its corresponding template name; this is handled specially when mangling
2912 // the type.
2913 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2914 if (DeducedTST->getDeducedType().isNull())
2915 return false;
2916 return true;
2917}
2918
2919void CXXNameMangler::mangleType(QualType T) {
2920 // If our type is instantiation-dependent but not dependent, we mangle
2921 // it as it was written in the source, removing any top-level sugar.
2922 // Otherwise, use the canonical type.
2923 //
2924 // FIXME: This is an approximation of the instantiation-dependent name
2925 // mangling rules, since we should really be using the type as written and
2926 // augmented via semantic analysis (i.e., with implicit conversions and
2927 // default template arguments) for any instantiation-dependent type.
2928 // Unfortunately, that requires several changes to our AST:
2929 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2930 // uniqued, so that we can handle substitutions properly
2931 // - Default template arguments will need to be represented in the
2932 // TemplateSpecializationType, since they need to be mangled even though
2933 // they aren't written.
2934 // - Conversions on non-type template arguments need to be expressed, since
2935 // they can affect the mangling of sizeof/alignof.
2936 //
2937 // FIXME: This is wrong when mapping to the canonical type for a dependent
2938 // type discards instantiation-dependent portions of the type, such as for:
2939 //
2940 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2941 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2942 //
2943 // It's also wrong in the opposite direction when instantiation-dependent,
2944 // canonically-equivalent types differ in some irrelevant portion of inner
2945 // type sugar. In such cases, we fail to form correct substitutions, eg:
2946 //
2947 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2948 //
2949 // We should instead canonicalize the non-instantiation-dependent parts,
2950 // regardless of whether the type as a whole is dependent or instantiation
2951 // dependent.
2953 T = T.getCanonicalType();
2954 else {
2955 // Desugar any types that are purely sugar.
2956 do {
2957 // Don't desugar through template specialization types that aren't
2958 // type aliases. We need to mangle the template arguments as written.
2959 if (const TemplateSpecializationType *TST
2960 = dyn_cast<TemplateSpecializationType>(T))
2961 if (!TST->isTypeAlias())
2962 break;
2963
2964 // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2965 // instantation-dependent qualifiers. See
2966 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2967
2968 QualType Desugared
2969 = T.getSingleStepDesugaredType(Context.getASTContext());
2970 if (Desugared == T)
2971 break;
2972
2973 T = Desugared;
2974 } while (true);
2975 }
2976 SplitQualType split = T.split();
2977 Qualifiers quals = split.Quals;
2978 const Type *ty = split.Ty;
2979
2980 bool isSubstitutable =
2981 isTypeSubstitutable(quals, ty, Context.getASTContext());
2982 if (isSubstitutable && mangleSubstitution(T))
2983 return;
2984
2985 // If we're mangling a qualified array type, push the qualifiers to
2986 // the element type.
2987 if (quals && isa<ArrayType>(T)) {
2988 ty = Context.getASTContext().getAsArrayType(T);
2989 quals = Qualifiers();
2990
2991 // Note that we don't update T: we want to add the
2992 // substitution at the original type.
2993 }
2994
2995 if (quals || ty->isDependentAddressSpaceType()) {
2996 if (const DependentAddressSpaceType *DAST =
2997 dyn_cast<DependentAddressSpaceType>(ty)) {
2998 SplitQualType splitDAST = DAST->getPointeeType().split();
2999 mangleQualifiers(splitDAST.Quals, DAST);
3000 mangleType(QualType(splitDAST.Ty, 0));
3001 } else {
3002 mangleQualifiers(quals);
3003
3004 // Recurse: even if the qualified type isn't yet substitutable,
3005 // the unqualified type might be.
3006 mangleType(QualType(ty, 0));
3007 }
3008 } else {
3009 switch (ty->getTypeClass()) {
3010#define ABSTRACT_TYPE(CLASS, PARENT)
3011#define NON_CANONICAL_TYPE(CLASS, PARENT) \
3012 case Type::CLASS: \
3013 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
3014 return;
3015#define TYPE(CLASS, PARENT) \
3016 case Type::CLASS: \
3017 mangleType(static_cast<const CLASS##Type*>(ty)); \
3018 break;
3019#include "clang/AST/TypeNodes.inc"
3020 }
3021 }
3022
3023 // Add the substitution.
3024 if (isSubstitutable)
3025 addSubstitution(T);
3026}
3027
3028void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
3029 if (!mangleStandardSubstitution(ND))
3030 mangleName(ND);
3031}
3032
3033void CXXNameMangler::mangleType(const BuiltinType *T) {
3034 // <type> ::= <builtin-type>
3035 // <builtin-type> ::= v # void
3036 // ::= w # wchar_t
3037 // ::= b # bool
3038 // ::= c # char
3039 // ::= a # signed char
3040 // ::= h # unsigned char
3041 // ::= s # short
3042 // ::= t # unsigned short
3043 // ::= i # int
3044 // ::= j # unsigned int
3045 // ::= l # long
3046 // ::= m # unsigned long
3047 // ::= x # long long, __int64
3048 // ::= y # unsigned long long, __int64
3049 // ::= n # __int128
3050 // ::= o # unsigned __int128
3051 // ::= f # float
3052 // ::= d # double
3053 // ::= e # long double, __float80
3054 // ::= g # __float128
3055 // ::= g # __ibm128
3056 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
3057 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
3058 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
3059 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3060 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
3061 // ::= Di # char32_t
3062 // ::= Ds # char16_t
3063 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3064 // ::= [DS] DA # N1169 fixed-point [_Sat] T _Accum
3065 // ::= [DS] DR # N1169 fixed-point [_Sat] T _Fract
3066 // ::= u <source-name> # vendor extended type
3067 //
3068 // <fixed-point-size>
3069 // ::= s # short
3070 // ::= t # unsigned short
3071 // ::= i # plain
3072 // ::= j # unsigned
3073 // ::= l # long
3074 // ::= m # unsigned long
3075 std::string type_name;
3076 // Normalize integer types as vendor extended types:
3077 // u<length>i<type size>
3078 // u<length>u<type size>
3079 if (NormalizeIntegers && T->isInteger()) {
3080 if (T->isSignedInteger()) {
3081 switch (getASTContext().getTypeSize(T)) {
3082 case 8:
3083 // Pick a representative for each integer size in the substitution
3084 // dictionary. (Its actual defined size is not relevant.)
3085 if (mangleSubstitution(BuiltinType::SChar))
3086 break;
3087 Out << "u2i8";
3088 addSubstitution(BuiltinType::SChar);
3089 break;
3090 case 16:
3091 if (mangleSubstitution(BuiltinType::Short))
3092 break;
3093 Out << "u3i16";
3094 addSubstitution(BuiltinType::Short);
3095 break;
3096 case 32:
3097 if (mangleSubstitution(BuiltinType::Int))
3098 break;
3099 Out << "u3i32";
3100 addSubstitution(BuiltinType::Int);
3101 break;
3102 case 64:
3103 if (mangleSubstitution(BuiltinType::Long))
3104 break;
3105 Out << "u3i64";
3106 addSubstitution(BuiltinType::Long);
3107 break;
3108 case 128:
3109 if (mangleSubstitution(BuiltinType::Int128))
3110 break;
3111 Out << "u4i128";
3112 addSubstitution(BuiltinType::Int128);
3113 break;
3114 default:
3115 llvm_unreachable("Unknown integer size for normalization");
3116 }
3117 } else {
3118 switch (getASTContext().getTypeSize(T)) {
3119 case 8:
3120 if (mangleSubstitution(BuiltinType::UChar))
3121 break;
3122 Out << "u2u8";
3123 addSubstitution(BuiltinType::UChar);
3124 break;
3125 case 16:
3126 if (mangleSubstitution(BuiltinType::UShort))
3127 break;
3128 Out << "u3u16";
3129 addSubstitution(BuiltinType::UShort);
3130 break;
3131 case 32:
3132 if (mangleSubstitution(BuiltinType::UInt))
3133 break;
3134 Out << "u3u32";
3135 addSubstitution(BuiltinType::UInt);
3136 break;
3137 case 64:
3138 if (mangleSubstitution(BuiltinType::ULong))
3139 break;
3140 Out << "u3u64";
3141 addSubstitution(BuiltinType::ULong);
3142 break;
3143 case 128:
3144 if (mangleSubstitution(BuiltinType::UInt128))
3145 break;
3146 Out << "u4u128";
3147 addSubstitution(BuiltinType::UInt128);
3148 break;
3149 default:
3150 llvm_unreachable("Unknown integer size for normalization");
3151 }
3152 }
3153 return;
3154 }
3155 switch (T->getKind()) {
3156 case BuiltinType::Void:
3157 Out << 'v';
3158 break;
3159 case BuiltinType::Bool:
3160 Out << 'b';
3161 break;
3162 case BuiltinType::Char_U:
3163 case BuiltinType::Char_S:
3164 Out << 'c';
3165 break;
3166 case BuiltinType::UChar:
3167 Out << 'h';
3168 break;
3169 case BuiltinType::UShort:
3170 Out << 't';
3171 break;
3172 case BuiltinType::UInt:
3173 Out << 'j';
3174 break;
3175 case BuiltinType::ULong:
3176 Out << 'm';
3177 break;
3178 case BuiltinType::ULongLong:
3179 Out << 'y';
3180 break;
3181 case BuiltinType::UInt128:
3182 Out << 'o';
3183 break;
3184 case BuiltinType::SChar:
3185 Out << 'a';
3186 break;
3187 case BuiltinType::WChar_S:
3188 case BuiltinType::WChar_U:
3189 Out << 'w';
3190 break;
3191 case BuiltinType::Char8:
3192 Out << "Du";
3193 break;
3194 case BuiltinType::Char16:
3195 Out << "Ds";
3196 break;
3197 case BuiltinType::Char32:
3198 Out << "Di";
3199 break;
3200 case BuiltinType::Short:
3201 Out << 's';
3202 break;
3203 case BuiltinType::Int:
3204 Out << 'i';
3205 break;
3206 case BuiltinType::Long:
3207 Out << 'l';
3208 break;
3209 case BuiltinType::LongLong:
3210 Out << 'x';
3211 break;
3212 case BuiltinType::Int128:
3213 Out << 'n';
3214 break;
3215 case BuiltinType::Float16:
3216 Out << "DF16_";
3217 break;
3218 case BuiltinType::ShortAccum:
3219 Out << "DAs";
3220 break;
3221 case BuiltinType::Accum:
3222 Out << "DAi";
3223 break;
3224 case BuiltinType::LongAccum:
3225 Out << "DAl";
3226 break;
3227 case BuiltinType::UShortAccum:
3228 Out << "DAt";
3229 break;
3230 case BuiltinType::UAccum:
3231 Out << "DAj";
3232 break;
3233 case BuiltinType::ULongAccum:
3234 Out << "DAm";
3235 break;
3236 case BuiltinType::ShortFract:
3237 Out << "DRs";
3238 break;
3239 case BuiltinType::Fract:
3240 Out << "DRi";
3241 break;
3242 case BuiltinType::LongFract:
3243 Out << "DRl";
3244 break;
3245 case BuiltinType::UShortFract:
3246 Out << "DRt";
3247 break;
3248 case BuiltinType::UFract:
3249 Out << "DRj";
3250 break;
3251 case BuiltinType::ULongFract:
3252 Out << "DRm";
3253 break;
3254 case BuiltinType::SatShortAccum:
3255 Out << "DSDAs";
3256 break;
3257 case BuiltinType::SatAccum:
3258 Out << "DSDAi";
3259 break;
3260 case BuiltinType::SatLongAccum:
3261 Out << "DSDAl";
3262 break;
3263 case BuiltinType::SatUShortAccum:
3264 Out << "DSDAt";
3265 break;
3266 case BuiltinType::SatUAccum:
3267 Out << "DSDAj";
3268 break;
3269 case BuiltinType::SatULongAccum:
3270 Out << "DSDAm";
3271 break;
3272 case BuiltinType::SatShortFract:
3273 Out << "DSDRs";
3274 break;
3275 case BuiltinType::SatFract:
3276 Out << "DSDRi";
3277 break;
3278 case BuiltinType::SatLongFract:
3279 Out << "DSDRl";
3280 break;
3281 case BuiltinType::SatUShortFract:
3282 Out << "DSDRt";
3283 break;
3284 case BuiltinType::SatUFract:
3285 Out << "DSDRj";
3286 break;
3287 case BuiltinType::SatULongFract:
3288 Out << "DSDRm";
3289 break;
3290 case BuiltinType::Half:
3291 Out << "Dh";
3292 break;
3293 case BuiltinType::Float:
3294 Out << 'f';
3295 break;
3296 case BuiltinType::Double:
3297 Out << 'd';
3298 break;
3299 case BuiltinType::LongDouble: {
3300 const TargetInfo *TI =
3301 getASTContext().getLangOpts().OpenMP &&
3302 getASTContext().getLangOpts().OpenMPIsTargetDevice
3303 ? getASTContext().getAuxTargetInfo()
3304 : &getASTContext().getTargetInfo();
3305 Out << TI->getLongDoubleMangling();
3306 break;
3307 }
3308 case BuiltinType::Float128: {
3309 const TargetInfo *TI =
3310 getASTContext().getLangOpts().OpenMP &&
3311 getASTContext().getLangOpts().OpenMPIsTargetDevice
3312 ? getASTContext().getAuxTargetInfo()
3313 : &getASTContext().getTargetInfo();
3314 Out << TI->getFloat128Mangling();
3315 break;
3316 }
3317 case BuiltinType::BFloat16: {
3318 const TargetInfo *TI =
3319 ((getASTContext().getLangOpts().OpenMP &&
3320 getASTContext().getLangOpts().OpenMPIsTargetDevice) ||
3321 getASTContext().getLangOpts().SYCLIsDevice)
3322 ? getASTContext().getAuxTargetInfo()
3323 : &getASTContext().getTargetInfo();
3324 Out << TI->getBFloat16Mangling();
3325 break;
3326 }
3327 case BuiltinType::Ibm128: {
3328 const TargetInfo *TI = &getASTContext().getTargetInfo();
3329 Out << TI->getIbm128Mangling();
3330 break;
3331 }
3332 case BuiltinType::NullPtr:
3333 Out << "Dn";
3334 break;
3335
3336#define BUILTIN_TYPE(Id, SingletonId)
3337#define PLACEHOLDER_TYPE(Id, SingletonId) \
3338 case BuiltinType::Id:
3339#include "clang/AST/BuiltinTypes.def"
3340 case BuiltinType::Dependent:
3341 if (!NullOut)
3342 llvm_unreachable("mangling a placeholder type");
3343 break;
3344 case BuiltinType::ObjCId:
3345 Out << "11objc_object";
3346 break;
3347 case BuiltinType::ObjCClass:
3348 Out << "10objc_class";
3349 break;
3350 case BuiltinType::ObjCSel:
3351 Out << "13objc_selector";
3352 break;
3353#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3354 case BuiltinType::Id: \
3355 type_name = "ocl_" #ImgType "_" #Suffix; \
3356 Out << type_name.size() << type_name; \
3357 break;
3358#include "clang/Basic/OpenCLImageTypes.def"
3359 case BuiltinType::OCLSampler:
3360 Out << "11ocl_sampler";
3361 break;
3362 case BuiltinType::OCLEvent:
3363 Out << "9ocl_event";
3364 break;
3365 case BuiltinType::OCLClkEvent:
3366 Out << "12ocl_clkevent";
3367 break;
3368 case BuiltinType::OCLQueue:
3369 Out << "9ocl_queue";
3370 break;
3371 case BuiltinType::OCLReserveID:
3372 Out << "13ocl_reserveid";
3373 break;
3374#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3375 case BuiltinType::Id: \
3376 type_name = "ocl_" #ExtType; \
3377 Out << type_name.size() << type_name; \
3378 break;
3379#include "clang/Basic/OpenCLExtensionTypes.def"
3380 // The SVE types are effectively target-specific. The mangling scheme
3381 // is defined in the appendices to the Procedure Call Standard for the
3382 // Arm Architecture.
3383#define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \
3384 ElBits, IsSigned, IsFP, IsBF) \
3385 case BuiltinType::Id: \
3386 if (T->getKind() == BuiltinType::SveBFloat16 && \
3387 isCompatibleWith(LangOptions::ClangABI::Ver17)) { \
3388 /* Prior to Clang 18.0 we used this incorrect mangled name */ \
3389 type_name = "__SVBFloat16_t"; \
3390 Out << "u" << type_name.size() << type_name; \
3391 } else { \
3392 type_name = MangledName; \
3393 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3394 << type_name; \
3395 } \
3396 break;
3397#define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
3398 case BuiltinType::Id: \
3399 type_name = MangledName; \
3400 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3401 << type_name; \
3402 break;
3403#define SVE_OPAQUE_TYPE(InternalName, MangledName, Id, SingletonId) \
3404 case BuiltinType::Id: \
3405 type_name = MangledName; \
3406 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3407 << type_name; \
3408 break;
3409#include "clang/Basic/AArch64SVEACLETypes.def"
3410#define PPC_VECTOR_TYPE(Name, Id, Size) \
3411 case BuiltinType::Id: \
3412 type_name = #Name; \
3413 Out << 'u' << type_name.size() << type_name; \
3414 break;
3415#include "clang/Basic/PPCTypes.def"
3416 // TODO: Check the mangling scheme for RISC-V V.
3417#define RVV_TYPE(Name, Id, SingletonId) \
3418 case BuiltinType::Id: \
3419 type_name = Name; \
3420 Out << 'u' << type_name.size() << type_name; \
3421 break;
3422#include "clang/Basic/RISCVVTypes.def"
3423#define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \
3424 case BuiltinType::Id: \
3425 type_name = MangledName; \
3426 Out << 'u' << type_name.size() << type_name; \
3427 break;
3428#include "clang/Basic/WebAssemblyReferenceTypes.def"
3429#define AMDGPU_TYPE(Name, Id, SingletonId) \
3430 case BuiltinType::Id: \
3431 type_name = Name; \
3432 Out << 'u' << type_name.size() << type_name; \
3433 break;
3434#include "clang/Basic/AMDGPUTypes.def"
3435#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3436 case BuiltinType::Id: \
3437 type_name = #Name; \
3438 Out << 'u' << type_name.size() << type_name; \
3439 break;
3440#include "clang/Basic/HLSLIntangibleTypes.def"
3441 }
3442}
3443
3444StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3445 switch (CC) {
3446 case CC_C:
3447 return "";
3448
3449 case CC_X86VectorCall:
3450 case CC_X86Pascal:
3451 case CC_X86RegCall:
3452 case CC_AAPCS:
3453 case CC_AAPCS_VFP:
3455 case CC_AArch64SVEPCS:
3457 case CC_IntelOclBicc:
3458 case CC_SpirFunction:
3459 case CC_OpenCLKernel:
3460 case CC_PreserveMost:
3461 case CC_PreserveAll:
3462 case CC_M68kRTD:
3463 case CC_PreserveNone:
3464 case CC_RISCVVectorCall:
3465 // FIXME: we should be mangling all of the above.
3466 return "";
3467
3468 case CC_X86ThisCall:
3469 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3470 // used explicitly. At this point, we don't have that much information in
3471 // the AST, since clang tends to bake the convention into the canonical
3472 // function type. thiscall only rarely used explicitly, so don't mangle it
3473 // for now.
3474 return "";
3475
3476 case CC_X86StdCall:
3477 return "stdcall";
3478 case CC_X86FastCall:
3479 return "fastcall";
3480 case CC_X86_64SysV:
3481 return "sysv_abi";
3482 case CC_Win64:
3483 return "ms_abi";
3484 case CC_Swift:
3485 return "swiftcall";
3486 case CC_SwiftAsync:
3487 return "swiftasynccall";
3488 }
3489 llvm_unreachable("bad calling convention");
3490}
3491
3492void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3493 // Fast path.
3495 return;
3496
3497 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3498 // This will get more complicated in the future if we mangle other
3499 // things here; but for now, since we mangle ns_returns_retained as
3500 // a qualifier on the result type, we can get away with this:
3501 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
3502 if (!CCQualifier.empty())
3503 mangleVendorQualifier(CCQualifier);
3504
3505 // FIXME: regparm
3506 // FIXME: noreturn
3507}
3508
3509void
3510CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3511 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3512
3513 // Note that these are *not* substitution candidates. Demanglers might
3514 // have trouble with this if the parameter type is fully substituted.
3515
3516 switch (PI.getABI()) {
3517 case ParameterABI::Ordinary:
3518 break;
3519
3520 // All of these start with "swift", so they come before "ns_consumed".
3521 case ParameterABI::SwiftContext:
3522 case ParameterABI::SwiftAsyncContext:
3523 case ParameterABI::SwiftErrorResult:
3524 case ParameterABI::SwiftIndirectResult:
3525 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3526 break;
3527 }
3528
3529 if (PI.isConsumed())
3530 mangleVendorQualifier("ns_consumed");
3531
3532 if (PI.isNoEscape())
3533 mangleVendorQualifier("noescape");
3534}
3535
3536// <type> ::= <function-type>
3537// <function-type> ::= [<CV-qualifiers>] F [Y]
3538// <bare-function-type> [<ref-qualifier>] E
3539void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3540 mangleExtFunctionInfo(T);
3541
3542 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3543 // e.g. "const" in "int (A::*)() const".
3544 mangleQualifiers(T->getMethodQuals());
3545
3546 // Mangle instantiation-dependent exception-specification, if present,
3547 // per cxx-abi-dev proposal on 2016-10-11.
3550 Out << "DO";
3551 mangleExpression(T->getNoexceptExpr());
3552 Out << "E";
3553 } else {
3554 assert(T->getExceptionSpecType() == EST_Dynamic);
3555 Out << "Dw";
3556 for (auto ExceptTy : T->exceptions())
3557 mangleType(ExceptTy);
3558 Out << "E";
3559 }
3560 } else if (T->isNothrow()) {
3561 Out << "Do";
3562 }
3563
3564 Out << 'F';
3565
3566 // FIXME: We don't have enough information in the AST to produce the 'Y'
3567 // encoding for extern "C" function types.
3568 mangleBareFunctionType(T, /*MangleReturnType=*/true);
3569
3570 // Mangle the ref-qualifier, if present.
3571 mangleRefQualifier(T->getRefQualifier());
3572
3573 Out << 'E';
3574}
3575
3576void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3577 // Function types without prototypes can arise when mangling a function type
3578 // within an overloadable function in C. We mangle these as the absence of any
3579 // parameter types (not even an empty parameter list).
3580 Out << 'F';
3581
3582 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3583
3584 FunctionTypeDepth.enterResultType();
3585 mangleType(T->getReturnType());
3586 FunctionTypeDepth.leaveResultType();
3587
3588 FunctionTypeDepth.pop(saved);
3589 Out << 'E';
3590}
3591
3592void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3593 bool MangleReturnType,
3594 const FunctionDecl *FD) {
3595 // Record that we're in a function type. See mangleFunctionParam
3596 // for details on what we're trying to achieve here.
3597 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3598
3599 // <bare-function-type> ::= <signature type>+
3600 if (MangleReturnType) {
3601 FunctionTypeDepth.enterResultType();
3602
3603 // Mangle ns_returns_retained as an order-sensitive qualifier here.
3604 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3605 mangleVendorQualifier("ns_returns_retained");
3606
3607 // Mangle the return type without any direct ARC ownership qualifiers.
3608 QualType ReturnTy = Proto->getReturnType();
3609 if (ReturnTy.getObjCLifetime()) {
3610 auto SplitReturnTy = ReturnTy.split();
3611 SplitReturnTy.Quals.removeObjCLifetime();
3612 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3613 }
3614 mangleType(ReturnTy);
3615
3616 FunctionTypeDepth.leaveResultType();
3617 }
3618
3619 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3620 // <builtin-type> ::= v # void
3621 Out << 'v';
3622 } else {
3623 assert(!FD || FD->getNumParams() == Proto->getNumParams());
3624 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3625 // Mangle extended parameter info as order-sensitive qualifiers here.
3626 if (Proto->hasExtParameterInfos() && FD == nullptr) {
3627 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3628 }
3629
3630 // Mangle the type.
3631 QualType ParamTy = Proto->getParamType(I);
3632 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3633
3634 if (FD) {
3635 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3636 // Attr can only take 1 character, so we can hardcode the length
3637 // below.
3638 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3639 if (Attr->isDynamic())
3640 Out << "U25pass_dynamic_object_size" << Attr->getType();
3641 else
3642 Out << "U17pass_object_size" << Attr->getType();
3643 }
3644 }
3645 }
3646
3647 // <builtin-type> ::= z # ellipsis
3648 if (Proto->isVariadic())
3649 Out << 'z';
3650 }
3651
3652 if (FD) {
3653 FunctionTypeDepth.enterResultType();
3654 mangleRequiresClause(FD->getTrailingRequiresClause());
3655 }
3656
3657 FunctionTypeDepth.pop(saved);
3658}
3659
3660// <type> ::= <class-enum-type>
3661// <class-enum-type> ::= <name>
3662void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3663 mangleName(T->getDecl());
3664}
3665
3666// <type> ::= <class-enum-type>
3667// <class-enum-type> ::= <name>
3668void CXXNameMangler::mangleType(const EnumType *T) {
3669 mangleType(static_cast<const TagType*>(T));
3670}
3671void CXXNameMangler::mangleType(const RecordType *T) {
3672 mangleType(static_cast<const TagType*>(T));
3673}
3674void CXXNameMangler::mangleType(const TagType *T) {
3675 mangleName(T->getDecl());
3676}
3677
3678// <type> ::= <array-type>
3679// <array-type> ::= A <positive dimension number> _ <element type>
3680// ::= A [<dimension expression>] _ <element type>
3681void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3682 Out << 'A' << T->getSize() << '_';
3683 mangleType(T->getElementType());
3684}
3685void CXXNameMangler::mangleType(const VariableArrayType *T) {
3686 Out << 'A';
3687 // decayed vla types (size 0) will just be skipped.
3688 if (T->getSizeExpr())
3689 mangleExpression(T->getSizeExpr());
3690 Out << '_';
3691 mangleType(T->getElementType());
3692}
3693void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3694 Out << 'A';
3695 // A DependentSizedArrayType might not have size expression as below
3696 //
3697 // template<int ...N> int arr[] = {N...};
3698 if (T->getSizeExpr())
3699 mangleExpression(T->getSizeExpr());
3700 Out << '_';
3701 mangleType(T->getElementType());
3702}
3703void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3704 Out << "A_";
3705 mangleType(T->getElementType());
3706}
3707
3708// <type> ::= <pointer-to-member-type>
3709// <pointer-to-member-type> ::= M <class type> <member type>
3710void CXXNameMangler::mangleType(const MemberPointerType *T) {
3711 Out << 'M';
3712 mangleType(QualType(T->getClass(), 0));
3713 QualType PointeeType = T->getPointeeType();
3714 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3715 mangleType(FPT);
3716
3717 // Itanium C++ ABI 5.1.8:
3718 //
3719 // The type of a non-static member function is considered to be different,
3720 // for the purposes of substitution, from the type of a namespace-scope or
3721 // static member function whose type appears similar. The types of two
3722 // non-static member functions are considered to be different, for the
3723 // purposes of substitution, if the functions are members of different
3724 // classes. In other words, for the purposes of substitution, the class of
3725 // which the function is a member is considered part of the type of
3726 // function.
3727
3728 // Given that we already substitute member function pointers as a
3729 // whole, the net effect of this rule is just to unconditionally
3730 // suppress substitution on the function type in a member pointer.
3731 // We increment the SeqID here to emulate adding an entry to the
3732 // substitution table.
3733 ++SeqID;
3734 } else
3735 mangleType(PointeeType);
3736}
3737
3738// <type> ::= <template-param>
3739void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3740 mangleTemplateParameter(T->getDepth(), T->getIndex());
3741}
3742
3743// <type> ::= <template-param>
3744void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3745 // FIXME: not clear how to mangle this!
3746 // template <class T...> class A {
3747 // template <class U...> void foo(T(*)(U) x...);
3748 // };
3749 Out << "_SUBSTPACK_";
3750}
3751
3752// <type> ::= P <type> # pointer-to
3753void CXXNameMangler::mangleType(const PointerType *T) {
3754 Out << 'P';
3755 mangleType(T->getPointeeType());
3756}
3757void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3758 Out << 'P';
3759 mangleType(T->getPointeeType());
3760}
3761
3762// <type> ::= R <type> # reference-to
3763void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3764 Out << 'R';
3765 mangleType(T->getPointeeType());
3766}
3767
3768// <type> ::= O <type> # rvalue reference-to (C++0x)
3769void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3770 Out << 'O';
3771 mangleType(T->getPointeeType());
3772}
3773
3774// <type> ::= C <type> # complex pair (C 2000)
3775void CXXNameMangler::mangleType(const ComplexType *T) {
3776 Out << 'C';
3777 mangleType(T->getElementType());
3778}
3779
3780// ARM's ABI for Neon vector types specifies that they should be mangled as
3781// if they are structs (to match ARM's initial implementation). The
3782// vector type must be one of the special types predefined by ARM.
3783void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3784 QualType EltType = T->getElementType();
3785 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3786 const char *EltName = nullptr;
3787 if (T->getVectorKind() == VectorKind::NeonPoly) {
3788 switch (cast<BuiltinType>(EltType)->getKind()) {
3789 case BuiltinType::SChar:
3790 case BuiltinType::UChar:
3791 EltName = "poly8_t";
3792 break;
3793 case BuiltinType::Short:
3794 case BuiltinType::UShort:
3795 EltName = "poly16_t";
3796 break;
3797 case BuiltinType::LongLong:
3798 case BuiltinType::ULongLong:
3799 EltName = "poly64_t";
3800 break;
3801 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3802 }
3803 } else {
3804 switch (cast<BuiltinType>(EltType)->getKind()) {
3805 case BuiltinType::SChar: EltName = "int8_t"; break;
3806 case BuiltinType::UChar: EltName = "uint8_t"; break;
3807 case BuiltinType::Short: EltName = "int16_t"; break;
3808 case BuiltinType::UShort: EltName = "uint16_t"; break;
3809 case BuiltinType::Int: EltName = "int32_t"; break;
3810 case BuiltinType::UInt: EltName = "uint32_t"; break;
3811 case BuiltinType::LongLong: EltName = "int64_t"; break;
3812 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3813 case BuiltinType::Double: EltName = "float64_t"; break;
3814 case BuiltinType::Float: EltName = "float32_t"; break;
3815 case BuiltinType::Half: EltName = "float16_t"; break;
3816 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
3817 default:
3818 llvm_unreachable("unexpected Neon vector element type");
3819 }
3820 }
3821 const char *BaseName = nullptr;
3822 unsigned BitSize = (T->getNumElements() *
3823 getASTContext().getTypeSize(EltType));
3824 if (BitSize == 64)
3825 BaseName = "__simd64_";
3826 else {
3827 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3828 BaseName = "__simd128_";
3829 }
3830 Out << strlen(BaseName) + strlen(EltName);
3831 Out << BaseName << EltName;
3832}
3833
3834void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3835 DiagnosticsEngine &Diags = Context.getDiags();
3836 unsigned DiagID = Diags.getCustomDiagID(
3838 "cannot mangle this dependent neon vector type yet");
3839 Diags.Report(T->getAttributeLoc(), DiagID);
3840}
3841
3842static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3843 switch (EltType->getKind()) {
3844 case BuiltinType::SChar:
3845 return "Int8";
3846 case BuiltinType::Short:
3847 return "Int16";
3848 case BuiltinType::Int:
3849 return "Int32";
3850 case BuiltinType::Long:
3851 case BuiltinType::LongLong:
3852 return "Int64";
3853 case BuiltinType::UChar:
3854 return "Uint8";
3855 case BuiltinType::UShort:
3856 return "Uint16";
3857 case BuiltinType::UInt:
3858 return "Uint32";
3859 case BuiltinType::ULong:
3860 case BuiltinType::ULongLong:
3861 return "Uint64";
3862 case BuiltinType::Half:
3863 return "Float16";
3864 case BuiltinType::Float:
3865 return "Float32";
3866 case BuiltinType::Double:
3867 return "Float64";
3868 case BuiltinType::BFloat16:
3869 return "Bfloat16";
3870 default:
3871 llvm_unreachable("Unexpected vector element base type");
3872 }
3873}
3874
3875// AArch64's ABI for Neon vector types specifies that they should be mangled as
3876// the equivalent internal name. The vector type must be one of the special
3877// types predefined by ARM.
3878void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3879 QualType EltType = T->getElementType();
3880 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3881 unsigned BitSize =
3882 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3883 (void)BitSize; // Silence warning.
3884
3885 assert((BitSize == 64 || BitSize == 128) &&
3886 "Neon vector type not 64 or 128 bits");
3887
3888 StringRef EltName;
3889 if (T->getVectorKind() == VectorKind::NeonPoly) {
3890 switch (cast<BuiltinType>(EltType)->getKind()) {
3891 case BuiltinType::UChar:
3892 EltName = "Poly8";
3893 break;
3894 case BuiltinType::UShort:
3895 EltName = "Poly16";
3896 break;
3897 case BuiltinType::ULong:
3898 case BuiltinType::ULongLong:
3899 EltName = "Poly64";
3900 break;
3901 default:
3902 llvm_unreachable("unexpected Neon polynomial vector element type");
3903 }
3904 } else
3905 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3906
3907 std::string TypeName =
3908 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3909 Out << TypeName.length() << TypeName;
3910}
3911void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3912 DiagnosticsEngine &Diags = Context.getDiags();
3913 unsigned DiagID = Diags.getCustomDiagID(
3915 "cannot mangle this dependent neon vector type yet");
3916 Diags.Report(T->getAttributeLoc(), DiagID);
3917}
3918
3919// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3920// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3921// type as the sizeless variants.
3922//
3923// The mangling scheme for VLS types is implemented as a "pseudo" template:
3924//
3925// '__SVE_VLS<<type>, <vector length>>'
3926//
3927// Combining the existing SVE type and a specific vector length (in bits).
3928// For example:
3929//
3930// typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3931//
3932// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3933//
3934// "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3935//
3936// i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3937//
3938// The latest ACLE specification (00bet5) does not contain details of this
3939// mangling scheme, it will be specified in the next revision. The mangling
3940// scheme is otherwise defined in the appendices to the Procedure Call Standard
3941// for the Arm Architecture, see
3942// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
3943void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
3944 assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||
3945 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
3946 "expected fixed-length SVE vector!");
3947
3948 QualType EltType = T->getElementType();
3949 assert(EltType->isBuiltinType() &&
3950 "expected builtin type for fixed-length SVE vector!");
3951
3952 StringRef TypeName;
3953 switch (cast<BuiltinType>(EltType)->getKind()) {
3954 case BuiltinType::SChar:
3955 TypeName = "__SVInt8_t";
3956 break;
3957 case BuiltinType::UChar: {
3958 if (T->getVectorKind() == VectorKind::SveFixedLengthData)
3959 TypeName = "__SVUint8_t";
3960 else
3961 TypeName = "__SVBool_t";
3962 break;
3963 }
3964 case BuiltinType::Short:
3965 TypeName = "__SVInt16_t";
3966 break;
3967 case BuiltinType::UShort:
3968 TypeName = "__SVUint16_t";
3969 break;
3970 case BuiltinType::Int:
3971 TypeName = "__SVInt32_t";
3972 break;
3973 case BuiltinType::UInt:
3974 TypeName = "__SVUint32_t";
3975 break;
3976 case BuiltinType::Long:
3977 TypeName = "__SVInt64_t";
3978 break;
3979 case BuiltinType::ULong:
3980 TypeName = "__SVUint64_t";
3981 break;
3982 case BuiltinType::Half:
3983 TypeName = "__SVFloat16_t";
3984 break;
3985 case BuiltinType::Float:
3986 TypeName = "__SVFloat32_t";
3987 break;
3988 case BuiltinType::Double:
3989 TypeName = "__SVFloat64_t";
3990 break;
3991 case BuiltinType::BFloat16:
3992 TypeName = "__SVBfloat16_t";
3993 break;
3994 default:
3995 llvm_unreachable("unexpected element type for fixed-length SVE vector!");
3996 }
3997
3998 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
3999
4000 if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)
4001 VecSizeInBits *= 8;
4002
4003 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
4004 << VecSizeInBits << "EE";
4005}
4006
4007void CXXNameMangler::mangleAArch64FixedSveVectorType(
4008 const DependentVectorType *T) {
4009 DiagnosticsEngine &Diags = Context.getDiags();
4010 unsigned DiagID = Diags.getCustomDiagID(
4012 "cannot mangle this dependent fixed-length SVE vector type yet");
4013 Diags.Report(T->getAttributeLoc(), DiagID);
4014}
4015
4016void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {
4017 assert((T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4018 T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4019 T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4020 T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4021 T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) &&
4022 "expected fixed-length RVV vector!");
4023
4024 QualType EltType = T->getElementType();
4025 assert(EltType->isBuiltinType() &&
4026 "expected builtin type for fixed-length RVV vector!");
4027
4028 SmallString<20> TypeNameStr;
4029 llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
4030 TypeNameOS << "__rvv_";
4031 switch (cast<BuiltinType>(EltType)->getKind()) {
4032 case BuiltinType::SChar:
4033 TypeNameOS << "int8";
4034 break;
4035 case BuiltinType::UChar:
4036 if (T->getVectorKind() == VectorKind::RVVFixedLengthData)
4037 TypeNameOS << "uint8";
4038 else
4039 TypeNameOS << "bool";
4040 break;
4041 case BuiltinType::Short:
4042 TypeNameOS << "int16";
4043 break;
4044 case BuiltinType::UShort:
4045 TypeNameOS << "uint16";
4046 break;
4047 case BuiltinType::Int:
4048 TypeNameOS << "int32";
4049 break;
4050 case BuiltinType::UInt:
4051 TypeNameOS << "uint32";
4052 break;
4053 case BuiltinType::Long:
4054 TypeNameOS << "int64";
4055 break;
4056 case BuiltinType::ULong:
4057 TypeNameOS << "uint64";
4058 break;
4059 case BuiltinType::Float16:
4060 TypeNameOS << "float16";
4061 break;
4062 case BuiltinType::Float:
4063 TypeNameOS << "float32";
4064 break;
4065 case BuiltinType::Double:
4066 TypeNameOS << "float64";
4067 break;
4068 default:
4069 llvm_unreachable("unexpected element type for fixed-length RVV vector!");
4070 }
4071
4072 unsigned VecSizeInBits;
4073 switch (T->getVectorKind()) {
4074 case VectorKind::RVVFixedLengthMask_1:
4075 VecSizeInBits = 1;
4076 break;
4077 case VectorKind::RVVFixedLengthMask_2:
4078 VecSizeInBits = 2;
4079 break;
4080 case VectorKind::RVVFixedLengthMask_4:
4081 VecSizeInBits = 4;
4082 break;
4083 default:
4084 VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4085 break;
4086 }
4087
4088 // Apend the LMUL suffix.
4089 auto VScale = getASTContext().getTargetInfo().getVScaleRange(
4090 getASTContext().getLangOpts());
4091 unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;
4092
4093 if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4094 TypeNameOS << 'm';
4095 if (VecSizeInBits >= VLen)
4096 TypeNameOS << (VecSizeInBits / VLen);
4097 else
4098 TypeNameOS << 'f' << (VLen / VecSizeInBits);
4099 } else {
4100 TypeNameOS << (VLen / VecSizeInBits);
4101 }
4102 TypeNameOS << "_t";
4103
4104 Out << "9__RVV_VLSI" << 'u' << TypeNameStr.size() << TypeNameStr << "Lj"
4105 << VecSizeInBits << "EE";
4106}
4107
4108void CXXNameMangler::mangleRISCVFixedRVVVectorType(
4109 const DependentVectorType *T) {
4110 DiagnosticsEngine &Diags = Context.getDiags();
4111 unsigned DiagID = Diags.getCustomDiagID(
4113 "cannot mangle this dependent fixed-length RVV vector type yet");
4114 Diags.Report(T->getAttributeLoc(), DiagID);
4115}
4116
4117// GNU extension: vector types
4118// <type> ::= <vector-type>
4119// <vector-type> ::= Dv <positive dimension number> _
4120// <extended element type>
4121// ::= Dv [<dimension expression>] _ <element type>
4122// <extended element type> ::= <element type>
4123// ::= p # AltiVec vector pixel
4124// ::= b # Altivec vector bool
4125void CXXNameMangler::mangleType(const VectorType *T) {
4126 if ((T->getVectorKind() == VectorKind::Neon ||
4127 T->getVectorKind() == VectorKind::NeonPoly)) {
4128 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4129 llvm::Triple::ArchType Arch =
4130 getASTContext().getTargetInfo().getTriple().getArch();
4131 if ((Arch == llvm::Triple::aarch64 ||
4132 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
4133 mangleAArch64NeonVectorType(T);
4134 else
4135 mangleNeonVectorType(T);
4136 return;
4137 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4138 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4139 mangleAArch64FixedSveVectorType(T);
4140 return;
4141 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4142 T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4143 T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4144 T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4145 T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
4146 mangleRISCVFixedRVVVectorType(T);
4147 return;
4148 }
4149 Out << "Dv" << T->getNumElements() << '_';
4150 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4151 Out << 'p';
4152 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4153 Out << 'b';
4154 else
4155 mangleType(T->getElementType());
4156}
4157
4158void CXXNameMangler::mangleType(const DependentVectorType *T) {
4159 if ((T->getVectorKind() == VectorKind::Neon ||
4160 T->getVectorKind() == VectorKind::NeonPoly)) {
4161 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4162 llvm::Triple::ArchType Arch =
4163 getASTContext().getTargetInfo().getTriple().getArch();
4164 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
4165 !Target.isOSDarwin())
4166 mangleAArch64NeonVectorType(T);
4167 else
4168 mangleNeonVectorType(T);
4169 return;
4170 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4171 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4172 mangleAArch64FixedSveVectorType(T);
4173 return;
4174 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4175 mangleRISCVFixedRVVVectorType(T);
4176 return;
4177 }
4178
4179 Out << "Dv";
4180 mangleExpression(T->getSizeExpr());
4181 Out << '_';
4182 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4183 Out << 'p';
4184 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4185 Out << 'b';
4186 else
4187 mangleType(T->getElementType());
4188}
4189
4190void CXXNameMangler::mangleType(const ExtVectorType *T) {
4191 mangleType(static_cast<const VectorType*>(T));
4192}
4193void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
4194 Out << "Dv";
4195 mangleExpression(T->getSizeExpr());
4196 Out << '_';
4197 mangleType(T->getElementType());
4198}
4199
4200void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
4201 // Mangle matrix types as a vendor extended type:
4202 // u<Len>matrix_typeI<Rows><Columns><element type>E
4203
4204 StringRef VendorQualifier = "matrix_type";
4205 Out << "u" << VendorQualifier.size() << VendorQualifier;
4206
4207 Out << "I";
4208 auto &ASTCtx = getASTContext();
4209 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
4210 llvm::APSInt Rows(BitWidth);
4211 Rows = T->getNumRows();
4212 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
4213 llvm::APSInt Columns(BitWidth);
4214 Columns = T->getNumColumns();
4215 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
4216 mangleType(T->getElementType());
4217 Out << "E";
4218}
4219
4220void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
4221 // Mangle matrix types as a vendor extended type:
4222 // u<Len>matrix_typeI<row expr><column expr><element type>E
4223 StringRef VendorQualifier = "matrix_type";
4224 Out << "u" << VendorQualifier.size() << VendorQualifier;
4225
4226 Out << "I";
4227 mangleTemplateArgExpr(T->getRowExpr());
4228 mangleTemplateArgExpr(T->getColumnExpr());
4229 mangleType(T->getElementType());
4230 Out << "E";
4231}
4232
4233void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
4234 SplitQualType split = T->getPointeeType().split();
4235 mangleQualifiers(split.Quals, T);
4236 mangleType(QualType(split.Ty, 0));
4237}
4238
4239void CXXNameMangler::mangleType(const PackExpansionType *T) {
4240 // <type> ::= Dp <type> # pack expansion (C++0x)
4241 Out << "Dp";
4242 mangleType(T->getPattern());
4243}
4244
4245void CXXNameMangler::mangleType(const PackIndexingType *T) {
4246 if (!T->hasSelectedType())
4247 mangleType(T->getPattern());
4248 else
4249 mangleType(T->getSelectedType());
4250}
4251
4252void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
4253 mangleSourceName(T->getDecl()->getIdentifier());
4254}
4255
4256void CXXNameMangler::mangleType(const ObjCObjectType *T) {
4257 // Treat __kindof as a vendor extended type qualifier.
4258 if (T->isKindOfType())
4259 Out << "U8__kindof";
4260
4261 if (!T->qual_empty()) {
4262 // Mangle protocol qualifiers.
4263 SmallString<64> QualStr;
4264 llvm::raw_svector_ostream QualOS(QualStr);
4265 QualOS << "objcproto";
4266 for (const auto *I : T->quals()) {
4267 StringRef name = I->getName();
4268 QualOS << name.size() << name;
4269 }
4270 Out << 'U' << QualStr.size() << QualStr;
4271 }
4272
4273 mangleType(T->getBaseType());
4274
4275 if (T->isSpecialized()) {
4276 // Mangle type arguments as I <type>+ E
4277 Out << 'I';
4278 for (auto typeArg : T->getTypeArgs())
4279 mangleType(typeArg);
4280 Out << 'E';
4281 }
4282}
4283
4284void CXXNameMangler::mangleType(const BlockPointerType *T) {
4285 Out << "U13block_pointer";
4286 mangleType(T->getPointeeType());
4287}
4288
4289void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
4290 // Mangle injected class name types as if the user had written the
4291 // specialization out fully. It may not actually be possible to see
4292 // this mangling, though.
4293 mangleType(T->getInjectedSpecializationType());
4294}
4295
4296void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
4297 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
4298 mangleTemplateName(TD, T->template_arguments());
4299 } else {
4300 if (mangleSubstitution(QualType(T, 0)))
4301 return;
4302
4303 mangleTemplatePrefix(T->getTemplateName());
4304
4305 // FIXME: GCC does not appear to mangle the template arguments when
4306 // the template in question is a dependent template name. Should we
4307 // emulate that badness?
4308 mangleTemplateArgs(T->getTemplateName(), T->template_arguments());
4309 addSubstitution(QualType(T, 0));
4310 }
4311}
4312
4313void CXXNameMangler::mangleType(const DependentNameType *T) {
4314 // Proposal by cxx-abi-dev, 2014-03-26
4315 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
4316 // # dependent elaborated type specifier using
4317 // # 'typename'
4318 // ::= Ts <name> # dependent elaborated type specifier using
4319 // # 'struct' or 'class'
4320 // ::= Tu <name> # dependent elaborated type specifier using
4321 // # 'union'
4322 // ::= Te <name> # dependent elaborated type specifier using
4323 // # 'enum'
4324 switch (T->getKeyword()) {
4325 case ElaboratedTypeKeyword::None:
4326 case ElaboratedTypeKeyword::Typename:
4327 break;
4328 case ElaboratedTypeKeyword::Struct:
4329 case ElaboratedTypeKeyword::Class:
4330 case ElaboratedTypeKeyword::Interface:
4331 Out << "Ts";
4332 break;
4333 case ElaboratedTypeKeyword::Union:
4334 Out << "Tu";
4335 break;
4336 case ElaboratedTypeKeyword::Enum:
4337 Out << "Te";
4338 break;
4339 }
4340 // Typename types are always nested
4341 Out << 'N';
4342 manglePrefix(T->getQualifier());
4343 mangleSourceName(T->getIdentifier());
4344 Out << 'E';
4345}
4346
4347void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
4348 // Dependently-scoped template types are nested if they have a prefix.
4349 Out << 'N';
4350
4351 // TODO: avoid making this TemplateName.
4352 TemplateName Prefix =
4353 getASTContext().getDependentTemplateName(T->getQualifier(),
4354 T->getIdentifier());
4355 mangleTemplatePrefix(Prefix);
4356
4357 // FIXME: GCC does not appear to mangle the template arguments when
4358 // the template in question is a dependent template name. Should we
4359 // emulate that badness?
4360 mangleTemplateArgs(Prefix, T->template_arguments());
4361 Out << 'E';
4362}
4363
4364void CXXNameMangler::mangleType(const TypeOfType *T) {
4365 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4366 // "extension with parameters" mangling.
4367 Out << "u6typeof";
4368}
4369
4370void CXXNameMangler::mangleType(const TypeOfExprType *T) {
4371 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4372 // "extension with parameters" mangling.
4373 Out << "u6typeof";
4374}
4375
4376void CXXNameMangler::mangleType(const DecltypeType *T) {
4377 Expr *E = T->getUnderlyingExpr();
4378
4379 // type ::= Dt <expression> E # decltype of an id-expression
4380 // # or class member access
4381 // ::= DT <expression> E # decltype of an expression
4382
4383 // This purports to be an exhaustive list of id-expressions and
4384 // class member accesses. Note that we do not ignore parentheses;
4385 // parentheses change the semantics of decltype for these
4386 // expressions (and cause the mangler to use the other form).
4387 if (isa<DeclRefExpr>(E) ||
4388 isa<MemberExpr>(E) ||
4389 isa<UnresolvedLookupExpr>(E) ||
4390 isa<DependentScopeDeclRefExpr>(E) ||
4391 isa<CXXDependentScopeMemberExpr>(E) ||
4392 isa<UnresolvedMemberExpr>(E))
4393 Out << "Dt";
4394 else
4395 Out << "DT";
4396 mangleExpression(E);
4397 Out << 'E';
4398}
4399
4400void CXXNameMangler::mangleType(const UnaryTransformType *T) {
4401 // If this is dependent, we need to record that. If not, we simply
4402 // mangle it as the underlying type since they are equivalent.
4403 if (T->isDependentType()) {
4404 Out << "u";
4405
4406 StringRef BuiltinName;
4407 switch (T->getUTTKind()) {
4408#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
4409 case UnaryTransformType::Enum: \
4410 BuiltinName = "__" #Trait; \
4411 break;
4412#include "clang/Basic/TransformTypeTraits.def"
4413 }
4414 Out << BuiltinName.size() << BuiltinName;
4415 }
4416
4417 Out << "I";
4418 mangleType(T->getBaseType());
4419 Out << "E";
4420}
4421
4422void CXXNameMangler::mangleType(const AutoType *T) {
4423 assert(T->getDeducedType().isNull() &&
4424 "Deduced AutoType shouldn't be handled here!");
4425 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
4426 "shouldn't need to mangle __auto_type!");
4427 // <builtin-type> ::= Da # auto
4428 // ::= Dc # decltype(auto)
4429 // ::= Dk # constrained auto
4430 // ::= DK # constrained decltype(auto)
4431 if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
4432 Out << (T->isDecltypeAuto() ? "DK" : "Dk");
4433 mangleTypeConstraint(T->getTypeConstraintConcept(),
4434 T->getTypeConstraintArguments());
4435 } else {
4436 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
4437 }
4438}
4439
4440void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4441 QualType Deduced = T->getDeducedType();
4442 if (!Deduced.isNull())
4443 return mangleType(Deduced);
4444
4445 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
4446 assert(TD && "shouldn't form deduced TST unless we know we have a template");
4447
4448 if (mangleSubstitution(TD))
4449 return;
4450
4451 mangleName(GlobalDecl(TD));
4452 addSubstitution(TD);
4453}
4454
4455void CXXNameMangler::mangleType(const AtomicType *T) {
4456 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4457 // (Until there's a standardized mangling...)
4458 Out << "U7_Atomic";
4459 mangleType(T->getValueType());
4460}
4461
4462void CXXNameMangler::mangleType(const PipeType *T) {
4463 // Pipe type mangling rules are described in SPIR 2.0 specification
4464 // A.1 Data types and A.3 Summary of changes
4465 // <type> ::= 8ocl_pipe
4466 Out << "8ocl_pipe";
4467}
4468
4469void CXXNameMangler::mangleType(const BitIntType *T) {
4470 // 5.1.5.2 Builtin types
4471 // <type> ::= DB <number | instantiation-dependent expression> _
4472 // ::= DU <number | instantiation-dependent expression> _
4473 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4474}
4475
4476void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4477 // 5.1.5.2 Builtin types
4478 // <type> ::= DB <number | instantiation-dependent expression> _
4479 // ::= DU <number | instantiation-dependent expression> _
4480 Out << "D" << (T->isUnsigned() ? "U" : "B");
4481 mangleExpression(T->getNumBitsExpr());
4482 Out << "_";
4483}
4484
4485void CXXNameMangler::mangleType(const ArrayParameterType *T) {
4486 mangleType(cast<ConstantArrayType>(T));
4487}
4488
4489void CXXNameMangler::mangleIntegerLiteral(QualType T,
4490 const llvm::APSInt &Value) {
4491 // <expr-primary> ::= L <type> <value number> E # integer literal
4492 Out << 'L';
4493
4494 mangleType(T);
4495 if (T->isBooleanType()) {
4496 // Boolean values are encoded as 0/1.
4497 Out << (Value.getBoolValue() ? '1' : '0');
4498 } else {
4499 mangleNumber(Value);
4500 }
4501 Out << 'E';
4502
4503}
4504
4505void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4506 // Ignore member expressions involving anonymous unions.
4507 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
4508 if (!RT->getDecl()->isAnonymousStructOrUnion())
4509 break;
4510 const auto *ME = dyn_cast<MemberExpr>(Base);
4511 if (!ME)
4512 break;
4513 Base = ME->getBase();
4514 IsArrow = ME->isArrow();
4515 }
4516
4517 if (Base->isImplicitCXXThis()) {
4518 // Note: GCC mangles member expressions to the implicit 'this' as
4519 // *this., whereas we represent them as this->. The Itanium C++ ABI
4520 // does not specify anything here, so we follow GCC.
4521 Out << "dtdefpT";
4522 } else {
4523 Out << (IsArrow ? "pt" : "dt");
4524 mangleExpression(Base);
4525 }
4526}
4527
4528/// Mangles a member expression.
4529void CXXNameMangler::mangleMemberExpr(const Expr *base,
4530 bool isArrow,
4531 NestedNameSpecifier *qualifier,
4532 NamedDecl *firstQualifierLookup,
4533 DeclarationName member,
4534 const TemplateArgumentLoc *TemplateArgs,
4535 unsigned NumTemplateArgs,
4536 unsigned arity) {
4537 // <expression> ::= dt <expression> <unresolved-name>
4538 // ::= pt <expression> <unresolved-name>
4539 if (base)
4540 mangleMemberExprBase(base, isArrow);
4541 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
4542}
4543
4544/// Look at the callee of the given call expression and determine if
4545/// it's a parenthesized id-expression which would have triggered ADL
4546/// otherwise.
4547static bool isParenthesizedADLCallee(const CallExpr *call) {
4548 const Expr *callee = call->getCallee();
4549 const Expr *fn = callee->IgnoreParens();
4550
4551 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4552 // too, but for those to appear in the callee, it would have to be
4553 // parenthesized.
4554 if (callee == fn) return false;
4555
4556 // Must be an unresolved lookup.
4557 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
4558 if (!lookup) return false;
4559
4560 assert(!lookup->requiresADL());
4561
4562 // Must be an unqualified lookup.
4563 if (lookup->getQualifier()) return false;
4564
4565 // Must not have found a class member. Note that if one is a class
4566 // member, they're all class members.
4567 if (lookup->getNumDecls() > 0 &&
4568 (*lookup->decls_begin())->isCXXClassMember())
4569 return false;
4570
4571 // Otherwise, ADL would have been triggered.
4572 return true;
4573}
4574
4575void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4576 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
4577 Out << CastEncoding;
4578 mangleType(ECE->getType());
4579 mangleExpression(ECE->getSubExpr());
4580}
4581
4582void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
4583 if (auto *Syntactic = InitList->getSyntacticForm())
4584 InitList = Syntactic;
4585 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
4586 mangleExpression(InitList->getInit(i));
4587}
4588
4589void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc,
4590 const concepts::Requirement *Req) {
4592
4593 // TODO: We can't mangle the result of a failed substitution. It's not clear
4594 // whether we should be mangling the original form prior to any substitution
4595 // instead. See https://lists.isocpp.org/core/2023/04/14118.php
4596 auto HandleSubstitutionFailure =
4597 [&](SourceLocation Loc) {
4598 DiagnosticsEngine &Diags = Context.getDiags();
4599 unsigned DiagID = Diags.getCustomDiagID(
4600 DiagnosticsEngine::Error, "cannot mangle this requires-expression "
4601 "containing a substitution failure");
4602 Diags.Report(Loc, DiagID);
4603 Out << 'F';
4604 };
4605
4606 switch (Req->getKind()) {
4607 case Requirement::RK_Type: {
4608 const auto *TR = cast<concepts::TypeRequirement>(Req);
4609 if (TR->isSubstitutionFailure())
4610 return HandleSubstitutionFailure(
4611 TR->getSubstitutionDiagnostic()->DiagLoc);
4612
4613 Out << 'T';
4614 mangleType(TR->getType()->getType());
4615 break;
4616 }
4617
4618 case Requirement::RK_Simple:
4619 case Requirement::RK_Compound: {
4620 const auto *ER = cast<concepts::ExprRequirement>(Req);
4621 if (ER->isExprSubstitutionFailure())
4622 return HandleSubstitutionFailure(
4623 ER->getExprSubstitutionDiagnostic()->DiagLoc);
4624
4625 Out << 'X';
4626 mangleExpression(ER->getExpr());
4627
4628 if (ER->hasNoexceptRequirement())
4629 Out << 'N';
4630
4631 if (!ER->getReturnTypeRequirement().isEmpty()) {
4632 if (ER->getReturnTypeRequirement().isSubstitutionFailure())
4633 return HandleSubstitutionFailure(ER->getReturnTypeRequirement()
4634 .getSubstitutionDiagnostic()
4635 ->DiagLoc);
4636
4637 Out << 'R';
4638 mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());
4639 }
4640 break;
4641 }
4642
4643 case Requirement::RK_Nested:
4644 const auto *NR = cast<concepts::NestedRequirement>(Req);
4645 if (NR->hasInvalidConstraint()) {
4646 // FIXME: NestedRequirement should track the location of its requires
4647 // keyword.
4648 return HandleSubstitutionFailure(RequiresExprLoc);
4649 }
4650
4651 Out << 'Q';
4652 mangleExpression(NR->getConstraintExpr());
4653 break;
4654 }
4655}
4656
4657void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4658 bool AsTemplateArg) {
4659 // <expression> ::= <unary operator-name> <expression>
4660 // ::= <binary operator-name> <expression> <expression>
4661 // ::= <trinary operator-name> <expression> <expression> <expression>
4662 // ::= cv <type> expression # conversion with one argument
4663 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4664 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
4665 // ::= sc <type> <expression> # static_cast<type> (expression)
4666 // ::= cc <type> <expression> # const_cast<type> (expression)
4667 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4668 // ::= st <type> # sizeof (a type)
4669 // ::= at <type> # alignof (a type)
4670 // ::= <template-param>
4671 // ::= <function-param>
4672 // ::= fpT # 'this' expression (part of <function-param>)
4673 // ::= sr <type> <unqualified-name> # dependent name
4674 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
4675 // ::= ds <expression> <expression> # expr.*expr
4676 // ::= sZ <template-param> # size of a parameter pack
4677 // ::= sZ <function-param> # size of a function parameter pack
4678 // ::= u <source-name> <template-arg>* E # vendor extended expression
4679 // ::= <expr-primary>
4680 // <expr-primary> ::= L <type> <value number> E # integer literal
4681 // ::= L <type> <value float> E # floating literal
4682 // ::= L <type> <string type> E # string literal
4683 // ::= L <nullptr type> E # nullptr literal "LDnE"
4684 // ::= L <pointer type> 0 E # null pointer template argument
4685 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
4686 // ::= L <mangled-name> E # external name
4687 QualType ImplicitlyConvertedToType;
4688
4689 // A top-level expression that's not <expr-primary> needs to be wrapped in
4690 // X...E in a template arg.
4691 bool IsPrimaryExpr = true;
4692 auto NotPrimaryExpr = [&] {
4693 if (AsTemplateArg && IsPrimaryExpr)
4694 Out << 'X';
4695 IsPrimaryExpr = false;
4696 };
4697
4698 auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4699 switch (D->getKind()) {
4700 default:
4701 // <expr-primary> ::= L <mangled-name> E # external name
4702 Out << 'L';
4703 mangle(D);
4704 Out << 'E';
4705 break;
4706
4707 case Decl::ParmVar:
4708 NotPrimaryExpr();
4709 mangleFunctionParam(cast<ParmVarDecl>(D));
4710 break;
4711
4712 case Decl::EnumConstant: {
4713 // <expr-primary>
4714 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4715 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4716 break;
4717 }
4718
4719 case Decl::NonTypeTemplateParm:
4720 NotPrimaryExpr();
4721 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4722 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4723 break;
4724 }
4725 };
4726
4727 // 'goto recurse' is used when handling a simple "unwrapping" node which
4728 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4729 // to be preserved.
4730recurse:
4731 switch (E->getStmtClass()) {
4732 case Expr::NoStmtClass:
4733#define ABSTRACT_STMT(Type)
4734#define EXPR(Type, Base)
4735#define STMT(Type, Base) \
4736 case Expr::Type##Class:
4737#include "clang/AST/StmtNodes.inc"
4738 // fallthrough
4739
4740 // These all can only appear in local or variable-initialization
4741 // contexts and so should never appear in a mangling.
4742 case Expr::AddrLabelExprClass:
4743 case Expr::DesignatedInitUpdateExprClass:
4744 case Expr::ImplicitValueInitExprClass:
4745 case Expr::ArrayInitLoopExprClass:
4746 case Expr::ArrayInitIndexExprClass:
4747 case Expr::NoInitExprClass:
4748 case Expr::ParenListExprClass:
4749 case Expr::MSPropertyRefExprClass:
4750 case Expr::MSPropertySubscriptExprClass:
4751 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
4752 case Expr::RecoveryExprClass:
4753 case Expr::ArraySectionExprClass:
4754 case Expr::OMPArrayShapingExprClass:
4755 case Expr::OMPIteratorExprClass:
4756 case Expr::CXXInheritedCtorInitExprClass:
4757 case Expr::CXXParenListInitExprClass:
4758 case Expr::PackIndexingExprClass:
4759 llvm_unreachable("unexpected statement kind");
4760
4761 case Expr::ConstantExprClass:
4762 E = cast<ConstantExpr>(E)->getSubExpr();
4763 goto recurse;
4764
4765 // FIXME: invent manglings for all these.
4766 case Expr::BlockExprClass:
4767 case Expr::ChooseExprClass:
4768 case Expr::CompoundLiteralExprClass:
4769 case Expr::ExtVectorElementExprClass:
4770 case Expr::GenericSelectionExprClass:
4771 case Expr::ObjCEncodeExprClass:
4772 case Expr::ObjCIsaExprClass:
4773 case Expr::ObjCIvarRefExprClass:
4774 case Expr::ObjCMessageExprClass:
4775 case Expr::ObjCPropertyRefExprClass:
4776 case Expr::ObjCProtocolExprClass:
4777 case Expr::ObjCSelectorExprClass:
4778 case Expr::ObjCStringLiteralClass:
4779 case Expr::ObjCBoxedExprClass:
4780 case Expr::ObjCArrayLiteralClass:
4781 case Expr::ObjCDictionaryLiteralClass:
4782 case Expr::ObjCSubscriptRefExprClass:
4783 case Expr::ObjCIndirectCopyRestoreExprClass:
4784 case Expr::ObjCAvailabilityCheckExprClass:
4785 case Expr::OffsetOfExprClass:
4786 case Expr::PredefinedExprClass:
4787 case Expr::ShuffleVectorExprClass:
4788 case Expr::ConvertVectorExprClass:
4789 case Expr::StmtExprClass:
4790 case Expr::ArrayTypeTraitExprClass:
4791 case Expr::ExpressionTraitExprClass:
4792 case Expr::VAArgExprClass:
4793 case Expr::CUDAKernelCallExprClass:
4794 case Expr::AsTypeExprClass:
4795 case Expr::PseudoObjectExprClass:
4796 case Expr::AtomicExprClass:
4797 case Expr::SourceLocExprClass:
4798 case Expr::EmbedExprClass:
4799 case Expr::BuiltinBitCastExprClass:
4800 {
4801 NotPrimaryExpr();
4802 if (!NullOut) {
4803 // As bad as this diagnostic is, it's better than crashing.
4804 DiagnosticsEngine &Diags = Context.getDiags();
4805 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4806 "cannot yet mangle expression type %0");
4807 Diags.Report(E->getExprLoc(), DiagID)
4808 << E->getStmtClassName() << E->getSourceRange();
4809 return;
4810 }
4811 break;
4812 }
4813
4814 case Expr::CXXUuidofExprClass: {
4815 NotPrimaryExpr();
4816 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4817 // As of clang 12, uuidof uses the vendor extended expression
4818 // mangling. Previously, it used a special-cased nonstandard extension.
4819 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
4820 Out << "u8__uuidof";
4821 if (UE->isTypeOperand())
4822 mangleType(UE->getTypeOperand(Context.getASTContext()));
4823 else
4824 mangleTemplateArgExpr(UE->getExprOperand());
4825 Out << 'E';
4826 } else {
4827 if (UE->isTypeOperand()) {
4828 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
4829 Out << "u8__uuidoft";
4830 mangleType(UuidT);
4831 } else {
4832 Expr *UuidExp = UE->getExprOperand();
4833 Out << "u8__uuidofz";
4834 mangleExpression(UuidExp);
4835 }
4836 }
4837 break;
4838 }
4839
4840 // Even gcc-4.5 doesn't mangle this.
4841 case Expr::BinaryConditionalOperatorClass: {
4842 NotPrimaryExpr();
4843 DiagnosticsEngine &Diags = Context.getDiags();
4844 unsigned DiagID =
4846 "?: operator with omitted middle operand cannot be mangled");
4847 Diags.Report(E->getExprLoc(), DiagID)
4848 << E->getStmtClassName() << E->getSourceRange();
4849 return;
4850 }
4851
4852 // These are used for internal purposes and cannot be meaningfully mangled.
4853 case Expr::OpaqueValueExprClass:
4854 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
4855
4856 case Expr::InitListExprClass: {
4857 NotPrimaryExpr();
4858 Out << "il";
4859 mangleInitListElements(cast<InitListExpr>(E));
4860 Out << "E";
4861 break;
4862 }
4863
4864 case Expr::DesignatedInitExprClass: {
4865 NotPrimaryExpr();
4866 auto *DIE = cast<DesignatedInitExpr>(E);
4867 for (const auto &Designator : DIE->designators()) {
4869 Out << "di";
4870 mangleSourceName(Designator.getFieldName());
4871 } else if (Designator.isArrayDesignator()) {
4872 Out << "dx";
4873 mangleExpression(DIE->getArrayIndex(Designator));
4874 } else {
4876 "unknown designator kind");
4877 Out << "dX";
4878 mangleExpression(DIE->getArrayRangeStart(Designator));
4879 mangleExpression(DIE->getArrayRangeEnd(Designator));
4880 }
4881 }
4882 mangleExpression(DIE->getInit());
4883 break;
4884 }
4885
4886 case Expr::CXXDefaultArgExprClass:
4887 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4888 goto recurse;
4889
4890 case Expr::CXXDefaultInitExprClass:
4891 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4892 goto recurse;
4893
4894 case Expr::CXXStdInitializerListExprClass:
4895 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
4896 goto recurse;
4897
4898 case Expr::SubstNonTypeTemplateParmExprClass: {
4899 // Mangle a substituted parameter the same way we mangle the template
4900 // argument.
4901 auto *SNTTPE = cast<SubstNonTypeTemplateParmExpr>(E);
4902 if (auto *CE = dyn_cast<ConstantExpr>(SNTTPE->getReplacement())) {
4903 // Pull out the constant value and mangle it as a template argument.
4904 QualType ParamType = SNTTPE->getParameterType(Context.getASTContext());
4905 assert(CE->hasAPValueResult() && "expected the NTTP to have an APValue");
4906 mangleValueInTemplateArg(ParamType, CE->getAPValueResult(), false,
4907 /*NeedExactType=*/true);
4908 break;
4909 }
4910 // The remaining cases all happen to be substituted with expressions that
4911 // mangle the same as a corresponding template argument anyway.
4912 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
4913 goto recurse;
4914 }
4915
4916 case Expr::UserDefinedLiteralClass:
4917 // We follow g++'s approach of mangling a UDL as a call to the literal
4918 // operator.
4919 case Expr::CXXMemberCallExprClass: // fallthrough
4920 case Expr::CallExprClass: {
4921 NotPrimaryExpr();
4922 const CallExpr *CE = cast<CallExpr>(E);
4923
4924 // <expression> ::= cp <simple-id> <expression>* E
4925 // We use this mangling only when the call would use ADL except
4926 // for being parenthesized. Per discussion with David
4927 // Vandervoorde, 2011.04.25.
4928 if (isParenthesizedADLCallee(CE)) {
4929 Out << "cp";
4930 // The callee here is a parenthesized UnresolvedLookupExpr with
4931 // no qualifier and should always get mangled as a <simple-id>
4932 // anyway.
4933
4934 // <expression> ::= cl <expression>* E
4935 } else {
4936 Out << "cl";
4937 }
4938
4939 unsigned CallArity = CE->getNumArgs();
4940 for (const Expr *Arg : CE->arguments())
4941 if (isa<PackExpansionExpr>(Arg))
4942 CallArity = UnknownArity;
4943
4944 mangleExpression(CE->getCallee(), CallArity);
4945 for (const Expr *Arg : CE->arguments())
4946 mangleExpression(Arg);
4947 Out << 'E';
4948 break;
4949 }
4950
4951 case Expr::CXXNewExprClass: {
4952 NotPrimaryExpr();
4953 const CXXNewExpr *New = cast<CXXNewExpr>(E);
4954 if (New->isGlobalNew()) Out << "gs";
4955 Out << (New->isArray() ? "na" : "nw");
4957 E = New->placement_arg_end(); I != E; ++I)
4958 mangleExpression(*I);
4959 Out << '_';
4960 mangleType(New->getAllocatedType());
4961 if (New->hasInitializer()) {
4962 if (New->getInitializationStyle() == CXXNewInitializationStyle::Braces)
4963 Out << "il";
4964 else
4965 Out << "pi";
4966 const Expr *Init = New->getInitializer();
4967 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
4968 // Directly inline the initializers.
4969 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
4970 E = CCE->arg_end();
4971 I != E; ++I)
4972 mangleExpression(*I);
4973 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
4974 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
4975 mangleExpression(PLE->getExpr(i));
4976 } else if (New->getInitializationStyle() ==
4977 CXXNewInitializationStyle::Braces &&
4978 isa<InitListExpr>(Init)) {
4979 // Only take InitListExprs apart for list-initialization.
4980 mangleInitListElements(cast<InitListExpr>(Init));
4981 } else
4982 mangleExpression(Init);
4983 }
4984 Out << 'E';
4985 break;
4986 }
4987
4988 case Expr::CXXPseudoDestructorExprClass: {
4989 NotPrimaryExpr();
4990 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
4991 if (const Expr *Base = PDE->getBase())
4992 mangleMemberExprBase(Base, PDE->isArrow());
4993 NestedNameSpecifier *Qualifier = PDE->getQualifier();
4994 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
4995 if (Qualifier) {
4996 mangleUnresolvedPrefix(Qualifier,
4997 /*recursive=*/true);
4998 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
4999 Out << 'E';
5000 } else {
5001 Out << "sr";
5002 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
5003 Out << 'E';
5004 }
5005 } else if (Qualifier) {
5006 mangleUnresolvedPrefix(Qualifier);
5007 }
5008 // <base-unresolved-name> ::= dn <destructor-name>
5009 Out << "dn";
5010 QualType DestroyedType = PDE->getDestroyedType();
5011 mangleUnresolvedTypeOrSimpleId(DestroyedType);
5012 break;
5013 }
5014
5015 case Expr::MemberExprClass: {
5016 NotPrimaryExpr();
5017 const MemberExpr *ME = cast<MemberExpr>(E);
5018 mangleMemberExpr(ME->getBase(), ME->isArrow(),
5019 ME->getQualifier(), nullptr,
5020 ME->getMemberDecl()->getDeclName(),
5022 Arity);
5023 break;
5024 }
5025
5026 case Expr::UnresolvedMemberExprClass: {
5027 NotPrimaryExpr();
5028 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
5029 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
5030 ME->isArrow(), ME->getQualifier(), nullptr,
5031 ME->getMemberName(),
5033 Arity);
5034 break;
5035 }
5036
5037 case Expr::CXXDependentScopeMemberExprClass: {
5038 NotPrimaryExpr();
5040 = cast<CXXDependentScopeMemberExpr>(E);
5041 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
5042 ME->isArrow(), ME->getQualifier(),
5044 ME->getMember(),
5046 Arity);
5047 break;
5048 }
5049
5050 case Expr::UnresolvedLookupExprClass: {
5051 NotPrimaryExpr();
5052 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
5053 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
5054 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
5055 Arity);
5056 break;
5057 }
5058
5059 case Expr::CXXUnresolvedConstructExprClass: {
5060 NotPrimaryExpr();
5061 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
5062 unsigned N = CE->getNumArgs();
5063
5064 if (CE->isListInitialization()) {
5065 assert(N == 1 && "unexpected form for list initialization");
5066 auto *IL = cast<InitListExpr>(CE->getArg(0));
5067 Out << "tl";
5068 mangleType(CE->getType());
5069 mangleInitListElements(IL);
5070 Out << "E";
5071 break;
5072 }
5073
5074 Out << "cv";
5075 mangleType(CE->getType());
5076 if (N != 1) Out << '_';
5077 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
5078 if (N != 1) Out << 'E';
5079 break;
5080 }
5081
5082 case Expr::CXXConstructExprClass: {
5083 // An implicit cast is silent, thus may contain <expr-primary>.
5084 const auto *CE = cast<CXXConstructExpr>(E);
5085 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
5086 assert(
5087 CE->getNumArgs() >= 1 &&
5088 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
5089 "implicit CXXConstructExpr must have one argument");
5090 E = cast<CXXConstructExpr>(E)->getArg(0);
5091 goto recurse;
5092 }
5093 NotPrimaryExpr();
5094 Out << "il";
5095 for (auto *E : CE->arguments())
5096 mangleExpression(E);
5097 Out << "E";
5098 break;
5099 }
5100
5101 case Expr::CXXTemporaryObjectExprClass: {
5102 NotPrimaryExpr();
5103 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
5104 unsigned N = CE->getNumArgs();
5105 bool List = CE->isListInitialization();
5106
5107 if (List)
5108 Out << "tl";
5109 else
5110 Out << "cv";
5111 mangleType(CE->getType());
5112 if (!List && N != 1)
5113 Out << '_';
5114 if (CE->isStdInitListInitialization()) {
5115 // We implicitly created a std::initializer_list<T> for the first argument
5116 // of a constructor of type U in an expression of the form U{a, b, c}.
5117 // Strip all the semantic gunk off the initializer list.
5118 auto *SILE =
5119 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
5120 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
5121 mangleInitListElements(ILE);
5122 } else {
5123 for (auto *E : CE->arguments())
5124 mangleExpression(E);
5125 }
5126 if (List || N != 1)
5127 Out << 'E';
5128 break;
5129 }
5130
5131 case Expr::CXXScalarValueInitExprClass:
5132 NotPrimaryExpr();
5133 Out << "cv";
5134 mangleType(E->getType());
5135 Out << "_E";
5136 break;
5137
5138 case Expr::CXXNoexceptExprClass:
5139 NotPrimaryExpr();
5140 Out << "nx";
5141 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
5142 break;
5143
5144 case Expr::UnaryExprOrTypeTraitExprClass: {
5145 // Non-instantiation-dependent traits are an <expr-primary> integer literal.
5146 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
5147
5148 if (!SAE->isInstantiationDependent()) {
5149 // Itanium C++ ABI:
5150 // If the operand of a sizeof or alignof operator is not
5151 // instantiation-dependent it is encoded as an integer literal
5152 // reflecting the result of the operator.
5153 //
5154 // If the result of the operator is implicitly converted to a known
5155 // integer type, that type is used for the literal; otherwise, the type
5156 // of std::size_t or std::ptrdiff_t is used.
5157 //
5158 // FIXME: We still include the operand in the profile in this case. This
5159 // can lead to mangling collisions between function templates that we
5160 // consider to be different.
5161 QualType T = (ImplicitlyConvertedToType.isNull() ||
5162 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
5163 : ImplicitlyConvertedToType;
5164 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
5165 mangleIntegerLiteral(T, V);
5166 break;
5167 }
5168
5169 NotPrimaryExpr(); // But otherwise, they are not.
5170
5171 auto MangleAlignofSizeofArg = [&] {
5172 if (SAE->isArgumentType()) {
5173 Out << 't';
5174 mangleType(SAE->getArgumentType());
5175 } else {
5176 Out << 'z';
5177 mangleExpression(SAE->getArgumentExpr());
5178 }
5179 };
5180
5181 switch(SAE->getKind()) {
5182 case UETT_SizeOf:
5183 Out << 's';
5184 MangleAlignofSizeofArg();
5185 break;
5186 case UETT_PreferredAlignOf:
5187 // As of clang 12, we mangle __alignof__ differently than alignof. (They
5188 // have acted differently since Clang 8, but were previously mangled the
5189 // same.)
5190 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
5191 Out << "u11__alignof__";
5192 if (SAE->isArgumentType())
5193 mangleType(SAE->getArgumentType());
5194 else
5195 mangleTemplateArgExpr(SAE->getArgumentExpr());
5196 Out << 'E';
5197 break;
5198 }
5199 [[fallthrough]];
5200 case UETT_AlignOf:
5201 Out << 'a';
5202 MangleAlignofSizeofArg();
5203 break;
5204 case UETT_DataSizeOf: {
5205 DiagnosticsEngine &Diags = Context.getDiags();
5206 unsigned DiagID =
5208 "cannot yet mangle __datasizeof expression");
5209 Diags.Report(DiagID);
5210 return;
5211 }
5212 case UETT_PtrAuthTypeDiscriminator: {
5213 DiagnosticsEngine &Diags = Context.getDiags();
5214 unsigned DiagID = Diags.getCustomDiagID(
5216 "cannot yet mangle __builtin_ptrauth_type_discriminator expression");
5217 Diags.Report(E->getExprLoc(), DiagID);
5218 return;
5219 }
5220 case UETT_VecStep: {
5221 DiagnosticsEngine &Diags = Context.getDiags();
5222 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
5223 "cannot yet mangle vec_step expression");
5224 Diags.Report(DiagID);
5225 return;
5226 }
5227 case UETT_OpenMPRequiredSimdAlign: {
5228 DiagnosticsEngine &Diags = Context.getDiags();
5229 unsigned DiagID = Diags.getCustomDiagID(
5231 "cannot yet mangle __builtin_omp_required_simd_align expression");
5232 Diags.Report(DiagID);
5233 return;
5234 }
5235 case UETT_VectorElements: {
5236 DiagnosticsEngine &Diags = Context.getDiags();
5237 unsigned DiagID = Diags.getCustomDiagID(
5239 "cannot yet mangle __builtin_vectorelements expression");
5240 Diags.Report(DiagID);
5241 return;
5242 }
5243 }
5244 break;
5245 }
5246
5247 case Expr::TypeTraitExprClass: {
5248 // <expression> ::= u <source-name> <template-arg>* E # vendor extension
5249 const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);
5250 NotPrimaryExpr();
5251 Out << 'u';
5252 llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());
5253 Out << Spelling.size() << Spelling;
5254 for (TypeSourceInfo *TSI : TTE->getArgs()) {
5255 mangleType(TSI->getType());
5256 }
5257 Out << 'E';
5258 break;
5259 }
5260
5261 case Expr::CXXThrowExprClass: {
5262 NotPrimaryExpr();
5263 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
5264 // <expression> ::= tw <expression> # throw expression
5265 // ::= tr # rethrow
5266 if (TE->getSubExpr()) {
5267 Out << "tw";
5268 mangleExpression(TE->getSubExpr());
5269 } else {
5270 Out << "tr";
5271 }
5272 break;
5273 }
5274
5275 case Expr::CXXTypeidExprClass: {
5276 NotPrimaryExpr();
5277 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
5278 // <expression> ::= ti <type> # typeid (type)
5279 // ::= te <expression> # typeid (expression)
5280 if (TIE->isTypeOperand()) {
5281 Out << "ti";
5282 mangleType(TIE->getTypeOperand(Context.getASTContext()));
5283 } else {
5284 Out << "te";
5285 mangleExpression(TIE->getExprOperand());
5286 }
5287 break;
5288 }
5289
5290 case Expr::CXXDeleteExprClass: {
5291 NotPrimaryExpr();
5292 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
5293 // <expression> ::= [gs] dl <expression> # [::] delete expr
5294 // ::= [gs] da <expression> # [::] delete [] expr
5295 if (DE->isGlobalDelete()) Out << "gs";
5296 Out << (DE->isArrayForm() ? "da" : "dl");
5297 mangleExpression(DE->getArgument());
5298 break;
5299 }
5300
5301 case Expr::UnaryOperatorClass: {
5302 NotPrimaryExpr();
5303 const UnaryOperator *UO = cast<UnaryOperator>(E);
5304 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
5305 /*Arity=*/1);
5306 mangleExpression(UO->getSubExpr());
5307 break;
5308 }
5309
5310 case Expr::ArraySubscriptExprClass: {
5311 NotPrimaryExpr();
5312 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
5313
5314 // Array subscript is treated as a syntactically weird form of
5315 // binary operator.
5316 Out << "ix";
5317 mangleExpression(AE->getLHS());
5318 mangleExpression(AE->getRHS());
5319 break;
5320 }
5321
5322 case Expr::MatrixSubscriptExprClass: {
5323 NotPrimaryExpr();
5324 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
5325 Out << "ixix";
5326 mangleExpression(ME->getBase());
5327 mangleExpression(ME->getRowIdx());
5328 mangleExpression(ME->getColumnIdx());
5329 break;
5330 }
5331
5332 case Expr::CompoundAssignOperatorClass: // fallthrough
5333 case Expr::BinaryOperatorClass: {
5334 NotPrimaryExpr();
5335 const BinaryOperator *BO = cast<BinaryOperator>(E);
5336 if (BO->getOpcode() == BO_PtrMemD)
5337 Out << "ds";
5338 else
5339 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
5340 /*Arity=*/2);
5341 mangleExpression(BO->getLHS());
5342 mangleExpression(BO->getRHS());
5343 break;
5344 }
5345
5346 case Expr::CXXRewrittenBinaryOperatorClass: {
5347 NotPrimaryExpr();
5348 // The mangled form represents the original syntax.
5350 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
5351 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
5352 /*Arity=*/2);
5353 mangleExpression(Decomposed.LHS);
5354 mangleExpression(Decomposed.RHS);
5355 break;
5356 }
5357
5358 case Expr::ConditionalOperatorClass: {
5359 NotPrimaryExpr();
5360 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
5361 mangleOperatorName(OO_Conditional, /*Arity=*/3);
5362 mangleExpression(CO->getCond());
5363 mangleExpression(CO->getLHS(), Arity);
5364 mangleExpression(CO->getRHS(), Arity);
5365 break;
5366 }
5367
5368 case Expr::ImplicitCastExprClass: {
5369 ImplicitlyConvertedToType = E->getType();
5370 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5371 goto recurse;
5372 }
5373
5374 case Expr::ObjCBridgedCastExprClass: {
5375 NotPrimaryExpr();
5376 // Mangle ownership casts as a vendor extended operator __bridge,
5377 // __bridge_transfer, or __bridge_retain.
5378 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
5379 Out << "v1U" << Kind.size() << Kind;
5380 mangleCastExpression(E, "cv");
5381 break;
5382 }
5383
5384 case Expr::CStyleCastExprClass:
5385 NotPrimaryExpr();
5386 mangleCastExpression(E, "cv");
5387 break;
5388
5389 case Expr::CXXFunctionalCastExprClass: {
5390 NotPrimaryExpr();
5391 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
5392 // FIXME: Add isImplicit to CXXConstructExpr.
5393 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
5394 if (CCE->getParenOrBraceRange().isInvalid())
5395 Sub = CCE->getArg(0)->IgnoreImplicit();
5396 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
5397 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
5398 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
5399 Out << "tl";
5400 mangleType(E->getType());
5401 mangleInitListElements(IL);
5402 Out << "E";
5403 } else {
5404 mangleCastExpression(E, "cv");
5405 }
5406 break;
5407 }
5408
5409 case Expr::CXXStaticCastExprClass:
5410 NotPrimaryExpr();
5411 mangleCastExpression(E, "sc");
5412 break;
5413 case Expr::CXXDynamicCastExprClass:
5414 NotPrimaryExpr();
5415 mangleCastExpression(E, "dc");
5416 break;
5417 case Expr::CXXReinterpretCastExprClass:
5418 NotPrimaryExpr();
5419 mangleCastExpression(E, "rc");
5420 break;
5421 case Expr::CXXConstCastExprClass:
5422 NotPrimaryExpr();
5423 mangleCastExpression(E, "cc");
5424 break;
5425 case Expr::CXXAddrspaceCastExprClass:
5426 NotPrimaryExpr();
5427 mangleCastExpression(E, "ac");
5428 break;
5429
5430 case Expr::CXXOperatorCallExprClass: {
5431 NotPrimaryExpr();
5432 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
5433 unsigned NumArgs = CE->getNumArgs();
5434 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
5435 // (the enclosing MemberExpr covers the syntactic portion).
5436 if (CE->getOperator() != OO_Arrow)
5437 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
5438 // Mangle the arguments.
5439 for (unsigned i = 0; i != NumArgs; ++i)
5440 mangleExpression(CE->getArg(i));
5441 break;
5442 }
5443
5444 case Expr::ParenExprClass:
5445 E = cast<ParenExpr>(E)->getSubExpr();
5446 goto recurse;
5447
5448 case Expr::ConceptSpecializationExprClass: {
5449 auto *CSE = cast<ConceptSpecializationExpr>(E);
5450 if (isCompatibleWith(LangOptions::ClangABI::Ver17)) {
5451 // Clang 17 and before mangled concept-ids as if they resolved to an
5452 // entity, meaning that references to enclosing template arguments don't
5453 // work.
5454 Out << "L_Z";
5455 mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
5456 Out << 'E';
5457 break;
5458 }
5459 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5460 NotPrimaryExpr();
5461 mangleUnresolvedName(
5462 CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
5463 CSE->getConceptNameInfo().getName(),
5464 CSE->getTemplateArgsAsWritten()->getTemplateArgs(),
5465 CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());
5466 break;
5467 }
5468
5469 case Expr::RequiresExprClass: {
5470 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5471 auto *RE = cast<RequiresExpr>(E);
5472 // This is a primary-expression in the C++ grammar, but does not have an
5473 // <expr-primary> mangling (starting with 'L').
5474 NotPrimaryExpr();
5475 if (RE->getLParenLoc().isValid()) {
5476 Out << "rQ";
5477 FunctionTypeDepthState saved = FunctionTypeDepth.push();
5478 if (RE->getLocalParameters().empty()) {
5479 Out << 'v';
5480 } else {
5481 for (ParmVarDecl *Param : RE->getLocalParameters()) {
5482 mangleType(Context.getASTContext().getSignatureParameterType(
5483 Param->getType()));
5484 }
5485 }
5486 Out << '_';
5487
5488 // The rest of the mangling is in the immediate scope of the parameters.
5489 FunctionTypeDepth.enterResultType();
5490 for (const concepts::Requirement *Req : RE->getRequirements())
5491 mangleRequirement(RE->getExprLoc(), Req);
5492 FunctionTypeDepth.pop(saved);
5493 Out << 'E';
5494 } else {
5495 Out << "rq";
5496 for (const concepts::Requirement *Req : RE->getRequirements())
5497 mangleRequirement(RE->getExprLoc(), Req);
5498 Out << 'E';
5499 }
5500 break;
5501 }
5502
5503 case Expr::DeclRefExprClass:
5504 // MangleDeclRefExpr helper handles primary-vs-nonprimary
5505 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
5506 break;
5507
5508 case Expr::SubstNonTypeTemplateParmPackExprClass:
5509 NotPrimaryExpr();
5510 // FIXME: not clear how to mangle this!
5511 // template <unsigned N...> class A {
5512 // template <class U...> void foo(U (&x)[N]...);
5513 // };
5514 Out << "_SUBSTPACK_";
5515 break;
5516
5517 case Expr::FunctionParmPackExprClass: {
5518 NotPrimaryExpr();
5519 // FIXME: not clear how to mangle this!
5520 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
5521 Out << "v110_SUBSTPACK";
5522 MangleDeclRefExpr(FPPE->getParameterPack());
5523 break;
5524 }
5525
5526 case Expr::DependentScopeDeclRefExprClass: {
5527 NotPrimaryExpr();
5528 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
5529 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
5530 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
5531 Arity);
5532 break;
5533 }
5534
5535 case Expr::CXXBindTemporaryExprClass:
5536 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
5537 goto recurse;
5538
5539 case Expr::ExprWithCleanupsClass:
5540 E = cast<ExprWithCleanups>(E)->getSubExpr();
5541 goto recurse;
5542
5543 case Expr::FloatingLiteralClass: {
5544 // <expr-primary>
5545 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
5546 mangleFloatLiteral(FL->getType(), FL->getValue());
5547 break;
5548 }
5549
5550 case Expr::FixedPointLiteralClass:
5551 // Currently unimplemented -- might be <expr-primary> in future?
5552 mangleFixedPointLiteral();
5553 break;
5554
5555 case Expr::CharacterLiteralClass:
5556 // <expr-primary>
5557 Out << 'L';
5558 mangleType(E->getType());
5559 Out << cast<CharacterLiteral>(E)->getValue();
5560 Out << 'E';
5561 break;
5562
5563 // FIXME. __objc_yes/__objc_no are mangled same as true/false
5564 case Expr::ObjCBoolLiteralExprClass:
5565 // <expr-primary>
5566 Out << "Lb";
5567 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5568 Out << 'E';
5569 break;
5570
5571 case Expr::CXXBoolLiteralExprClass:
5572 // <expr-primary>
5573 Out << "Lb";
5574 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5575 Out << 'E';
5576 break;
5577
5578 case Expr::IntegerLiteralClass: {
5579 // <expr-primary>
5580 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
5581 if (E->getType()->isSignedIntegerType())
5582 Value.setIsSigned(true);
5583 mangleIntegerLiteral(E->getType(), Value);
5584 break;
5585 }
5586
5587 case Expr::ImaginaryLiteralClass: {
5588 // <expr-primary>
5589 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
5590 // Mangle as if a complex literal.
5591 // Proposal from David Vandevoorde, 2010.06.30.
5592 Out << 'L';
5593 mangleType(E->getType());
5594 if (const FloatingLiteral *Imag =
5595 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
5596 // Mangle a floating-point zero of the appropriate type.
5597 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
5598 Out << '_';
5599 mangleFloat(Imag->getValue());
5600 } else {
5601 Out << "0_";
5602 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
5603 if (IE->getSubExpr()->getType()->isSignedIntegerType())
5604 Value.setIsSigned(true);
5605 mangleNumber(Value);
5606 }
5607 Out << 'E';
5608 break;
5609 }
5610
5611 case Expr::StringLiteralClass: {
5612 // <expr-primary>
5613 // Revised proposal from David Vandervoorde, 2010.07.15.
5614 Out << 'L';
5615 assert(isa<ConstantArrayType>(E->getType()));
5616 mangleType(E->getType());
5617 Out << 'E';
5618 break;
5619 }
5620
5621 case Expr::GNUNullExprClass:
5622 // <expr-primary>
5623 // Mangle as if an integer literal 0.
5624 mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
5625 break;
5626
5627 case Expr::CXXNullPtrLiteralExprClass: {
5628 // <expr-primary>
5629 Out << "LDnE";
5630 break;
5631 }
5632
5633 case Expr::LambdaExprClass: {
5634 // A lambda-expression can't appear in the signature of an
5635 // externally-visible declaration, so there's no standard mangling for
5636 // this, but mangling as a literal of the closure type seems reasonable.
5637 Out << "L";
5638 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
5639 Out << "E";
5640 break;
5641 }
5642
5643 case Expr::PackExpansionExprClass:
5644 NotPrimaryExpr();
5645 Out << "sp";
5646 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
5647 break;
5648
5649 case Expr::SizeOfPackExprClass: {
5650 NotPrimaryExpr();
5651 auto *SPE = cast<SizeOfPackExpr>(E);
5652 if (SPE->isPartiallySubstituted()) {
5653 Out << "sP";
5654 for (const auto &A : SPE->getPartialArguments())
5655 mangleTemplateArg(A, false);
5656 Out << "E";
5657 break;
5658 }
5659
5660 Out << "sZ";
5661 const NamedDecl *Pack = SPE->getPack();
5662 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
5663 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
5664 else if (const NonTypeTemplateParmDecl *NTTP
5665 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
5666 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
5667 else if (const TemplateTemplateParmDecl *TempTP
5668 = dyn_cast<TemplateTemplateParmDecl>(Pack))
5669 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
5670 else
5671 mangleFunctionParam(cast<ParmVarDecl>(Pack));
5672 break;
5673 }
5674
5675 case Expr::MaterializeTemporaryExprClass:
5676 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5677 goto recurse;
5678
5679 case Expr::CXXFoldExprClass: {
5680 NotPrimaryExpr();
5681 auto *FE = cast<CXXFoldExpr>(E);
5682 if (FE->isLeftFold())
5683 Out << (FE->getInit() ? "fL" : "fl");
5684 else
5685 Out << (FE->getInit() ? "fR" : "fr");
5686
5687 if (FE->getOperator() == BO_PtrMemD)
5688 Out << "ds";
5689 else
5690 mangleOperatorName(
5691 BinaryOperator::getOverloadedOperator(FE->getOperator()),
5692 /*Arity=*/2);
5693
5694 if (FE->getLHS())
5695 mangleExpression(FE->getLHS());
5696 if (FE->getRHS())
5697 mangleExpression(FE->getRHS());
5698 break;
5699 }
5700
5701 case Expr::CXXThisExprClass: