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