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