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