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