Thanks to visit codestin.com
Credit goes to clang.llvm.org

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)->getOriginalDecl()->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(cast<InjectedClassNameType>(Ty)
2560 ->getOriginalDecl()
2562 break;
2563
2564 case Type::DependentName:
2565 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2566 break;
2567
2568 case Type::Using:
2569 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2570 Prefix);
2571 }
2572
2573 return false;
2574}
2575
2576void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2577 switch (Name.getNameKind()) {
2586 llvm_unreachable("Not an operator name");
2587
2589 // <operator-name> ::= cv <type> # (cast)
2590 Out << "cv";
2591 mangleType(Name.getCXXNameType());
2592 break;
2593
2595 Out << "li";
2596 mangleSourceName(Name.getCXXLiteralIdentifier());
2597 return;
2598
2600 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2601 break;
2602 }
2603}
2604
2605void
2606CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2607 switch (OO) {
2608 // <operator-name> ::= nw # new
2609 case OO_New: Out << "nw"; break;
2610 // ::= na # new[]
2611 case OO_Array_New: Out << "na"; break;
2612 // ::= dl # delete
2613 case OO_Delete: Out << "dl"; break;
2614 // ::= da # delete[]
2615 case OO_Array_Delete: Out << "da"; break;
2616 // ::= ps # + (unary)
2617 // ::= pl # + (binary or unknown)
2618 case OO_Plus:
2619 Out << (Arity == 1? "ps" : "pl"); break;
2620 // ::= ng # - (unary)
2621 // ::= mi # - (binary or unknown)
2622 case OO_Minus:
2623 Out << (Arity == 1? "ng" : "mi"); break;
2624 // ::= ad # & (unary)
2625 // ::= an # & (binary or unknown)
2626 case OO_Amp:
2627 Out << (Arity == 1? "ad" : "an"); break;
2628 // ::= de # * (unary)
2629 // ::= ml # * (binary or unknown)
2630 case OO_Star:
2631 // Use binary when unknown.
2632 Out << (Arity == 1? "de" : "ml"); break;
2633 // ::= co # ~
2634 case OO_Tilde: Out << "co"; break;
2635 // ::= dv # /
2636 case OO_Slash: Out << "dv"; break;
2637 // ::= rm # %
2638 case OO_Percent: Out << "rm"; break;
2639 // ::= or # |
2640 case OO_Pipe: Out << "or"; break;
2641 // ::= eo # ^
2642 case OO_Caret: Out << "eo"; break;
2643 // ::= aS # =
2644 case OO_Equal: Out << "aS"; break;
2645 // ::= pL # +=
2646 case OO_PlusEqual: Out << "pL"; break;
2647 // ::= mI # -=
2648 case OO_MinusEqual: Out << "mI"; break;
2649 // ::= mL # *=
2650 case OO_StarEqual: Out << "mL"; break;
2651 // ::= dV # /=
2652 case OO_SlashEqual: Out << "dV"; break;
2653 // ::= rM # %=
2654 case OO_PercentEqual: Out << "rM"; break;
2655 // ::= aN # &=
2656 case OO_AmpEqual: Out << "aN"; break;
2657 // ::= oR # |=
2658 case OO_PipeEqual: Out << "oR"; break;
2659 // ::= eO # ^=
2660 case OO_CaretEqual: Out << "eO"; break;
2661 // ::= ls # <<
2662 case OO_LessLess: Out << "ls"; break;
2663 // ::= rs # >>
2664 case OO_GreaterGreater: Out << "rs"; break;
2665 // ::= lS # <<=
2666 case OO_LessLessEqual: Out << "lS"; break;
2667 // ::= rS # >>=
2668 case OO_GreaterGreaterEqual: Out << "rS"; break;
2669 // ::= eq # ==
2670 case OO_EqualEqual: Out << "eq"; break;
2671 // ::= ne # !=
2672 case OO_ExclaimEqual: Out << "ne"; break;
2673 // ::= lt # <
2674 case OO_Less: Out << "lt"; break;
2675 // ::= gt # >
2676 case OO_Greater: Out << "gt"; break;
2677 // ::= le # <=
2678 case OO_LessEqual: Out << "le"; break;
2679 // ::= ge # >=
2680 case OO_GreaterEqual: Out << "ge"; break;
2681 // ::= nt # !
2682 case OO_Exclaim: Out << "nt"; break;
2683 // ::= aa # &&
2684 case OO_AmpAmp: Out << "aa"; break;
2685 // ::= oo # ||
2686 case OO_PipePipe: Out << "oo"; break;
2687 // ::= pp # ++
2688 case OO_PlusPlus: Out << "pp"; break;
2689 // ::= mm # --
2690 case OO_MinusMinus: Out << "mm"; break;
2691 // ::= cm # ,
2692 case OO_Comma: Out << "cm"; break;
2693 // ::= pm # ->*
2694 case OO_ArrowStar: Out << "pm"; break;
2695 // ::= pt # ->
2696 case OO_Arrow: Out << "pt"; break;
2697 // ::= cl # ()
2698 case OO_Call: Out << "cl"; break;
2699 // ::= ix # []
2700 case OO_Subscript: Out << "ix"; break;
2701
2702 // ::= qu # ?
2703 // The conditional operator can't be overloaded, but we still handle it when
2704 // mangling expressions.
2705 case OO_Conditional: Out << "qu"; break;
2706 // Proposal on cxx-abi-dev, 2015-10-21.
2707 // ::= aw # co_await
2708 case OO_Coawait: Out << "aw"; break;
2709 // Proposed in cxx-abi github issue 43.
2710 // ::= ss # <=>
2711 case OO_Spaceship: Out << "ss"; break;
2712
2713 case OO_None:
2715 llvm_unreachable("Not an overloaded operator");
2716 }
2717}
2718
2719void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2720 // Vendor qualifiers come first and if they are order-insensitive they must
2721 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2722
2723 // <type> ::= U <addrspace-expr>
2724 if (DAST) {
2725 Out << "U2ASI";
2726 mangleExpression(DAST->getAddrSpaceExpr());
2727 Out << "E";
2728 }
2729
2730 // Address space qualifiers start with an ordinary letter.
2731 if (Quals.hasAddressSpace()) {
2732 // Address space extension:
2733 //
2734 // <type> ::= U <target-addrspace>
2735 // <type> ::= U <OpenCL-addrspace>
2736 // <type> ::= U <CUDA-addrspace>
2737
2738 SmallString<64> ASString;
2739 LangAS AS = Quals.getAddressSpace();
2740
2741 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2742 // <target-addrspace> ::= "AS" <address-space-number>
2743 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2744 if (TargetAS != 0 ||
2745 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
2746 ASString = "AS" + llvm::utostr(TargetAS);
2747 } else {
2748 switch (AS) {
2749 default: llvm_unreachable("Not a language specific address space");
2750 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2751 // "private"| "generic" | "device" |
2752 // "host" ]
2753 case LangAS::opencl_global:
2754 ASString = "CLglobal";
2755 break;
2756 case LangAS::opencl_global_device:
2757 ASString = "CLdevice";
2758 break;
2759 case LangAS::opencl_global_host:
2760 ASString = "CLhost";
2761 break;
2762 case LangAS::opencl_local:
2763 ASString = "CLlocal";
2764 break;
2765 case LangAS::opencl_constant:
2766 ASString = "CLconstant";
2767 break;
2768 case LangAS::opencl_private:
2769 ASString = "CLprivate";
2770 break;
2771 case LangAS::opencl_generic:
2772 ASString = "CLgeneric";
2773 break;
2774 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2775 // "device" | "host" ]
2776 case LangAS::sycl_global:
2777 ASString = "SYglobal";
2778 break;
2779 case LangAS::sycl_global_device:
2780 ASString = "SYdevice";
2781 break;
2782 case LangAS::sycl_global_host:
2783 ASString = "SYhost";
2784 break;
2785 case LangAS::sycl_local:
2786 ASString = "SYlocal";
2787 break;
2788 case LangAS::sycl_private:
2789 ASString = "SYprivate";
2790 break;
2791 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2792 case LangAS::cuda_device:
2793 ASString = "CUdevice";
2794 break;
2795 case LangAS::cuda_constant:
2796 ASString = "CUconstant";
2797 break;
2798 case LangAS::cuda_shared:
2799 ASString = "CUshared";
2800 break;
2801 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2802 case LangAS::ptr32_sptr:
2803 ASString = "ptr32_sptr";
2804 break;
2805 case LangAS::ptr32_uptr:
2806 // For z/OS, there are no special mangling rules applied to the ptr32
2807 // qualifier. Ex: void foo(int * __ptr32 p) -> _Z3f2Pi. The mangling for
2808 // "p" is treated the same as a regular integer pointer.
2809 if (!getASTContext().getTargetInfo().getTriple().isOSzOS())
2810 ASString = "ptr32_uptr";
2811 break;
2812 case LangAS::ptr64:
2813 ASString = "ptr64";
2814 break;
2815 }
2816 }
2817 if (!ASString.empty())
2818 mangleVendorQualifier(ASString);
2819 }
2820
2821 // The ARC ownership qualifiers start with underscores.
2822 // Objective-C ARC Extension:
2823 //
2824 // <type> ::= U "__strong"
2825 // <type> ::= U "__weak"
2826 // <type> ::= U "__autoreleasing"
2827 //
2828 // Note: we emit __weak first to preserve the order as
2829 // required by the Itanium ABI.
2831 mangleVendorQualifier("__weak");
2832
2833 // __unaligned (from -fms-extensions)
2834 if (Quals.hasUnaligned())
2835 mangleVendorQualifier("__unaligned");
2836
2837 // __ptrauth. Note that this is parameterized.
2838 if (PointerAuthQualifier PtrAuth = Quals.getPointerAuth()) {
2839 mangleVendorQualifier("__ptrauth");
2840 // For now, since we only allow non-dependent arguments, we can just
2841 // inline the mangling of those arguments as literals. We treat the
2842 // key and extra-discriminator arguments as 'unsigned int' and the
2843 // address-discriminated argument as 'bool'.
2844 Out << "I"
2845 "Lj"
2846 << PtrAuth.getKey()
2847 << "E"
2848 "Lb"
2849 << unsigned(PtrAuth.isAddressDiscriminated())
2850 << "E"
2851 "Lj"
2852 << PtrAuth.getExtraDiscriminator()
2853 << "E"
2854 "E";
2855 }
2856
2857 // Remaining ARC ownership qualifiers.
2858 switch (Quals.getObjCLifetime()) {
2860 break;
2861
2863 // Do nothing as we already handled this case above.
2864 break;
2865
2867 mangleVendorQualifier("__strong");
2868 break;
2869
2871 mangleVendorQualifier("__autoreleasing");
2872 break;
2873
2875 // The __unsafe_unretained qualifier is *not* mangled, so that
2876 // __unsafe_unretained types in ARC produce the same manglings as the
2877 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2878 // better ABI compatibility.
2879 //
2880 // It's safe to do this because unqualified 'id' won't show up
2881 // in any type signatures that need to be mangled.
2882 break;
2883 }
2884
2885 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2886 if (Quals.hasRestrict())
2887 Out << 'r';
2888 if (Quals.hasVolatile())
2889 Out << 'V';
2890 if (Quals.hasConst())
2891 Out << 'K';
2892}
2893
2894void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2895 Out << 'U' << name.size() << name;
2896}
2897
2898void CXXNameMangler::mangleVendorType(StringRef name) {
2899 Out << 'u' << name.size() << name;
2900}
2901
2902void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2903 // <ref-qualifier> ::= R # lvalue reference
2904 // ::= O # rvalue-reference
2905 switch (RefQualifier) {
2906 case RQ_None:
2907 break;
2908
2909 case RQ_LValue:
2910 Out << 'R';
2911 break;
2912
2913 case RQ_RValue:
2914 Out << 'O';
2915 break;
2916 }
2917}
2918
2919void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2920 Context.mangleObjCMethodNameAsSourceName(MD, Out);
2921}
2922
2923static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2924 ASTContext &Ctx) {
2925 if (Quals)
2926 return true;
2927 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2928 return true;
2929 if (Ty->isOpenCLSpecificType())
2930 return true;
2931 // From Clang 18.0 we correctly treat SVE types as substitution candidates.
2932 if (Ty->isSVESizelessBuiltinType() &&
2933 Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)
2934 return true;
2935 if (Ty->isBuiltinType())
2936 return false;
2937 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2938 // substitution candidates.
2939 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2940 isa<AutoType>(Ty))
2941 return false;
2942 // A placeholder type for class template deduction is substitutable with
2943 // its corresponding template name; this is handled specially when mangling
2944 // the type.
2945 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2946 if (DeducedTST->getDeducedType().isNull())
2947 return false;
2948 return true;
2949}
2950
2951void CXXNameMangler::mangleType(QualType T) {
2952 // If our type is instantiation-dependent but not dependent, we mangle
2953 // it as it was written in the source, removing any top-level sugar.
2954 // Otherwise, use the canonical type.
2955 //
2956 // FIXME: This is an approximation of the instantiation-dependent name
2957 // mangling rules, since we should really be using the type as written and
2958 // augmented via semantic analysis (i.e., with implicit conversions and
2959 // default template arguments) for any instantiation-dependent type.
2960 // Unfortunately, that requires several changes to our AST:
2961 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2962 // uniqued, so that we can handle substitutions properly
2963 // - Default template arguments will need to be represented in the
2964 // TemplateSpecializationType, since they need to be mangled even though
2965 // they aren't written.
2966 // - Conversions on non-type template arguments need to be expressed, since
2967 // they can affect the mangling of sizeof/alignof.
2968 //
2969 // FIXME: This is wrong when mapping to the canonical type for a dependent
2970 // type discards instantiation-dependent portions of the type, such as for:
2971 //
2972 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2973 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2974 //
2975 // It's also wrong in the opposite direction when instantiation-dependent,
2976 // canonically-equivalent types differ in some irrelevant portion of inner
2977 // type sugar. In such cases, we fail to form correct substitutions, eg:
2978 //
2979 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2980 //
2981 // We should instead canonicalize the non-instantiation-dependent parts,
2982 // regardless of whether the type as a whole is dependent or instantiation
2983 // dependent.
2985 T = T.getCanonicalType();
2986 else {
2987 // Desugar any types that are purely sugar.
2988 do {
2989 // Don't desugar through template specialization types that aren't
2990 // type aliases. We need to mangle the template arguments as written.
2991 if (const TemplateSpecializationType *TST
2992 = dyn_cast<TemplateSpecializationType>(T))
2993 if (!TST->isTypeAlias())
2994 break;
2995
2996 // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2997 // instantation-dependent qualifiers. See
2998 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2999
3000 QualType Desugared
3001 = T.getSingleStepDesugaredType(Context.getASTContext());
3002 if (Desugared == T)
3003 break;
3004
3005 T = Desugared;
3006 } while (true);
3007 }
3008 SplitQualType split = T.split();
3009 Qualifiers quals = split.Quals;
3010 const Type *ty = split.Ty;
3011
3012 bool isSubstitutable =
3013 isTypeSubstitutable(quals, ty, Context.getASTContext());
3014 if (isSubstitutable && mangleSubstitution(T))
3015 return;
3016
3017 // If we're mangling a qualified array type, push the qualifiers to
3018 // the element type.
3019 if (quals && isa<ArrayType>(T)) {
3020 ty = Context.getASTContext().getAsArrayType(T);
3021 quals = Qualifiers();
3022
3023 // Note that we don't update T: we want to add the
3024 // substitution at the original type.
3025 }
3026
3027 if (quals || ty->isDependentAddressSpaceType()) {
3028 if (const DependentAddressSpaceType *DAST =
3029 dyn_cast<DependentAddressSpaceType>(ty)) {
3030 SplitQualType splitDAST = DAST->getPointeeType().split();
3031 mangleQualifiers(splitDAST.Quals, DAST);
3032 mangleType(QualType(splitDAST.Ty, 0));
3033 } else {
3034 mangleQualifiers(quals);
3035
3036 // Recurse: even if the qualified type isn't yet substitutable,
3037 // the unqualified type might be.
3038 mangleType(QualType(ty, 0));
3039 }
3040 } else {
3041 switch (ty->getTypeClass()) {
3042#define ABSTRACT_TYPE(CLASS, PARENT)
3043#define NON_CANONICAL_TYPE(CLASS, PARENT) \
3044 case Type::CLASS: \
3045 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
3046 return;
3047#define TYPE(CLASS, PARENT) \
3048 case Type::CLASS: \
3049 mangleType(static_cast<const CLASS##Type*>(ty)); \
3050 break;
3051#include "clang/AST/TypeNodes.inc"
3052 }
3053 }
3054
3055 // Add the substitution.
3056 if (isSubstitutable)
3057 addSubstitution(T);
3058}
3059
3060void CXXNameMangler::mangleCXXRecordDecl(const CXXRecordDecl *Record,
3061 bool SuppressSubstitution) {
3062 if (mangleSubstitution(Record))
3063 return;
3064 mangleName(Record);
3065 if (SuppressSubstitution)
3066 return;
3067 addSubstitution(Record);
3068}
3069
3070void CXXNameMangler::mangleType(const BuiltinType *T) {
3071 // <type> ::= <builtin-type>
3072 // <builtin-type> ::= v # void
3073 // ::= w # wchar_t
3074 // ::= b # bool
3075 // ::= c # char
3076 // ::= a # signed char
3077 // ::= h # unsigned char
3078 // ::= s # short
3079 // ::= t # unsigned short
3080 // ::= i # int
3081 // ::= j # unsigned int
3082 // ::= l # long
3083 // ::= m # unsigned long
3084 // ::= x # long long, __int64
3085 // ::= y # unsigned long long, __int64
3086 // ::= n # __int128
3087 // ::= o # unsigned __int128
3088 // ::= f # float
3089 // ::= d # double
3090 // ::= e # long double, __float80
3091 // ::= g # __float128
3092 // ::= g # __ibm128
3093 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
3094 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
3095 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
3096 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3097 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
3098 // ::= Di # char32_t
3099 // ::= Ds # char16_t
3100 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3101 // ::= [DS] DA # N1169 fixed-point [_Sat] T _Accum
3102 // ::= [DS] DR # N1169 fixed-point [_Sat] T _Fract
3103 // ::= u <source-name> # vendor extended type
3104 //
3105 // <fixed-point-size>
3106 // ::= s # short
3107 // ::= t # unsigned short
3108 // ::= i # plain
3109 // ::= j # unsigned
3110 // ::= l # long
3111 // ::= m # unsigned long
3112 std::string type_name;
3113 // Normalize integer types as vendor extended types:
3114 // u<length>i<type size>
3115 // u<length>u<type size>
3116 if (NormalizeIntegers && T->isInteger()) {
3117 if (T->isSignedInteger()) {
3118 switch (getASTContext().getTypeSize(T)) {
3119 case 8:
3120 // Pick a representative for each integer size in the substitution
3121 // dictionary. (Its actual defined size is not relevant.)
3122 if (mangleSubstitution(BuiltinType::SChar))
3123 break;
3124 Out << "u2i8";
3125 addSubstitution(BuiltinType::SChar);
3126 break;
3127 case 16:
3128 if (mangleSubstitution(BuiltinType::Short))
3129 break;
3130 Out << "u3i16";
3131 addSubstitution(BuiltinType::Short);
3132 break;
3133 case 32:
3134 if (mangleSubstitution(BuiltinType::Int))
3135 break;
3136 Out << "u3i32";
3137 addSubstitution(BuiltinType::Int);
3138 break;
3139 case 64:
3140 if (mangleSubstitution(BuiltinType::Long))
3141 break;
3142 Out << "u3i64";
3143 addSubstitution(BuiltinType::Long);
3144 break;
3145 case 128:
3146 if (mangleSubstitution(BuiltinType::Int128))
3147 break;
3148 Out << "u4i128";
3149 addSubstitution(BuiltinType::Int128);
3150 break;
3151 default:
3152 llvm_unreachable("Unknown integer size for normalization");
3153 }
3154 } else {
3155 switch (getASTContext().getTypeSize(T)) {
3156 case 8:
3157 if (mangleSubstitution(BuiltinType::UChar))
3158 break;
3159 Out << "u2u8";
3160 addSubstitution(BuiltinType::UChar);
3161 break;
3162 case 16:
3163 if (mangleSubstitution(BuiltinType::UShort))
3164 break;
3165 Out << "u3u16";
3166 addSubstitution(BuiltinType::UShort);
3167 break;
3168 case 32:
3169 if (mangleSubstitution(BuiltinType::UInt))
3170 break;
3171 Out << "u3u32";
3172 addSubstitution(BuiltinType::UInt);
3173 break;
3174 case 64:
3175 if (mangleSubstitution(BuiltinType::ULong))
3176 break;
3177 Out << "u3u64";
3178 addSubstitution(BuiltinType::ULong);
3179 break;
3180 case 128:
3181 if (mangleSubstitution(BuiltinType::UInt128))
3182 break;
3183 Out << "u4u128";
3184 addSubstitution(BuiltinType::UInt128);
3185 break;
3186 default:
3187 llvm_unreachable("Unknown integer size for normalization");
3188 }
3189 }
3190 return;
3191 }
3192 switch (T->getKind()) {
3193 case BuiltinType::Void:
3194 Out << 'v';
3195 break;
3196 case BuiltinType::Bool:
3197 Out << 'b';
3198 break;
3199 case BuiltinType::Char_U:
3200 case BuiltinType::Char_S:
3201 Out << 'c';
3202 break;
3203 case BuiltinType::UChar:
3204 Out << 'h';
3205 break;
3206 case BuiltinType::UShort:
3207 Out << 't';
3208 break;
3209 case BuiltinType::UInt:
3210 Out << 'j';
3211 break;
3212 case BuiltinType::ULong:
3213 Out << 'm';
3214 break;
3215 case BuiltinType::ULongLong:
3216 Out << 'y';
3217 break;
3218 case BuiltinType::UInt128:
3219 Out << 'o';
3220 break;
3221 case BuiltinType::SChar:
3222 Out << 'a';
3223 break;
3224 case BuiltinType::WChar_S:
3225 case BuiltinType::WChar_U:
3226 Out << 'w';
3227 break;
3228 case BuiltinType::Char8:
3229 Out << "Du";
3230 break;
3231 case BuiltinType::Char16:
3232 Out << "Ds";
3233 break;
3234 case BuiltinType::Char32:
3235 Out << "Di";
3236 break;
3237 case BuiltinType::Short:
3238 Out << 's';
3239 break;
3240 case BuiltinType::Int:
3241 Out << 'i';
3242 break;
3243 case BuiltinType::Long:
3244 Out << 'l';
3245 break;
3246 case BuiltinType::LongLong:
3247 Out << 'x';
3248 break;
3249 case BuiltinType::Int128:
3250 Out << 'n';
3251 break;
3252 case BuiltinType::Float16:
3253 Out << "DF16_";
3254 break;
3255 case BuiltinType::ShortAccum:
3256 Out << "DAs";
3257 break;
3258 case BuiltinType::Accum:
3259 Out << "DAi";
3260 break;
3261 case BuiltinType::LongAccum:
3262 Out << "DAl";
3263 break;
3264 case BuiltinType::UShortAccum:
3265 Out << "DAt";
3266 break;
3267 case BuiltinType::UAccum:
3268 Out << "DAj";
3269 break;
3270 case BuiltinType::ULongAccum:
3271 Out << "DAm";
3272 break;
3273 case BuiltinType::ShortFract:
3274 Out << "DRs";
3275 break;
3276 case BuiltinType::Fract:
3277 Out << "DRi";
3278 break;
3279 case BuiltinType::LongFract:
3280 Out << "DRl";
3281 break;
3282 case BuiltinType::UShortFract:
3283 Out << "DRt";
3284 break;
3285 case BuiltinType::UFract:
3286 Out << "DRj";
3287 break;
3288 case BuiltinType::ULongFract:
3289 Out << "DRm";
3290 break;
3291 case BuiltinType::SatShortAccum:
3292 Out << "DSDAs";
3293 break;
3294 case BuiltinType::SatAccum:
3295 Out << "DSDAi";
3296 break;
3297 case BuiltinType::SatLongAccum:
3298 Out << "DSDAl";
3299 break;
3300 case BuiltinType::SatUShortAccum:
3301 Out << "DSDAt";
3302 break;
3303 case BuiltinType::SatUAccum:
3304 Out << "DSDAj";
3305 break;
3306 case BuiltinType::SatULongAccum:
3307 Out << "DSDAm";
3308 break;
3309 case BuiltinType::SatShortFract:
3310 Out << "DSDRs";
3311 break;
3312 case BuiltinType::SatFract:
3313 Out << "DSDRi";
3314 break;
3315 case BuiltinType::SatLongFract:
3316 Out << "DSDRl";
3317 break;
3318 case BuiltinType::SatUShortFract:
3319 Out << "DSDRt";
3320 break;
3321 case BuiltinType::SatUFract:
3322 Out << "DSDRj";
3323 break;
3324 case BuiltinType::SatULongFract:
3325 Out << "DSDRm";
3326 break;
3327 case BuiltinType::Half:
3328 Out << "Dh";
3329 break;
3330 case BuiltinType::Float:
3331 Out << 'f';
3332 break;
3333 case BuiltinType::Double:
3334 Out << 'd';
3335 break;
3336 case BuiltinType::LongDouble: {
3337 const TargetInfo *TI =
3338 getASTContext().getLangOpts().OpenMP &&
3339 getASTContext().getLangOpts().OpenMPIsTargetDevice
3340 ? getASTContext().getAuxTargetInfo()
3341 : &getASTContext().getTargetInfo();
3342 Out << TI->getLongDoubleMangling();
3343 break;
3344 }
3345 case BuiltinType::Float128: {
3346 const TargetInfo *TI =
3347 getASTContext().getLangOpts().OpenMP &&
3348 getASTContext().getLangOpts().OpenMPIsTargetDevice
3349 ? getASTContext().getAuxTargetInfo()
3350 : &getASTContext().getTargetInfo();
3351 Out << TI->getFloat128Mangling();
3352 break;
3353 }
3354 case BuiltinType::BFloat16: {
3355 const TargetInfo *TI =
3356 ((getASTContext().getLangOpts().OpenMP &&
3357 getASTContext().getLangOpts().OpenMPIsTargetDevice) ||
3358 getASTContext().getLangOpts().SYCLIsDevice)
3359 ? getASTContext().getAuxTargetInfo()
3360 : &getASTContext().getTargetInfo();
3361 Out << TI->getBFloat16Mangling();
3362 break;
3363 }
3364 case BuiltinType::Ibm128: {
3365 const TargetInfo *TI = &getASTContext().getTargetInfo();
3366 Out << TI->getIbm128Mangling();
3367 break;
3368 }
3369 case BuiltinType::NullPtr:
3370 Out << "Dn";
3371 break;
3372
3373#define BUILTIN_TYPE(Id, SingletonId)
3374#define PLACEHOLDER_TYPE(Id, SingletonId) \
3375 case BuiltinType::Id:
3376#include "clang/AST/BuiltinTypes.def"
3377 case BuiltinType::Dependent:
3378 if (!NullOut)
3379 llvm_unreachable("mangling a placeholder type");
3380 break;
3381 case BuiltinType::ObjCId:
3382 Out << "11objc_object";
3383 break;
3384 case BuiltinType::ObjCClass:
3385 Out << "10objc_class";
3386 break;
3387 case BuiltinType::ObjCSel:
3388 Out << "13objc_selector";
3389 break;
3390#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3391 case BuiltinType::Id: \
3392 type_name = "ocl_" #ImgType "_" #Suffix; \
3393 Out << type_name.size() << type_name; \
3394 break;
3395#include "clang/Basic/OpenCLImageTypes.def"
3396 case BuiltinType::OCLSampler:
3397 Out << "11ocl_sampler";
3398 break;
3399 case BuiltinType::OCLEvent:
3400 Out << "9ocl_event";
3401 break;
3402 case BuiltinType::OCLClkEvent:
3403 Out << "12ocl_clkevent";
3404 break;
3405 case BuiltinType::OCLQueue:
3406 Out << "9ocl_queue";
3407 break;
3408 case BuiltinType::OCLReserveID:
3409 Out << "13ocl_reserveid";
3410 break;
3411#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3412 case BuiltinType::Id: \
3413 type_name = "ocl_" #ExtType; \
3414 Out << type_name.size() << type_name; \
3415 break;
3416#include "clang/Basic/OpenCLExtensionTypes.def"
3417 // The SVE types are effectively target-specific. The mangling scheme
3418 // is defined in the appendices to the Procedure Call Standard for the
3419 // Arm Architecture.
3420#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
3421 case BuiltinType::Id: \
3422 if (T->getKind() == BuiltinType::SveBFloat16 && \
3423 isCompatibleWith(LangOptions::ClangABI::Ver17)) { \
3424 /* Prior to Clang 18.0 we used this incorrect mangled name */ \
3425 mangleVendorType("__SVBFloat16_t"); \
3426 } else { \
3427 type_name = #MangledName; \
3428 Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name; \
3429 } \
3430 break;
3431#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
3432 case BuiltinType::Id: \
3433 type_name = #MangledName; \
3434 Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name; \
3435 break;
3436#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
3437 case BuiltinType::Id: \
3438 type_name = #MangledName; \
3439 Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name; \
3440 break;
3441#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
3442 case BuiltinType::Id: \
3443 type_name = #MangledName; \
3444 Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name; \
3445 break;
3446#include "clang/Basic/AArch64ACLETypes.def"
3447#define PPC_VECTOR_TYPE(Name, Id, Size) \
3448 case BuiltinType::Id: \
3449 mangleVendorType(#Name); \
3450 break;
3451#include "clang/Basic/PPCTypes.def"
3452 // TODO: Check the mangling scheme for RISC-V V.
3453#define RVV_TYPE(Name, Id, SingletonId) \
3454 case BuiltinType::Id: \
3455 mangleVendorType(Name); \
3456 break;
3457#include "clang/Basic/RISCVVTypes.def"
3458#define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \
3459 case BuiltinType::Id: \
3460 mangleVendorType(MangledName); \
3461 break;
3462#include "clang/Basic/WebAssemblyReferenceTypes.def"
3463#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
3464 case BuiltinType::Id: \
3465 mangleVendorType(Name); \
3466 break;
3467#include "clang/Basic/AMDGPUTypes.def"
3468#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3469 case BuiltinType::Id: \
3470 mangleVendorType(#Name); \
3471 break;
3472#include "clang/Basic/HLSLIntangibleTypes.def"
3473 }
3474}
3475
3476StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3477 switch (CC) {
3478 case CC_C:
3479 return "";
3480
3481 case CC_X86VectorCall:
3482 case CC_X86Pascal:
3483 case CC_X86RegCall:
3484 case CC_AAPCS:
3485 case CC_AAPCS_VFP:
3487 case CC_AArch64SVEPCS:
3488 case CC_IntelOclBicc:
3489 case CC_SpirFunction:
3490 case CC_DeviceKernel:
3491 case CC_PreserveMost:
3492 case CC_PreserveAll:
3493 case CC_M68kRTD:
3494 case CC_PreserveNone:
3495 case CC_RISCVVectorCall:
3496#define CC_VLS_CASE(ABI_VLEN) case CC_RISCVVLSCall_##ABI_VLEN:
3497 CC_VLS_CASE(32)
3498 CC_VLS_CASE(64)
3499 CC_VLS_CASE(128)
3500 CC_VLS_CASE(256)
3501 CC_VLS_CASE(512)
3502 CC_VLS_CASE(1024)
3503 CC_VLS_CASE(2048)
3504 CC_VLS_CASE(4096)
3505 CC_VLS_CASE(8192)
3506 CC_VLS_CASE(16384)
3507 CC_VLS_CASE(32768)
3508 CC_VLS_CASE(65536)
3509#undef CC_VLS_CASE
3510 // FIXME: we should be mangling all of the above.
3511 return "";
3512
3513 case CC_X86ThisCall:
3514 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3515 // used explicitly. At this point, we don't have that much information in
3516 // the AST, since clang tends to bake the convention into the canonical
3517 // function type. thiscall only rarely used explicitly, so don't mangle it
3518 // for now.
3519 return "";
3520
3521 case CC_X86StdCall:
3522 return "stdcall";
3523 case CC_X86FastCall:
3524 return "fastcall";
3525 case CC_X86_64SysV:
3526 return "sysv_abi";
3527 case CC_Win64:
3528 return "ms_abi";
3529 case CC_Swift:
3530 return "swiftcall";
3531 case CC_SwiftAsync:
3532 return "swiftasynccall";
3533 }
3534 llvm_unreachable("bad calling convention");
3535}
3536
3537void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3538 // Fast path.
3539 if (T->getExtInfo() == FunctionType::ExtInfo())
3540 return;
3541
3542 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3543 // This will get more complicated in the future if we mangle other
3544 // things here; but for now, since we mangle ns_returns_retained as
3545 // a qualifier on the result type, we can get away with this:
3546 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
3547 if (!CCQualifier.empty())
3548 mangleVendorQualifier(CCQualifier);
3549
3550 // FIXME: regparm
3551 // FIXME: noreturn
3552}
3553
3567
3568static AAPCSBitmaskSME encodeAAPCSZAState(unsigned SMEAttrs) {
3569 switch (SMEAttrs) {
3580 default:
3581 llvm_unreachable("Unrecognised SME attribute");
3582 }
3583}
3584
3585// The mangling scheme for function types which have SME attributes is
3586// implemented as a "pseudo" template:
3587//
3588// '__SME_ATTRS<<normal_function_type>, <sme_state>>'
3589//
3590// Combining the function type with a bitmask representing the streaming and ZA
3591// properties of the function's interface.
3592//
3593// Mangling of SME keywords is described in more detail in the AArch64 ACLE:
3594// https://github.com/ARM-software/acle/blob/main/main/acle.md#c-mangling-of-sme-keywords
3595//
3596void CXXNameMangler::mangleSMEAttrs(unsigned SMEAttrs) {
3597 if (!SMEAttrs)
3598 return;
3599
3600 AAPCSBitmaskSME Bitmask = AAPCSBitmaskSME(0);
3603 else if (SMEAttrs & FunctionType::SME_PStateSMCompatibleMask)
3605
3608 else {
3611
3614 }
3615
3616 Out << "Lj" << static_cast<unsigned>(Bitmask) << "EE";
3617}
3618
3619void
3620CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3621 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3622
3623 // Note that these are *not* substitution candidates. Demanglers might
3624 // have trouble with this if the parameter type is fully substituted.
3625
3626 switch (PI.getABI()) {
3627 case ParameterABI::Ordinary:
3628 break;
3629
3630 // HLSL parameter mangling.
3631 case ParameterABI::HLSLOut:
3632 case ParameterABI::HLSLInOut:
3633 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3634 break;
3635
3636 // All of these start with "swift", so they come before "ns_consumed".
3637 case ParameterABI::SwiftContext:
3638 case ParameterABI::SwiftAsyncContext:
3639 case ParameterABI::SwiftErrorResult:
3640 case ParameterABI::SwiftIndirectResult:
3641 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3642 break;
3643 }
3644
3645 if (PI.isConsumed())
3646 mangleVendorQualifier("ns_consumed");
3647
3648 if (PI.isNoEscape())
3649 mangleVendorQualifier("noescape");
3650}
3651
3652// <type> ::= <function-type>
3653// <function-type> ::= [<CV-qualifiers>] F [Y]
3654// <bare-function-type> [<ref-qualifier>] E
3655void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3656 unsigned SMEAttrs = T->getAArch64SMEAttributes();
3657
3658 if (SMEAttrs)
3659 Out << "11__SME_ATTRSI";
3660
3661 mangleExtFunctionInfo(T);
3662
3663 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3664 // e.g. "const" in "int (A::*)() const".
3665 mangleQualifiers(T->getMethodQuals());
3666
3667 // Mangle instantiation-dependent exception-specification, if present,
3668 // per cxx-abi-dev proposal on 2016-10-11.
3671 Out << "DO";
3672 mangleExpression(T->getNoexceptExpr());
3673 Out << "E";
3674 } else {
3675 assert(T->getExceptionSpecType() == EST_Dynamic);
3676 Out << "Dw";
3677 for (auto ExceptTy : T->exceptions())
3678 mangleType(ExceptTy);
3679 Out << "E";
3680 }
3681 } else if (T->isNothrow()) {
3682 Out << "Do";
3683 }
3684
3685 Out << 'F';
3686
3687 // FIXME: We don't have enough information in the AST to produce the 'Y'
3688 // encoding for extern "C" function types.
3689 mangleBareFunctionType(T, /*MangleReturnType=*/true);
3690
3691 // Mangle the ref-qualifier, if present.
3692 mangleRefQualifier(T->getRefQualifier());
3693
3694 Out << 'E';
3695
3696 mangleSMEAttrs(SMEAttrs);
3697}
3698
3699void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3700 // Function types without prototypes can arise when mangling a function type
3701 // within an overloadable function in C. We mangle these as the absence of any
3702 // parameter types (not even an empty parameter list).
3703 Out << 'F';
3704
3705 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3706
3707 FunctionTypeDepth.enterResultType();
3708 mangleType(T->getReturnType());
3709 FunctionTypeDepth.leaveResultType();
3710
3711 FunctionTypeDepth.pop(saved);
3712 Out << 'E';
3713}
3714
3715void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3716 bool MangleReturnType,
3717 const FunctionDecl *FD) {
3718 // Record that we're in a function type. See mangleFunctionParam
3719 // for details on what we're trying to achieve here.
3720 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3721
3722 // <bare-function-type> ::= <signature type>+
3723 if (MangleReturnType) {
3724 FunctionTypeDepth.enterResultType();
3725
3726 // Mangle ns_returns_retained as an order-sensitive qualifier here.
3727 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3728 mangleVendorQualifier("ns_returns_retained");
3729
3730 // Mangle the return type without any direct ARC ownership qualifiers.
3731 QualType ReturnTy = Proto->getReturnType();
3732 if (ReturnTy.getObjCLifetime()) {
3733 auto SplitReturnTy = ReturnTy.split();
3734 SplitReturnTy.Quals.removeObjCLifetime();
3735 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3736 }
3737 mangleType(ReturnTy);
3738
3739 FunctionTypeDepth.leaveResultType();
3740 }
3741
3742 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3743 // <builtin-type> ::= v # void
3744 Out << 'v';
3745 } else {
3746 assert(!FD || FD->getNumParams() == Proto->getNumParams());
3747 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3748 // Mangle extended parameter info as order-sensitive qualifiers here.
3749 if (Proto->hasExtParameterInfos() && FD == nullptr) {
3750 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3751 }
3752
3753 // Mangle the type.
3754 QualType ParamTy = Proto->getParamType(I);
3755 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3756
3757 if (FD) {
3758 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3759 // Attr can only take 1 character, so we can hardcode the length
3760 // below.
3761 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3762 if (Attr->isDynamic())
3763 Out << "U25pass_dynamic_object_size" << Attr->getType();
3764 else
3765 Out << "U17pass_object_size" << Attr->getType();
3766 }
3767 }
3768 }
3769
3770 // <builtin-type> ::= z # ellipsis
3771 if (Proto->isVariadic())
3772 Out << 'z';
3773 }
3774
3775 if (FD) {
3776 FunctionTypeDepth.enterResultType();
3777 mangleRequiresClause(FD->getTrailingRequiresClause().ConstraintExpr);
3778 }
3779
3780 FunctionTypeDepth.pop(saved);
3781}
3782
3783// <type> ::= <class-enum-type>
3784// <class-enum-type> ::= <name>
3785void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3786 mangleName(T->getDecl());
3787}
3788
3789// <type> ::= <class-enum-type>
3790// <class-enum-type> ::= <name>
3791void CXXNameMangler::mangleType(const EnumType *T) {
3792 mangleType(static_cast<const TagType*>(T));
3793}
3794void CXXNameMangler::mangleType(const RecordType *T) {
3795 mangleType(static_cast<const TagType*>(T));
3796}
3797void CXXNameMangler::mangleType(const TagType *T) {
3798 mangleName(T->getOriginalDecl()->getDefinitionOrSelf());
3799}
3800
3801// <type> ::= <array-type>
3802// <array-type> ::= A <positive dimension number> _ <element type>
3803// ::= A [<dimension expression>] _ <element type>
3804void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3805 Out << 'A' << T->getSize() << '_';
3806 mangleType(T->getElementType());
3807}
3808void CXXNameMangler::mangleType(const VariableArrayType *T) {
3809 Out << 'A';
3810 // decayed vla types (size 0) will just be skipped.
3811 if (T->getSizeExpr())
3812 mangleExpression(T->getSizeExpr());
3813 Out << '_';
3814 mangleType(T->getElementType());
3815}
3816void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3817 Out << 'A';
3818 // A DependentSizedArrayType might not have size expression as below
3819 //
3820 // template<int ...N> int arr[] = {N...};
3821 if (T->getSizeExpr())
3822 mangleExpression(T->getSizeExpr());
3823 Out << '_';
3824 mangleType(T->getElementType());
3825}
3826void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3827 Out << "A_";
3828 mangleType(T->getElementType());
3829}
3830
3831// <type> ::= <pointer-to-member-type>
3832// <pointer-to-member-type> ::= M <class type> <member type>
3833void CXXNameMangler::mangleType(const MemberPointerType *T) {
3834 Out << 'M';
3835 if (auto *RD = T->getMostRecentCXXRecordDecl())
3836 mangleCXXRecordDecl(RD);
3837 else
3838 mangleType(QualType(T->getQualifier().getAsType(), 0));
3839 QualType PointeeType = T->getPointeeType();
3840 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3841 mangleType(FPT);
3842
3843 // Itanium C++ ABI 5.1.8:
3844 //
3845 // The type of a non-static member function is considered to be different,
3846 // for the purposes of substitution, from the type of a namespace-scope or
3847 // static member function whose type appears similar. The types of two
3848 // non-static member functions are considered to be different, for the
3849 // purposes of substitution, if the functions are members of different
3850 // classes. In other words, for the purposes of substitution, the class of
3851 // which the function is a member is considered part of the type of
3852 // function.
3853
3854 // Given that we already substitute member function pointers as a
3855 // whole, the net effect of this rule is just to unconditionally
3856 // suppress substitution on the function type in a member pointer.
3857 // We increment the SeqID here to emulate adding an entry to the
3858 // substitution table.
3859 ++SeqID;
3860 } else
3861 mangleType(PointeeType);
3862}
3863
3864// <type> ::= <template-param>
3865void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3866 mangleTemplateParameter(T->getDepth(), T->getIndex());
3867}
3868
3869// <type> ::= <template-param>
3870void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3871 // FIXME: not clear how to mangle this!
3872 // template <class T...> class A {
3873 // template <class U...> void foo(T(*)(U) x...);
3874 // };
3875 Out << "_SUBSTPACK_";
3876}
3877
3878void CXXNameMangler::mangleType(const SubstBuiltinTemplatePackType *T) {
3879 // FIXME: not clear how to mangle this!
3880 // template <class T...> class A {
3881 // template <class U...> void foo(__builtin_dedup_pack<T...>(*)(U) x...);
3882 // };
3883 Out << "_SUBSTBUILTINPACK_";
3884}
3885
3886// <type> ::= P <type> # pointer-to
3887void CXXNameMangler::mangleType(const PointerType *T) {
3888 Out << 'P';
3889 mangleType(T->getPointeeType());
3890}
3891void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3892 Out << 'P';
3893 mangleType(T->getPointeeType());
3894}
3895
3896// <type> ::= R <type> # reference-to
3897void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3898 Out << 'R';
3899 mangleType(T->getPointeeType());
3900}
3901
3902// <type> ::= O <type> # rvalue reference-to (C++0x)
3903void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3904 Out << 'O';
3905 mangleType(T->getPointeeType());
3906}
3907
3908// <type> ::= C <type> # complex pair (C 2000)
3909void CXXNameMangler::mangleType(const ComplexType *T) {
3910 Out << 'C';
3911 mangleType(T->getElementType());
3912}
3913
3914// ARM's ABI for Neon vector types specifies that they should be mangled as
3915// if they are structs (to match ARM's initial implementation). The
3916// vector type must be one of the special types predefined by ARM.
3917void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3918 QualType EltType = T->getElementType();
3919 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3920 const char *EltName = nullptr;
3921 if (T->getVectorKind() == VectorKind::NeonPoly) {
3922 switch (cast<BuiltinType>(EltType)->getKind()) {
3923 case BuiltinType::SChar:
3924 case BuiltinType::UChar:
3925 EltName = "poly8_t";
3926 break;
3927 case BuiltinType::Short:
3928 case BuiltinType::UShort:
3929 EltName = "poly16_t";
3930 break;
3931 case BuiltinType::LongLong:
3932 case BuiltinType::ULongLong:
3933 EltName = "poly64_t";
3934 break;
3935 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3936 }
3937 } else {
3938 switch (cast<BuiltinType>(EltType)->getKind()) {
3939 case BuiltinType::SChar: EltName = "int8_t"; break;
3940 case BuiltinType::UChar: EltName = "uint8_t"; break;
3941 case BuiltinType::Short: EltName = "int16_t"; break;
3942 case BuiltinType::UShort: EltName = "uint16_t"; break;
3943 case BuiltinType::Int: EltName = "int32_t"; break;
3944 case BuiltinType::UInt: EltName = "uint32_t"; break;
3945 case BuiltinType::LongLong: EltName = "int64_t"; break;
3946 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3947 case BuiltinType::Double: EltName = "float64_t"; break;
3948 case BuiltinType::Float: EltName = "float32_t"; break;
3949 case BuiltinType::Half: EltName = "float16_t"; break;
3950 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
3951 case BuiltinType::MFloat8:
3952 EltName = "mfloat8_t";
3953 break;
3954 default:
3955 llvm_unreachable("unexpected Neon vector element type");
3956 }
3957 }
3958 const char *BaseName = nullptr;
3959 unsigned BitSize = (T->getNumElements() *
3960 getASTContext().getTypeSize(EltType));
3961 if (BitSize == 64)
3962 BaseName = "__simd64_";
3963 else {
3964 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3965 BaseName = "__simd128_";
3966 }
3967 Out << strlen(BaseName) + strlen(EltName);
3968 Out << BaseName << EltName;
3969}
3970
3971void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3972 DiagnosticsEngine &Diags = Context.getDiags();
3973 unsigned DiagID = Diags.getCustomDiagID(
3975 "cannot mangle this dependent neon vector type yet");
3976 Diags.Report(T->getAttributeLoc(), DiagID);
3977}
3978
3979static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3980 switch (EltType->getKind()) {
3981 case BuiltinType::SChar:
3982 return "Int8";
3983 case BuiltinType::Short:
3984 return "Int16";
3985 case BuiltinType::Int:
3986 return "Int32";
3987 case BuiltinType::Long:
3988 case BuiltinType::LongLong:
3989 return "Int64";
3990 case BuiltinType::UChar:
3991 return "Uint8";
3992 case BuiltinType::UShort:
3993 return "Uint16";
3994 case BuiltinType::UInt:
3995 return "Uint32";
3996 case BuiltinType::ULong:
3997 case BuiltinType::ULongLong:
3998 return "Uint64";
3999 case BuiltinType::Half:
4000 return "Float16";
4001 case BuiltinType::Float:
4002 return "Float32";
4003 case BuiltinType::Double:
4004 return "Float64";
4005 case BuiltinType::BFloat16:
4006 return "Bfloat16";
4007 case BuiltinType::MFloat8:
4008 return "Mfloat8";
4009 default:
4010 llvm_unreachable("Unexpected vector element base type");
4011 }
4012}
4013
4014// AArch64's ABI for Neon vector types specifies that they should be mangled as
4015// the equivalent internal name. The vector type must be one of the special
4016// types predefined by ARM.
4017void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
4018 QualType EltType = T->getElementType();
4019 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
4020 unsigned BitSize =
4021 (T->getNumElements() * getASTContext().getTypeSize(EltType));
4022 (void)BitSize; // Silence warning.
4023
4024 assert((BitSize == 64 || BitSize == 128) &&
4025 "Neon vector type not 64 or 128 bits");
4026
4027 StringRef EltName;
4028 if (T->getVectorKind() == VectorKind::NeonPoly) {
4029 switch (cast<BuiltinType>(EltType)->getKind()) {
4030 case BuiltinType::UChar:
4031 EltName = "Poly8";
4032 break;
4033 case BuiltinType::UShort:
4034 EltName = "Poly16";
4035 break;
4036 case BuiltinType::ULong:
4037 case BuiltinType::ULongLong:
4038 EltName = "Poly64";
4039 break;
4040 default:
4041 llvm_unreachable("unexpected Neon polynomial vector element type");
4042 }
4043 } else
4044 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
4045
4046 std::string TypeName =
4047 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
4048 Out << TypeName.length() << TypeName;
4049}
4050void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
4051 DiagnosticsEngine &Diags = Context.getDiags();
4052 unsigned DiagID = Diags.getCustomDiagID(
4054 "cannot mangle this dependent neon vector type yet");
4055 Diags.Report(T->getAttributeLoc(), DiagID);
4056}
4057
4058// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
4059// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
4060// type as the sizeless variants.
4061//
4062// The mangling scheme for VLS types is implemented as a "pseudo" template:
4063//
4064// '__SVE_VLS<<type>, <vector length>>'
4065//
4066// Combining the existing SVE type and a specific vector length (in bits).
4067// For example:
4068//
4069// typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
4070//
4071// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
4072//
4073// "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
4074//
4075// i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
4076//
4077// The latest ACLE specification (00bet5) does not contain details of this
4078// mangling scheme, it will be specified in the next revision. The mangling
4079// scheme is otherwise defined in the appendices to the Procedure Call Standard
4080// for the Arm Architecture, see
4081// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
4082void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
4083 assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||
4084 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
4085 "expected fixed-length SVE vector!");
4086
4087 QualType EltType = T->getElementType();
4088 assert(EltType->isBuiltinType() &&
4089 "expected builtin type for fixed-length SVE vector!");
4090
4091 StringRef TypeName;
4092 switch (cast<BuiltinType>(EltType)->getKind()) {
4093 case BuiltinType::SChar:
4094 TypeName = "__SVInt8_t";
4095 break;
4096 case BuiltinType::UChar: {
4097 if (T->getVectorKind() == VectorKind::SveFixedLengthData)
4098 TypeName = "__SVUint8_t";
4099 else
4100 TypeName = "__SVBool_t";
4101 break;
4102 }
4103 case BuiltinType::Short:
4104 TypeName = "__SVInt16_t";
4105 break;
4106 case BuiltinType::UShort:
4107 TypeName = "__SVUint16_t";
4108 break;
4109 case BuiltinType::Int:
4110 TypeName = "__SVInt32_t";
4111 break;
4112 case BuiltinType::UInt:
4113 TypeName = "__SVUint32_t";
4114 break;
4115 case BuiltinType::Long:
4116 TypeName = "__SVInt64_t";
4117 break;
4118 case BuiltinType::ULong:
4119 TypeName = "__SVUint64_t";
4120 break;
4121 case BuiltinType::Half:
4122 TypeName = "__SVFloat16_t";
4123 break;
4124 case BuiltinType::Float:
4125 TypeName = "__SVFloat32_t";
4126 break;
4127 case BuiltinType::Double:
4128 TypeName = "__SVFloat64_t";
4129 break;
4130 case BuiltinType::BFloat16:
4131 TypeName = "__SVBfloat16_t";
4132 break;
4133 default:
4134 llvm_unreachable("unexpected element type for fixed-length SVE vector!");
4135 }
4136
4137 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4138
4139 if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)
4140 VecSizeInBits *= 8;
4141
4142 Out << "9__SVE_VLSI";
4143 mangleVendorType(TypeName);
4144 Out << "Lj" << VecSizeInBits << "EE";
4145}
4146
4147void CXXNameMangler::mangleAArch64FixedSveVectorType(
4148 const DependentVectorType *T) {
4149 DiagnosticsEngine &Diags = Context.getDiags();
4150 unsigned DiagID = Diags.getCustomDiagID(
4152 "cannot mangle this dependent fixed-length SVE vector type yet");
4153 Diags.Report(T->getAttributeLoc(), DiagID);
4154}
4155
4156void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {
4157 assert((T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4158 T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4159 T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4160 T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4161 T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) &&
4162 "expected fixed-length RVV vector!");
4163
4164 QualType EltType = T->getElementType();
4165 assert(EltType->isBuiltinType() &&
4166 "expected builtin type for fixed-length RVV vector!");
4167
4168 SmallString<20> TypeNameStr;
4169 llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
4170 TypeNameOS << "__rvv_";
4171 switch (cast<BuiltinType>(EltType)->getKind()) {
4172 case BuiltinType::SChar:
4173 TypeNameOS << "int8";
4174 break;
4175 case BuiltinType::UChar:
4176 if (T->getVectorKind() == VectorKind::RVVFixedLengthData)
4177 TypeNameOS << "uint8";
4178 else
4179 TypeNameOS << "bool";
4180 break;
4181 case BuiltinType::Short:
4182 TypeNameOS << "int16";
4183 break;
4184 case BuiltinType::UShort:
4185 TypeNameOS << "uint16";
4186 break;
4187 case BuiltinType::Int:
4188 TypeNameOS << "int32";
4189 break;
4190 case BuiltinType::UInt:
4191 TypeNameOS << "uint32";
4192 break;
4193 case BuiltinType::Long:
4194 TypeNameOS << "int64";
4195 break;
4196 case BuiltinType::ULong:
4197 TypeNameOS << "uint64";
4198 break;
4199 case BuiltinType::Float16:
4200 TypeNameOS << "float16";
4201 break;
4202 case BuiltinType::Float:
4203 TypeNameOS << "float32";
4204 break;
4205 case BuiltinType::Double:
4206 TypeNameOS << "float64";
4207 break;
4208 default:
4209 llvm_unreachable("unexpected element type for fixed-length RVV vector!");
4210 }
4211
4212 unsigned VecSizeInBits;
4213 switch (T->getVectorKind()) {
4214 case VectorKind::RVVFixedLengthMask_1:
4215 VecSizeInBits = 1;
4216 break;
4217 case VectorKind::RVVFixedLengthMask_2:
4218 VecSizeInBits = 2;
4219 break;
4220 case VectorKind::RVVFixedLengthMask_4:
4221 VecSizeInBits = 4;
4222 break;
4223 default:
4224 VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4225 break;
4226 }
4227
4228 // Apend the LMUL suffix.
4229 auto VScale = getASTContext().getTargetInfo().getVScaleRange(
4230 getASTContext().getLangOpts(),
4231 TargetInfo::ArmStreamingKind::NotStreaming);
4232 unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;
4233
4234 if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4235 TypeNameOS << 'm';
4236 if (VecSizeInBits >= VLen)
4237 TypeNameOS << (VecSizeInBits / VLen);
4238 else
4239 TypeNameOS << 'f' << (VLen / VecSizeInBits);
4240 } else {
4241 TypeNameOS << (VLen / VecSizeInBits);
4242 }
4243 TypeNameOS << "_t";
4244
4245 Out << "9__RVV_VLSI";
4246 mangleVendorType(TypeNameStr);
4247 Out << "Lj" << VecSizeInBits << "EE";
4248}
4249
4250void CXXNameMangler::mangleRISCVFixedRVVVectorType(
4251 const DependentVectorType *T) {
4252 DiagnosticsEngine &Diags = Context.getDiags();
4253 unsigned DiagID = Diags.getCustomDiagID(
4255 "cannot mangle this dependent fixed-length RVV vector type yet");
4256 Diags.Report(T->getAttributeLoc(), DiagID);
4257}
4258
4259// GNU extension: vector types
4260// <type> ::= <vector-type>
4261// <vector-type> ::= Dv <positive dimension number> _
4262// <extended element type>
4263// ::= Dv [<dimension expression>] _ <element type>
4264// <extended element type> ::= <element type>
4265// ::= p # AltiVec vector pixel
4266// ::= b # Altivec vector bool
4267void CXXNameMangler::mangleType(const VectorType *T) {
4268 if ((T->getVectorKind() == VectorKind::Neon ||
4269 T->getVectorKind() == VectorKind::NeonPoly)) {
4270 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4271 llvm::Triple::ArchType Arch =
4272 getASTContext().getTargetInfo().getTriple().getArch();
4273 if ((Arch == llvm::Triple::aarch64 ||
4274 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
4275 mangleAArch64NeonVectorType(T);
4276 else
4277 mangleNeonVectorType(T);
4278 return;
4279 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4280 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4281 mangleAArch64FixedSveVectorType(T);
4282 return;
4283 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4284 T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4285 T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4286 T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4287 T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
4288 mangleRISCVFixedRVVVectorType(T);
4289 return;
4290 }
4291 Out << "Dv" << T->getNumElements() << '_';
4292 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4293 Out << 'p';
4294 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4295 Out << 'b';
4296 else
4297 mangleType(T->getElementType());
4298}
4299
4300void CXXNameMangler::mangleType(const DependentVectorType *T) {
4301 if ((T->getVectorKind() == VectorKind::Neon ||
4302 T->getVectorKind() == VectorKind::NeonPoly)) {
4303 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4304 llvm::Triple::ArchType Arch =
4305 getASTContext().getTargetInfo().getTriple().getArch();
4306 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
4307 !Target.isOSDarwin())
4308 mangleAArch64NeonVectorType(T);
4309 else
4310 mangleNeonVectorType(T);
4311 return;
4312 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4313 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4314 mangleAArch64FixedSveVectorType(T);
4315 return;
4316 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4317 mangleRISCVFixedRVVVectorType(T);
4318 return;
4319 }
4320
4321 Out << "Dv";
4322 mangleExpression(T->getSizeExpr());
4323 Out << '_';
4324 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4325 Out << 'p';
4326 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4327 Out << 'b';
4328 else
4329 mangleType(T->getElementType());
4330}
4331
4332void CXXNameMangler::mangleType(const ExtVectorType *T) {
4333 mangleType(static_cast<const VectorType*>(T));
4334}
4335void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
4336 Out << "Dv";
4337 mangleExpression(T->getSizeExpr());
4338 Out << '_';
4339 mangleType(T->getElementType());
4340}
4341
4342void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
4343 // Mangle matrix types as a vendor extended type:
4344 // u<Len>matrix_typeI<Rows><Columns><element type>E
4345
4346 mangleVendorType("matrix_type");
4347
4348 Out << "I";
4349 auto &ASTCtx = getASTContext();
4350 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
4351 llvm::APSInt Rows(BitWidth);
4352 Rows = T->getNumRows();
4353 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
4354 llvm::APSInt Columns(BitWidth);
4355 Columns = T->getNumColumns();
4356 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
4357 mangleType(T->getElementType());
4358 Out << "E";
4359}
4360
4361void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
4362 // Mangle matrix types as a vendor extended type:
4363 // u<Len>matrix_typeI<row expr><column expr><element type>E
4364 mangleVendorType("matrix_type");
4365
4366 Out << "I";
4367 mangleTemplateArgExpr(T->getRowExpr());
4368 mangleTemplateArgExpr(T->getColumnExpr());
4369 mangleType(T->getElementType());
4370 Out << "E";
4371}
4372
4373void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
4374 SplitQualType split = T->getPointeeType().split();
4375 mangleQualifiers(split.Quals, T);
4376 mangleType(QualType(split.Ty, 0));
4377}
4378
4379void CXXNameMangler::mangleType(const PackExpansionType *T) {
4380 // <type> ::= Dp <type> # pack expansion (C++0x)
4381 Out << "Dp";
4382 mangleType(T->getPattern());
4383}
4384
4385void CXXNameMangler::mangleType(const PackIndexingType *T) {
4386 if (!T->hasSelectedType())
4387 mangleType(T->getPattern());
4388 else
4389 mangleType(T->getSelectedType());
4390}
4391
4392void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
4393 mangleSourceName(T->getDecl()->getIdentifier());
4394}
4395
4396void CXXNameMangler::mangleType(const ObjCObjectType *T) {
4397 // Treat __kindof as a vendor extended type qualifier.
4398 if (T->isKindOfType())
4399 Out << "U8__kindof";
4400
4401 if (!T->qual_empty()) {
4402 // Mangle protocol qualifiers.
4403 SmallString<64> QualStr;
4404 llvm::raw_svector_ostream QualOS(QualStr);
4405 QualOS << "objcproto";
4406 for (const auto *I : T->quals()) {
4407 StringRef name = I->getName();
4408 QualOS << name.size() << name;
4409 }
4410 mangleVendorQualifier(QualStr);
4411 }
4412
4413 mangleType(T->getBaseType());
4414
4415 if (T->isSpecialized()) {
4416 // Mangle type arguments as I <type>+ E
4417 Out << 'I';
4418 for (auto typeArg : T->getTypeArgs())
4419 mangleType(typeArg);
4420 Out << 'E';
4421 }
4422}
4423
4424void CXXNameMangler::mangleType(const BlockPointerType *T) {
4425 Out << "U13block_pointer";
4426 mangleType(T->getPointeeType());
4427}
4428
4429void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
4430 // Mangle injected class name types as if the user had written the
4431 // specialization out fully. It may not actually be possible to see
4432 // this mangling, though.
4433 mangleType(T->getOriginalDecl()->getCanonicalTemplateSpecializationType(
4434 getASTContext()));
4435}
4436
4437void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
4438 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
4439 mangleTemplateName(TD, T->template_arguments());
4440 } else {
4441 Out << 'N';
4442 mangleTemplatePrefix(T->getTemplateName());
4443
4444 // FIXME: GCC does not appear to mangle the template arguments when
4445 // the template in question is a dependent template name. Should we
4446 // emulate that badness?
4447 mangleTemplateArgs(T->getTemplateName(), T->template_arguments());
4448 Out << 'E';
4449 }
4450}
4451
4452void CXXNameMangler::mangleType(const DependentNameType *T) {
4453 // Proposal by cxx-abi-dev, 2014-03-26
4454 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
4455 // # dependent elaborated type specifier using
4456 // # 'typename'
4457 // ::= Ts <name> # dependent elaborated type specifier using
4458 // # 'struct' or 'class'
4459 // ::= Tu <name> # dependent elaborated type specifier using
4460 // # 'union'
4461 // ::= Te <name> # dependent elaborated type specifier using
4462 // # 'enum'
4463 switch (T->getKeyword()) {
4464 case ElaboratedTypeKeyword::None:
4465 case ElaboratedTypeKeyword::Typename:
4466 break;
4467 case ElaboratedTypeKeyword::Struct:
4468 case ElaboratedTypeKeyword::Class:
4469 case ElaboratedTypeKeyword::Interface:
4470 Out << "Ts";
4471 break;
4472 case ElaboratedTypeKeyword::Union:
4473 Out << "Tu";
4474 break;
4475 case ElaboratedTypeKeyword::Enum:
4476 Out << "Te";
4477 break;
4478 }
4479 // Typename types are always nested
4480 Out << 'N';
4481 manglePrefix(T->getQualifier());
4482 mangleSourceName(T->getIdentifier());
4483 Out << 'E';
4484}
4485
4486void CXXNameMangler::mangleType(const TypeOfType *T) {
4487 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4488 // "extension with parameters" mangling.
4489 Out << "u6typeof";
4490}
4491
4492void CXXNameMangler::mangleType(const TypeOfExprType *T) {
4493 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4494 // "extension with parameters" mangling.
4495 Out << "u6typeof";
4496}
4497
4498void CXXNameMangler::mangleType(const DecltypeType *T) {
4499 Expr *E = T->getUnderlyingExpr();
4500
4501 // type ::= Dt <expression> E # decltype of an id-expression
4502 // # or class member access
4503 // ::= DT <expression> E # decltype of an expression
4504
4505 // This purports to be an exhaustive list of id-expressions and
4506 // class member accesses. Note that we do not ignore parentheses;
4507 // parentheses change the semantics of decltype for these
4508 // expressions (and cause the mangler to use the other form).
4509 if (isa<DeclRefExpr>(E) ||
4510 isa<MemberExpr>(E) ||
4515 Out << "Dt";
4516 else
4517 Out << "DT";
4518 mangleExpression(E);
4519 Out << 'E';
4520}
4521
4522void CXXNameMangler::mangleType(const UnaryTransformType *T) {
4523 // If this is dependent, we need to record that. If not, we simply
4524 // mangle it as the underlying type since they are equivalent.
4525 if (T->isDependentType()) {
4526 StringRef BuiltinName;
4527 switch (T->getUTTKind()) {
4528#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
4529 case UnaryTransformType::Enum: \
4530 BuiltinName = "__" #Trait; \
4531 break;
4532#include "clang/Basic/TransformTypeTraits.def"
4533 }
4534 mangleVendorType(BuiltinName);
4535 }
4536
4537 Out << "I";
4538 mangleType(T->getBaseType());
4539 Out << "E";
4540}
4541
4542void CXXNameMangler::mangleType(const AutoType *T) {
4543 assert(T->getDeducedType().isNull() &&
4544 "Deduced AutoType shouldn't be handled here!");
4545 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
4546 "shouldn't need to mangle __auto_type!");
4547 // <builtin-type> ::= Da # auto
4548 // ::= Dc # decltype(auto)
4549 // ::= Dk # constrained auto
4550 // ::= DK # constrained decltype(auto)
4551 if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
4552 Out << (T->isDecltypeAuto() ? "DK" : "Dk");
4553 mangleTypeConstraint(T->getTypeConstraintConcept(),
4554 T->getTypeConstraintArguments());
4555 } else {
4556 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
4557 }
4558}
4559
4560void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4561 QualType Deduced = T->getDeducedType();
4562 if (!Deduced.isNull())
4563 return mangleType(Deduced);
4564
4565 TemplateName TN = T->getTemplateName();
4566 assert(TN.getAsTemplateDecl() &&
4567 "shouldn't form deduced TST unless we know we have a template");
4568 mangleType(TN);
4569}
4570
4571void CXXNameMangler::mangleType(const AtomicType *T) {
4572 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4573 // (Until there's a standardized mangling...)
4574 Out << "U7_Atomic";
4575 mangleType(T->getValueType());
4576}
4577
4578void CXXNameMangler::mangleType(const PipeType *T) {
4579 // Pipe type mangling rules are described in SPIR 2.0 specification
4580 // A.1 Data types and A.3 Summary of changes
4581 // <type> ::= 8ocl_pipe
4582 Out << "8ocl_pipe";
4583}
4584
4585void CXXNameMangler::mangleType(const BitIntType *T) {
4586 // 5.1.5.2 Builtin types
4587 // <type> ::= DB <number | instantiation-dependent expression> _
4588 // ::= DU <number | instantiation-dependent expression> _
4589 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4590}
4591
4592void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4593 // 5.1.5.2 Builtin types
4594 // <type> ::= DB <number | instantiation-dependent expression> _
4595 // ::= DU <number | instantiation-dependent expression> _
4596 Out << "D" << (T->isUnsigned() ? "U" : "B");
4597 mangleExpression(T->getNumBitsExpr());
4598 Out << "_";
4599}
4600
4601void CXXNameMangler::mangleType(const ArrayParameterType *T) {
4602 mangleType(cast<ConstantArrayType>(T));
4603}
4604
4605void CXXNameMangler::mangleType(const HLSLAttributedResourceType *T) {
4606 llvm::SmallString<64> Str("_Res");
4607 const HLSLAttributedResourceType::Attributes &Attrs = T->getAttrs();
4608 // map resource class to HLSL virtual register letter
4609 switch (Attrs.ResourceClass) {
4610 case llvm::dxil::ResourceClass::UAV:
4611 Str += "_u";
4612 break;
4613 case llvm::dxil::ResourceClass::SRV:
4614 Str += "_t";
4615 break;
4616 case llvm::dxil::ResourceClass::CBuffer:
4617 Str += "_b";
4618 break;
4619 case llvm::dxil::ResourceClass::Sampler:
4620 Str += "_s";
4621 break;
4622 }
4623 if (Attrs.IsROV)
4624 Str += "_ROV";
4625 if (Attrs.RawBuffer)
4626 Str += "_Raw";
4627 if (T->hasContainedType())
4628 Str += "_CT";
4629 mangleVendorQualifier(Str);
4630
4631 if (T->hasContainedType()) {
4632 mangleType(T->getContainedType());
4633 }
4634 mangleType(T->getWrappedType());
4635}
4636
4637void CXXNameMangler::mangleType(const HLSLInlineSpirvType *T) {
4638 SmallString<20> TypeNameStr;
4639 llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
4640
4641 TypeNameOS << "spirv_type";
4642
4643 TypeNameOS << "_" << T->getOpcode();
4644 TypeNameOS << "_" << T->getSize();
4645 TypeNameOS << "_" << T->getAlignment();
4646
4647 mangleVendorType(TypeNameStr);
4648
4649 for (auto &Operand : T->getOperands()) {
4650 using SpirvOperandKind = SpirvOperand::SpirvOperandKind;
4651
4652 switch (Operand.getKind()) {
4653 case SpirvOperandKind::ConstantId:
4654 mangleVendorQualifier("_Const");
4655 mangleIntegerLiteral(Operand.getResultType(),
4656 llvm::APSInt(Operand.getValue()));
4657 break;
4658 case SpirvOperandKind::Literal:
4659 mangleVendorQualifier("_Lit");
4660 mangleIntegerLiteral(Context.getASTContext().IntTy,
4661 llvm::APSInt(Operand.getValue()));
4662 break;
4663 case SpirvOperandKind::TypeId:
4664 mangleVendorQualifier("_Type");
4665 mangleType(Operand.getResultType());
4666 break;
4667 default:
4668 llvm_unreachable("Invalid SpirvOperand kind");
4669 break;
4670 }
4671 TypeNameOS << Operand.getKind();
4672 }
4673}
4674
4675void CXXNameMangler::mangleIntegerLiteral(QualType T,
4676 const llvm::APSInt &Value) {
4677 // <expr-primary> ::= L <type> <value number> E # integer literal
4678 Out << 'L';
4679
4680 mangleType(T);
4681 if (T->isBooleanType()) {
4682 // Boolean values are encoded as 0/1.
4683 Out << (Value.getBoolValue() ? '1' : '0');
4684 } else {
4685 mangleNumber(Value);
4686 }
4687 Out << 'E';
4688}
4689
4690void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4691 // Ignore member expressions involving anonymous unions.
4692 while (const auto *RT = Base->getType()->getAsCanonical<RecordType>()) {
4693 if (!RT->getOriginalDecl()->isAnonymousStructOrUnion())
4694 break;
4695 const auto *ME = dyn_cast<MemberExpr>(Base);
4696 if (!ME)
4697 break;
4698 Base = ME->getBase();
4699 IsArrow = ME->isArrow();
4700 }
4701
4702 if (Base->isImplicitCXXThis()) {
4703 // Note: GCC mangles member expressions to the implicit 'this' as
4704 // *this., whereas we represent them as this->. The Itanium C++ ABI
4705 // does not specify anything here, so we follow GCC.
4706 Out << "dtdefpT";
4707 } else {
4708 Out << (IsArrow ? "pt" : "dt");
4709 mangleExpression(Base);
4710 }
4711}
4712
4713/// Mangles a member expression.
4714void CXXNameMangler::mangleMemberExpr(const Expr *base, bool isArrow,
4715 NestedNameSpecifier Qualifier,
4716 NamedDecl *firstQualifierLookup,
4717 DeclarationName member,
4718 const TemplateArgumentLoc *TemplateArgs,
4719 unsigned NumTemplateArgs,
4720 unsigned arity) {
4721 // <expression> ::= dt <expression> <unresolved-name>
4722 // ::= pt <expression> <unresolved-name>
4723 if (base)
4724 mangleMemberExprBase(base, isArrow);
4725 mangleUnresolvedName(Qualifier, member, TemplateArgs, NumTemplateArgs, arity);
4726}
4727
4728/// Look at the callee of the given call expression and determine if
4729/// it's a parenthesized id-expression which would have triggered ADL
4730/// otherwise.
4731static bool isParenthesizedADLCallee(const CallExpr *call) {
4732 const Expr *callee = call->getCallee();
4733 const Expr *fn = callee->IgnoreParens();
4734
4735 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4736 // too, but for those to appear in the callee, it would have to be
4737 // parenthesized.
4738 if (callee == fn) return false;
4739
4740 // Must be an unresolved lookup.
4741 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
4742 if (!lookup) return false;
4743
4744 assert(!lookup->requiresADL());
4745
4746 // Must be an unqualified lookup.
4747 if (lookup->getQualifier()) return false;
4748
4749 // Must not have found a class member. Note that if one is a class
4750 // member, they're all class members.
4751 if (lookup->getNumDecls() > 0 &&
4752 (*lookup->decls_begin())->isCXXClassMember())
4753 return false;
4754
4755 // Otherwise, ADL would have been triggered.
4756 return true;
4757}
4758
4759void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4760 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
4761 Out << CastEncoding;
4762 mangleType(ECE->getType());
4763 mangleExpression(ECE->getSubExpr());
4764}
4765
4766void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
4767 if (auto *Syntactic = InitList->getSyntacticForm())
4768 InitList = Syntactic;
4769 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
4770 mangleExpression(InitList->getInit(i));
4771}
4772
4773void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc,
4774 const concepts::Requirement *Req) {
4775 using concepts::Requirement;
4776
4777 // TODO: We can't mangle the result of a failed substitution. It's not clear
4778 // whether we should be mangling the original form prior to any substitution
4779 // instead. See https://lists.isocpp.org/core/2023/04/14118.php
4780 auto HandleSubstitutionFailure =
4781 [&](SourceLocation Loc) {
4782 DiagnosticsEngine &Diags = Context.getDiags();
4783 unsigned DiagID = Diags.getCustomDiagID(
4784 DiagnosticsEngine::Error, "cannot mangle this requires-expression "
4785 "containing a substitution failure");
4786 Diags.Report(Loc, DiagID);
4787 Out << 'F';
4788 };
4789
4790 switch (Req->getKind()) {
4791 case Requirement::RK_Type: {
4792 const auto *TR = cast<concepts::TypeRequirement>(Req);
4793 if (TR->isSubstitutionFailure())
4794 return HandleSubstitutionFailure(
4795 TR->getSubstitutionDiagnostic()->DiagLoc);
4796
4797 Out << 'T';
4798 mangleType(TR->getType()->getType());
4799 break;
4800 }
4801
4802 case Requirement::RK_Simple:
4803 case Requirement::RK_Compound: {
4804 const auto *ER = cast<concepts::ExprRequirement>(Req);
4805 if (ER->isExprSubstitutionFailure())
4806 return HandleSubstitutionFailure(
4807 ER->getExprSubstitutionDiagnostic()->DiagLoc);
4808
4809 Out << 'X';
4810 mangleExpression(ER->getExpr());
4811
4812 if (ER->hasNoexceptRequirement())
4813 Out << 'N';
4814
4815 if (!ER->getReturnTypeRequirement().isEmpty()) {
4816 if (ER->getReturnTypeRequirement().isSubstitutionFailure())
4817 return HandleSubstitutionFailure(ER->getReturnTypeRequirement()
4818 .getSubstitutionDiagnostic()
4819 ->DiagLoc);
4820
4821 Out << 'R';
4822 mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());
4823 }
4824 break;
4825 }
4826
4827 case Requirement::RK_Nested:
4828 const auto *NR = cast<concepts::NestedRequirement>(Req);
4829 if (NR->hasInvalidConstraint()) {
4830 // FIXME: NestedRequirement should track the location of its requires
4831 // keyword.
4832 return HandleSubstitutionFailure(RequiresExprLoc);
4833 }
4834
4835 Out << 'Q';
4836 mangleExpression(NR->getConstraintExpr());
4837 break;
4838 }
4839}
4840
4841void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4842 bool AsTemplateArg) {
4843 // <expression> ::= <unary operator-name> <expression>
4844 // ::= <binary operator-name> <expression> <expression>
4845 // ::= <trinary operator-name> <expression> <expression> <expression>
4846 // ::= cv <type> expression # conversion with one argument
4847 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4848 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
4849 // ::= sc <type> <expression> # static_cast<type> (expression)
4850 // ::= cc <type> <expression> # const_cast<type> (expression)
4851 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4852 // ::= st <type> # sizeof (a type)
4853 // ::= at <type> # alignof (a type)
4854 // ::= <template-param>
4855 // ::= <function-param>
4856 // ::= fpT # 'this' expression (part of <function-param>)
4857 // ::= sr <type> <unqualified-name> # dependent name
4858 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
4859 // ::= ds <expression> <expression> # expr.*expr
4860 // ::= sZ <template-param> # size of a parameter pack
4861 // ::= sZ <function-param> # size of a function parameter pack
4862 // ::= u <source-name> <template-arg>* E # vendor extended expression
4863 // ::= <expr-primary>
4864 // <expr-primary> ::= L <type> <value number> E # integer literal
4865 // ::= L <type> <value float> E # floating literal
4866 // ::= L <type> <string type> E # string literal
4867 // ::= L <nullptr type> E # nullptr literal "LDnE"
4868 // ::= L <pointer type> 0 E # null pointer template argument
4869 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
4870 // ::= L <mangled-name> E # external name
4871 QualType ImplicitlyConvertedToType;
4872
4873 // A top-level expression that's not <expr-primary> needs to be wrapped in
4874 // X...E in a template arg.
4875 bool IsPrimaryExpr = true;
4876 auto NotPrimaryExpr = [&] {
4877 if (AsTemplateArg && IsPrimaryExpr)
4878 Out << 'X';
4879 IsPrimaryExpr = false;
4880 };
4881
4882 auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4883 switch (D->getKind()) {
4884 default:
4885 // <expr-primary> ::= L <mangled-name> E # external name
4886 Out << 'L';
4887 mangle(D);
4888 Out << 'E';
4889 break;
4890
4891 case Decl::ParmVar:
4892 NotPrimaryExpr();
4893 mangleFunctionParam(cast<ParmVarDecl>(D));
4894 break;
4895
4896 case Decl::EnumConstant: {
4897 // <expr-primary>
4898 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4899 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4900 break;
4901 }
4902
4903 case Decl::NonTypeTemplateParm:
4904 NotPrimaryExpr();
4905 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4906 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4907 break;
4908 }
4909 };
4910
4911 // 'goto recurse' is used when handling a simple "unwrapping" node which
4912 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4913 // to be preserved.
4914recurse:
4915 switch (E->getStmtClass()) {
4916 case Expr::NoStmtClass:
4917#define ABSTRACT_STMT(Type)
4918#define EXPR(Type, Base)
4919#define STMT(Type, Base) \
4920 case Expr::Type##Class:
4921#include "clang/AST/StmtNodes.inc"
4922 // fallthrough
4923
4924 // These all can only appear in local or variable-initialization
4925 // contexts and so should never appear in a mangling.
4926 case Expr::AddrLabelExprClass:
4927 case Expr::DesignatedInitUpdateExprClass:
4928 case Expr::ImplicitValueInitExprClass:
4929 case Expr::ArrayInitLoopExprClass:
4930 case Expr::ArrayInitIndexExprClass:
4931 case Expr::NoInitExprClass:
4932 case Expr::ParenListExprClass:
4933 case Expr::MSPropertyRefExprClass:
4934 case Expr::MSPropertySubscriptExprClass:
4935 case Expr::RecoveryExprClass:
4936 case Expr::ArraySectionExprClass:
4937 case Expr::OMPArrayShapingExprClass:
4938 case Expr::OMPIteratorExprClass:
4939 case Expr::CXXInheritedCtorInitExprClass:
4940 case Expr::CXXParenListInitExprClass:
4941 case Expr::PackIndexingExprClass:
4942 llvm_unreachable("unexpected statement kind");
4943
4944 case Expr::ConstantExprClass:
4945 E = cast<ConstantExpr>(E)->getSubExpr();
4946 goto recurse;
4947
4948 // FIXME: invent manglings for all these.
4949 case Expr::BlockExprClass:
4950 case Expr::ChooseExprClass:
4951 case Expr::CompoundLiteralExprClass:
4952 case Expr::ExtVectorElementExprClass:
4953 case Expr::GenericSelectionExprClass:
4954 case Expr::ObjCEncodeExprClass:
4955 case Expr::ObjCIsaExprClass:
4956 case Expr::ObjCIvarRefExprClass:
4957 case Expr::ObjCMessageExprClass:
4958 case Expr::ObjCPropertyRefExprClass:
4959 case Expr::ObjCProtocolExprClass:
4960 case Expr::ObjCSelectorExprClass:
4961 case Expr::ObjCStringLiteralClass:
4962 case Expr::ObjCBoxedExprClass:
4963 case Expr::ObjCArrayLiteralClass:
4964 case Expr::ObjCDictionaryLiteralClass:
4965 case Expr::ObjCSubscriptRefExprClass:
4966 case Expr::ObjCIndirectCopyRestoreExprClass:
4967 case Expr::ObjCAvailabilityCheckExprClass:
4968 case Expr::OffsetOfExprClass:
4969 case Expr::PredefinedExprClass:
4970 case Expr::ShuffleVectorExprClass:
4971 case Expr::ConvertVectorExprClass:
4972 case Expr::StmtExprClass:
4973 case Expr::ArrayTypeTraitExprClass:
4974 case Expr::ExpressionTraitExprClass:
4975 case Expr::VAArgExprClass:
4976 case Expr::CUDAKernelCallExprClass:
4977 case Expr::AsTypeExprClass:
4978 case Expr::PseudoObjectExprClass:
4979 case Expr::AtomicExprClass:
4980 case Expr::SourceLocExprClass:
4981 case Expr::EmbedExprClass:
4982 case Expr::BuiltinBitCastExprClass: {
4983 NotPrimaryExpr();
4984 if (!NullOut) {
4985 // As bad as this diagnostic is, it's better than crashing.
4986 DiagnosticsEngine &Diags = Context.getDiags();
4987 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4988 "cannot yet mangle expression type %0");
4989 Diags.Report(E->getExprLoc(), DiagID)
4990 << E->getStmtClassName() << E->getSourceRange();
4991 return;
4992 }
4993 break;
4994 }
4995
4996 case Expr::CXXUuidofExprClass: {
4997 NotPrimaryExpr();
4998 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4999 // As of clang 12, uuidof uses the vendor extended expression
5000 // mangling. Previously, it used a special-cased nonstandard extension.
5001 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
5002 Out << "u8__uuidof";
5003 if (UE->isTypeOperand())
5004 mangleType(UE->getTypeOperand(Context.getASTContext()));
5005 else
5006 mangleTemplateArgExpr(UE->getExprOperand());
5007 Out << 'E';
5008 } else {
5009 if (UE->isTypeOperand()) {
5010 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
5011 Out << "u8__uuidoft";
5012 mangleType(UuidT);
5013 } else {
5014 Expr *UuidExp = UE->getExprOperand();
5015 Out << "u8__uuidofz";
5016 mangleExpression(UuidExp);
5017 }
5018 }
5019 break;
5020 }
5021
5022 // Even gcc-4.5 doesn't mangle this.
5023 case Expr::BinaryConditionalOperatorClass: {
5024 NotPrimaryExpr();
5025 DiagnosticsEngine &Diags = Context.getDiags();
5026 unsigned DiagID =
5028 "?: operator with omitted middle operand cannot be mangled");
5029 Diags.Report(E->getExprLoc(), DiagID)
5030 << E->getStmtClassName() << E->getSourceRange();
5031 return;
5032 }
5033
5034 // These are used for internal purposes and cannot be meaningfully mangled.
5035 case Expr::OpaqueValueExprClass:
5036 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
5037
5038 case Expr::InitListExprClass: {
5039 NotPrimaryExpr();
5040 Out << "il";
5041 mangleInitListElements(cast<InitListExpr>(E));
5042 Out << "E";
5043 break;
5044 }
5045
5046 case Expr::DesignatedInitExprClass: {
5047 NotPrimaryExpr();
5048 auto *DIE = cast<DesignatedInitExpr>(E);
5049 for (const auto &Designator : DIE->designators()) {
5050 if (Designator.isFieldDesignator()) {
5051 Out << "di";
5052 mangleSourceName(Designator.getFieldName());
5053 } else if (Designator.isArrayDesignator()) {
5054 Out << "dx";
5055 mangleExpression(DIE->getArrayIndex(Designator));
5056 } else {
5057 assert(Designator.isArrayRangeDesignator() &&
5058 "unknown designator kind");
5059 Out << "dX";
5060 mangleExpression(DIE->getArrayRangeStart(Designator));
5061 mangleExpression(DIE->getArrayRangeEnd(Designator));
5062 }
5063 }
5064 mangleExpression(DIE->getInit());
5065 break;
5066 }
5067
5068 case Expr::CXXDefaultArgExprClass:
5069 E = cast<CXXDefaultArgExpr>(E)->getExpr();
5070 goto recurse;
5071
5072 case Expr::CXXDefaultInitExprClass:
5073 E = cast<CXXDefaultInitExpr>(E)->getExpr();
5074 goto recurse;
5075
5076 case Expr::CXXStdInitializerListExprClass:
5077 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
5078 goto recurse;
5079
5080 case Expr::SubstNonTypeTemplateParmExprClass: {
5081 // Mangle a substituted parameter the same way we mangle the template
5082 // argument.
5083 auto *SNTTPE = cast<SubstNonTypeTemplateParmExpr>(E);
5084 if (auto *CE = dyn_cast<ConstantExpr>(SNTTPE->getReplacement())) {
5085 // Pull out the constant value and mangle it as a template argument.
5086 QualType ParamType = SNTTPE->getParameterType(Context.getASTContext());
5087 assert(CE->hasAPValueResult() && "expected the NTTP to have an APValue");
5088 mangleValueInTemplateArg(ParamType, CE->getAPValueResult(), false,
5089 /*NeedExactType=*/true);
5090 break;
5091 }
5092 // The remaining cases all happen to be substituted with expressions that
5093 // mangle the same as a corresponding template argument anyway.
5094 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
5095 goto recurse;
5096 }
5097
5098 case Expr::UserDefinedLiteralClass:
5099 // We follow g++'s approach of mangling a UDL as a call to the literal
5100 // operator.
5101 case Expr::CXXMemberCallExprClass: // fallthrough
5102 case Expr::CallExprClass: {
5103 NotPrimaryExpr();
5104 const CallExpr *CE = cast<CallExpr>(E);
5105
5106 // <expression> ::= cp <simple-id> <expression>* E
5107 // We use this mangling only when the call would use ADL except
5108 // for being parenthesized. Per discussion with David
5109 // Vandervoorde, 2011.04.25.
5110 if (isParenthesizedADLCallee(CE)) {
5111 Out << "cp";
5112 // The callee here is a parenthesized UnresolvedLookupExpr with
5113 // no qualifier and should always get mangled as a <simple-id>
5114 // anyway.
5115
5116 // <expression> ::= cl <expression>* E
5117 } else {
5118 Out << "cl";
5119 }
5120
5121 unsigned CallArity = CE->getNumArgs();
5122 for (const Expr *Arg : CE->arguments())
5123 if (isa<PackExpansionExpr>(Arg))
5124 CallArity = UnknownArity;
5125
5126 mangleExpression(CE->getCallee(), CallArity);
5127 for (const Expr *Arg : CE->arguments())
5128 mangleExpression(Arg);
5129 Out << 'E';
5130 break;
5131 }
5132
5133 case Expr::CXXNewExprClass: {
5134 NotPrimaryExpr();
5135 const CXXNewExpr *New = cast<CXXNewExpr>(E);
5136 if (New->isGlobalNew()) Out << "gs";
5137 Out << (New->isArray() ? "na" : "nw");
5138 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
5139 E = New->placement_arg_end(); I != E; ++I)
5140 mangleExpression(*I);
5141 Out << '_';
5142 mangleType(New->getAllocatedType());
5143 if (New->hasInitializer()) {
5144 if (New->getInitializationStyle() == CXXNewInitializationStyle::Braces)
5145 Out << "il";
5146 else
5147 Out << "pi";
5148 const Expr *Init = New->getInitializer();
5149 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
5150 // Directly inline the initializers.
5151 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
5152 E = CCE->arg_end();
5153 I != E; ++I)
5154 mangleExpression(*I);
5155 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
5156 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
5157 mangleExpression(PLE->getExpr(i));
5158 } else if (New->getInitializationStyle() ==
5159 CXXNewInitializationStyle::Braces &&
5161 // Only take InitListExprs apart for list-initialization.
5162 mangleInitListElements(cast<InitListExpr>(Init));
5163 } else
5164 mangleExpression(Init);
5165 }
5166 Out << 'E';
5167 break;
5168 }
5169
5170 case Expr::CXXPseudoDestructorExprClass: {
5171 NotPrimaryExpr();
5172 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
5173 if (const Expr *Base = PDE->getBase())
5174 mangleMemberExprBase(Base, PDE->isArrow());
5175 NestedNameSpecifier Qualifier = PDE->getQualifier();
5176 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
5177 if (Qualifier) {
5178 mangleUnresolvedPrefix(Qualifier,
5179 /*recursive=*/true);
5180 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
5181 Out << 'E';
5182 } else {
5183 Out << "sr";
5184 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
5185 Out << 'E';
5186 }
5187 } else if (Qualifier) {
5188 mangleUnresolvedPrefix(Qualifier);
5189 }
5190 // <base-unresolved-name> ::= dn <destructor-name>
5191 Out << "dn";
5192 QualType DestroyedType = PDE->getDestroyedType();
5193 mangleUnresolvedTypeOrSimpleId(DestroyedType);
5194 break;
5195 }
5196
5197 case Expr::MemberExprClass: {
5198 NotPrimaryExpr();
5199 const MemberExpr *ME = cast<MemberExpr>(E);
5200 mangleMemberExpr(ME->getBase(), ME->isArrow(),
5201 ME->getQualifier(), nullptr,
5202 ME->getMemberDecl()->getDeclName(),
5204 Arity);
5205 break;
5206 }
5207
5208 case Expr::UnresolvedMemberExprClass: {
5209 NotPrimaryExpr();
5210 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
5211 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
5212 ME->isArrow(), ME->getQualifier(), nullptr,
5213 ME->getMemberName(),
5215 Arity);
5216 break;
5217 }
5218
5219 case Expr::CXXDependentScopeMemberExprClass: {
5220 NotPrimaryExpr();
5221 const CXXDependentScopeMemberExpr *ME
5223 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
5224 ME->isArrow(), ME->getQualifier(),
5226 ME->getMember(),
5228 Arity);
5229 break;
5230 }
5231
5232 case Expr::UnresolvedLookupExprClass: {
5233 NotPrimaryExpr();
5234 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
5235 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
5236 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
5237 Arity);
5238 break;
5239 }
5240
5241 case Expr::CXXUnresolvedConstructExprClass: {
5242 NotPrimaryExpr();
5243 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
5244 unsigned N = CE->getNumArgs();
5245
5246 if (CE->isListInitialization()) {
5247 assert(N == 1 && "unexpected form for list initialization");
5248 auto *IL = cast<InitListExpr>(CE->getArg(0));
5249 Out << "tl";
5250 mangleType(CE->getType());
5251 mangleInitListElements(IL);
5252 Out << "E";
5253 break;
5254 }
5255
5256 Out << "cv";
5257 mangleType(CE->getType());
5258 if (N != 1) Out << '_';
5259 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
5260 if (N != 1) Out << 'E';
5261 break;
5262 }
5263
5264 case Expr::CXXConstructExprClass: {
5265 // An implicit cast is silent, thus may contain <expr-primary>.
5266 const auto *CE = cast<CXXConstructExpr>(E);
5267 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
5268 assert(
5269 CE->getNumArgs() >= 1 &&
5270 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
5271 "implicit CXXConstructExpr must have one argument");
5272 E = cast<CXXConstructExpr>(E)->getArg(0);
5273 goto recurse;
5274 }
5275 NotPrimaryExpr();
5276 Out << "il";
5277 for (auto *E : CE->arguments())
5278 mangleExpression(E);
5279 Out << "E";
5280 break;
5281 }
5282
5283 case Expr::CXXTemporaryObjectExprClass: {
5284 NotPrimaryExpr();
5285 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
5286 unsigned N = CE->getNumArgs();
5287 bool List = CE->isListInitialization();
5288
5289 if (List)
5290 Out << "tl";
5291 else
5292 Out << "cv";
5293 mangleType(CE->getType());
5294 if (!List && N != 1)
5295 Out << '_';
5296 if (CE->isStdInitListInitialization()) {
5297 // We implicitly created a std::initializer_list<T> for the first argument
5298 // of a constructor of type U in an expression of the form U{a, b, c}.
5299 // Strip all the semantic gunk off the initializer list.
5300 auto *SILE =
5302 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
5303 mangleInitListElements(ILE);
5304 } else {
5305 for (auto *E : CE->arguments())
5306 mangleExpression(E);
5307 }
5308 if (List || N != 1)
5309 Out << 'E';
5310 break;
5311 }
5312
5313 case Expr::CXXScalarValueInitExprClass:
5314 NotPrimaryExpr();
5315 Out << "cv";
5316 mangleType(E->getType());
5317 Out << "_E";
5318 break;
5319
5320 case Expr::CXXNoexceptExprClass:
5321 NotPrimaryExpr();
5322 Out << "nx";
5323 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
5324 break;
5325
5326 case Expr::UnaryExprOrTypeTraitExprClass: {
5327 // Non-instantiation-dependent traits are an <expr-primary> integer literal.
5328 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
5329
5330 if (!SAE->isInstantiationDependent()) {
5331 // Itanium C++ ABI:
5332 // If the operand of a sizeof or alignof operator is not
5333 // instantiation-dependent it is encoded as an integer literal
5334 // reflecting the result of the operator.
5335 //
5336 // If the result of the operator is implicitly converted to a known
5337 // integer type, that type is used for the literal; otherwise, the type
5338 // of std::size_t or std::ptrdiff_t is used.
5339 //
5340 // FIXME: We still include the operand in the profile in this case. This
5341 // can lead to mangling collisions between function templates that we
5342 // consider to be different.
5343 QualType T = (ImplicitlyConvertedToType.isNull() ||
5344 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
5345 : ImplicitlyConvertedToType;
5346 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
5347 mangleIntegerLiteral(T, V);
5348 break;
5349 }
5350
5351 NotPrimaryExpr(); // But otherwise, they are not.
5352
5353 auto MangleAlignofSizeofArg = [&] {
5354 if (SAE->isArgumentType()) {
5355 Out << 't';
5356 mangleType(SAE->getArgumentType());
5357 } else {
5358 Out << 'z';
5359 mangleExpression(SAE->getArgumentExpr());
5360 }
5361 };
5362
5363 auto MangleExtensionBuiltin = [&](const UnaryExprOrTypeTraitExpr *E,
5364 StringRef Name = {}) {
5365 if (Name.empty())
5366 Name = getTraitSpelling(E->getKind());
5367 mangleVendorType(Name);
5368 if (SAE->isArgumentType())
5369 mangleType(SAE->getArgumentType());
5370 else
5371 mangleTemplateArgExpr(SAE->getArgumentExpr());
5372 Out << 'E';
5373 };
5374
5375 switch (SAE->getKind()) {
5376 case UETT_SizeOf:
5377 Out << 's';
5378 MangleAlignofSizeofArg();
5379 break;
5380 case UETT_PreferredAlignOf:
5381 // As of clang 12, we mangle __alignof__ differently than alignof. (They
5382 // have acted differently since Clang 8, but were previously mangled the
5383 // same.)
5384 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
5385 MangleExtensionBuiltin(SAE, "__alignof__");
5386 break;
5387 }
5388 [[fallthrough]];
5389 case UETT_AlignOf:
5390 Out << 'a';
5391 MangleAlignofSizeofArg();
5392 break;
5393
5394 case UETT_CountOf:
5395 case UETT_VectorElements:
5396 case UETT_OpenMPRequiredSimdAlign:
5397 case UETT_VecStep:
5398 case UETT_PtrAuthTypeDiscriminator:
5399 case UETT_DataSizeOf: {
5400 DiagnosticsEngine &Diags = Context.getDiags();
5401 unsigned DiagID = Diags.getCustomDiagID(
5402 DiagnosticsEngine::Error, "cannot yet mangle %0 expression");
5403 Diags.Report(E->getExprLoc(), DiagID) << getTraitSpelling(SAE->getKind());
5404 return;
5405 }
5406 }
5407 break;
5408 }
5409
5410 case Expr::TypeTraitExprClass: {
5411 // <expression> ::= u <source-name> <template-arg>* E # vendor extension
5412 const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);
5413 NotPrimaryExpr();
5414 llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());
5415 mangleVendorType(Spelling);
5416 for (TypeSourceInfo *TSI : TTE->getArgs()) {
5417 mangleType(TSI->getType());
5418 }
5419 Out << 'E';
5420 break;
5421 }
5422
5423 case Expr::CXXThrowExprClass: {
5424 NotPrimaryExpr();
5425 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
5426 // <expression> ::= tw <expression> # throw expression
5427 // ::= tr # rethrow
5428 if (TE->getSubExpr()) {
5429 Out << "tw";
5430 mangleExpression(TE->getSubExpr());
5431 } else {
5432 Out << "tr";
5433 }
5434 break;
5435 }
5436
5437 case Expr::CXXTypeidExprClass: {
5438 NotPrimaryExpr();
5439 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
5440 // <expression> ::= ti <type> # typeid (type)
5441 // ::= te <expression> # typeid (expression)
5442 if (TIE->isTypeOperand()) {
5443 Out << "ti";
5444 mangleType(TIE->getTypeOperand(Context.getASTContext()));
5445 } else {
5446 Out << "te";
5447 mangleExpression(TIE->getExprOperand());
5448 }
5449 break;
5450 }
5451
5452 case Expr::CXXDeleteExprClass: {
5453 NotPrimaryExpr();
5454 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
5455 // <expression> ::= [gs] dl <expression> # [::] delete expr
5456 // ::= [gs] da <expression> # [::] delete [] expr
5457 if (DE->isGlobalDelete()) Out << "gs";
5458 Out << (DE->isArrayForm() ? "da" : "dl");
5459 mangleExpression(DE->getArgument());
5460 break;
5461 }
5462
5463 case Expr::UnaryOperatorClass: {
5464 NotPrimaryExpr();
5465 const UnaryOperator *UO = cast<UnaryOperator>(E);
5466 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
5467 /*Arity=*/1);
5468 mangleExpression(UO->getSubExpr());
5469 break;
5470 }
5471
5472 case Expr::ArraySubscriptExprClass: {
5473 NotPrimaryExpr();
5474 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
5475
5476 // Array subscript is treated as a syntactically weird form of
5477 // binary operator.
5478 Out << "ix";
5479 mangleExpression(AE->getLHS());
5480 mangleExpression(AE->getRHS());
5481 break;
5482 }
5483
5484 case Expr::MatrixSubscriptExprClass: {
5485 NotPrimaryExpr();
5486 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
5487 Out << "ixix";
5488 mangleExpression(ME->getBase());
5489 mangleExpression(ME->getRowIdx());
5490 mangleExpression(ME->getColumnIdx());
5491 break;
5492 }
5493
5494 case Expr::CompoundAssignOperatorClass: // fallthrough
5495 case Expr::BinaryOperatorClass: {
5496 NotPrimaryExpr();
5497 const BinaryOperator *BO = cast<BinaryOperator>(E);
5498 if (BO->getOpcode() == BO_PtrMemD)
5499 Out << "ds";
5500 else
5501 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
5502 /*Arity=*/2);
5503 mangleExpression(BO->getLHS());
5504 mangleExpression(BO->getRHS());
5505 break;
5506 }
5507
5508 case Expr::CXXRewrittenBinaryOperatorClass: {
5509 NotPrimaryExpr();
5510 // The mangled form represents the original syntax.
5511 CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
5512 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
5513 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
5514 /*Arity=*/2);
5515 mangleExpression(Decomposed.LHS);
5516 mangleExpression(Decomposed.RHS);
5517 break;
5518 }
5519
5520 case Expr::ConditionalOperatorClass: {
5521 NotPrimaryExpr();
5522 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
5523 mangleOperatorName(OO_Conditional, /*Arity=*/3);
5524 mangleExpression(CO->getCond());
5525 mangleExpression(CO->getLHS(), Arity);
5526 mangleExpression(CO->getRHS(), Arity);
5527 break;
5528 }
5529
5530 case Expr::ImplicitCastExprClass: {
5531 ImplicitlyConvertedToType = E->getType();
5532 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5533 goto recurse;
5534 }
5535
5536 case Expr::ObjCBridgedCastExprClass: {
5537 NotPrimaryExpr();
5538 // Mangle ownership casts as a vendor extended operator __bridge,
5539 // __bridge_transfer, or __bridge_retain.
5540 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
5541 Out << "v1U" << Kind.size() << Kind;
5542 mangleCastExpression(E, "cv");
5543 break;
5544 }
5545
5546 case Expr::CStyleCastExprClass:
5547 NotPrimaryExpr();
5548 mangleCastExpression(E, "cv");
5549 break;
5550
5551 case Expr::CXXFunctionalCastExprClass: {
5552 NotPrimaryExpr();
5553 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
5554 // FIXME: Add isImplicit to CXXConstructExpr.
5555 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
5556 if (CCE->getParenOrBraceRange().isInvalid())
5557 Sub = CCE->getArg(0)->IgnoreImplicit();
5558 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
5559 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
5560 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
5561 Out << "tl";
5562 mangleType(E->getType());
5563 mangleInitListElements(IL);
5564 Out << "E";
5565 } else {
5566 mangleCastExpression(E, "cv");
5567 }
5568 break;
5569 }
5570
5571 case Expr::CXXStaticCastExprClass:
5572 NotPrimaryExpr();
5573 mangleCastExpression(E, "sc");
5574 break;
5575 case Expr::CXXDynamicCastExprClass:
5576 NotPrimaryExpr();
5577 mangleCastExpression(E, "dc");
5578 break;
5579 case Expr::CXXReinterpretCastExprClass:
5580 NotPrimaryExpr();
5581 mangleCastExpression(E, "rc");
5582 break;
5583 case Expr::CXXConstCastExprClass:
5584 NotPrimaryExpr();
5585 mangleCastExpression(E, "cc");
5586 break;
5587 case Expr::CXXAddrspaceCastExprClass:
5588 NotPrimaryExpr();
5589 mangleCastExpression(E, "ac");
5590 break;
5591
5592 case Expr::CXXOperatorCallExprClass: {
5593 NotPrimaryExpr();
5594 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
5595 unsigned NumArgs = CE->getNumArgs();
5596 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
5597 // (the enclosing MemberExpr covers the syntactic portion).
5598 if (CE->getOperator() != OO_Arrow)
5599 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
5600 // Mangle the arguments.
5601 for (unsigned i = 0; i != NumArgs; ++i)
5602 mangleExpression(CE->getArg(i));
5603 break;
5604 }
5605
5606 case Expr::ParenExprClass:
5607 E = cast<ParenExpr>(E)->getSubExpr();
5608 goto recurse;
5609
5610 case Expr::ConceptSpecializationExprClass: {
5611 auto *CSE = cast<ConceptSpecializationExpr>(E);
5612 if (isCompatibleWith(LangOptions::ClangABI::Ver17)) {
5613 // Clang 17 and before mangled concept-ids as if they resolved to an
5614 // entity, meaning that references to enclosing template arguments don't
5615 // work.
5616 Out << "L_Z";
5617 mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
5618 Out << 'E';
5619 break;
5620 }
5621 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5622 NotPrimaryExpr();
5623 mangleUnresolvedName(
5624 CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
5625 CSE->getConceptNameInfo().getName(),
5626 CSE->getTemplateArgsAsWritten()->getTemplateArgs(),
5627 CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());
5628 break;
5629 }
5630
5631 case Expr::RequiresExprClass: {
5632 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5633 auto *RE = cast<RequiresExpr>(E);
5634 // This is a primary-expression in the C++ grammar, but does not have an
5635 // <expr-primary> mangling (starting with 'L').
5636 NotPrimaryExpr();
5637 if (RE->getLParenLoc().isValid()) {
5638 Out << "rQ";
5639 FunctionTypeDepthState saved = FunctionTypeDepth.push();
5640 if (RE->getLocalParameters().empty()) {
5641 Out << 'v';
5642 } else {
5643 for (ParmVarDecl *Param : RE->getLocalParameters()) {
5644 mangleType(Context.getASTContext().getSignatureParameterType(
5645 Param->getType()));
5646 }
5647 }
5648 Out << '_';
5649
5650 // The rest of the mangling is in the immediate scope of the parameters.
5651 FunctionTypeDepth.enterResultType();
5652 for (const concepts::Requirement *Req : RE->getRequirements())
5653 mangleRequirement(RE->getExprLoc(), Req);
5654 FunctionTypeDepth.pop(saved);
5655 Out << 'E';
5656 } else {
5657 Out << "rq";
5658 for (const concepts::Requirement *Req : RE->getRequirements())
5659 mangleRequirement(RE->getExprLoc(), Req);
5660 Out << 'E';
5661 }
5662 break;
5663 }
5664
5665 case Expr::DeclRefExprClass:
5666 // MangleDeclRefExpr helper handles primary-vs-nonprimary
5667 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
5668 break;
5669
5670 case Expr::SubstNonTypeTemplateParmPackExprClass:
5671 NotPrimaryExpr();
5672 // FIXME: not clear how to mangle this!
5673 // template <unsigned N...> class A {
5674 // template <class U...> void foo(U (&x)[N]...);
5675 // };
5676 Out << "_SUBSTPACK_";
5677 break;
5678
5679 case Expr::FunctionParmPackExprClass: {
5680 NotPrimaryExpr();
5681 // FIXME: not clear how to mangle this!
5682 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
5683 Out << "v110_SUBSTPACK";
5684 MangleDeclRefExpr(FPPE->getParameterPack());
5685 break;
5686 }
5687
5688 case Expr::DependentScopeDeclRefExprClass: {
5689 NotPrimaryExpr();
5690 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
5691 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
5692 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
5693 Arity);
5694 break;
5695 }
5696
5697 case Expr::CXXBindTemporaryExprClass:
5698 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
5699 goto recurse;
5700
5701 case Expr::ExprWithCleanupsClass:
5702 E = cast<ExprWithCleanups>(E)->getSubExpr();
5703 goto recurse;
5704
5705 case Expr::FloatingLiteralClass: {
5706 // <expr-primary>
5707 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
5708 mangleFloatLiteral(FL->getType(), FL->getValue());
5709 break;
5710 }
5711
5712 case Expr::FixedPointLiteralClass:
5713 // Currently unimplemented -- might be <expr-primary> in future?
5714 mangleFixedPointLiteral();
5715 break;
5716
5717 case Expr::CharacterLiteralClass:
5718 // <expr-primary>
5719 Out << 'L';
5720 mangleType(E->getType());
5721 Out << cast<CharacterLiteral>(E)->getValue();
5722 Out << 'E';
5723 break;
5724
5725 // FIXME. __objc_yes/__objc_no are mangled same as true/false
5726 case Expr::ObjCBoolLiteralExprClass:
5727 // <expr-primary>
5728 Out << "Lb";
5729 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5730 Out << 'E';
5731 break;
5732
5733 case Expr::CXXBoolLiteralExprClass:
5734 // <expr-primary>
5735 Out << "Lb";
5736 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5737 Out << 'E';
5738 break;
5739
5740 case Expr::IntegerLiteralClass: {
5741 // <expr-primary>
5742 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
5743 if (E->getType()->isSignedIntegerType())
5744 Value.setIsSigned(true);
5745 mangleIntegerLiteral(E->getType(), Value);
5746 break;
5747 }
5748
5749 case Expr::ImaginaryLiteralClass: {
5750 // <expr-primary>
5751 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
5752 // Mangle as if a complex literal.
5753 // Proposal from David Vandevoorde, 2010.06.30.
5754 Out << 'L';
5755 mangleType(E->getType());
5756 if (const FloatingLiteral *Imag =
5757 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
5758 // Mangle a floating-point zero of the appropriate type.
5759 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
5760 Out << '_';
5761 mangleFloat(Imag->getValue());
5762 } else {
5763 Out << "0_";
5764 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
5765 if (IE->getSubExpr()->getType()->isSignedIntegerType())
5766 Value.setIsSigned(true);
5767 mangleNumber(Value);
5768 }
5769 Out << 'E';
5770 break;
5771 }
5772
5773 case Expr::StringLiteralClass: {
5774 // <expr-primary>
5775 // Revised proposal from David Vandervoorde, 2010.07.15.
5776 Out << 'L';
5777 assert(isa<ConstantArrayType>(E->getType()));
5778 mangleType(E->getType());
5779 Out << 'E';
5780 break;
5781 }
5782
5783 case Expr::GNUNullExprClass:
5784 // <expr-primary>
5785 // Mangle as if an integer literal 0.
5786 mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
5787 break;
5788
5789 case Expr::CXXNullPtrLiteralExprClass: {
5790 // <expr-primary>
5791 Out << "LDnE";
5792 break;
5793 }
5794
5795 case Expr::LambdaExprClass: {
5796 // A lambda-expression can't appear in the signature of an
5797 // externally-visible declaration, so there's no standard mangling for
5798 // this, but mangling as a literal of the closure type seems reasonable.
5799 Out << "L";
5800 mangleType(Context.getASTContext().getCanonicalTagType(
5801 cast<LambdaExpr>(E)->getLambdaClass()));
5802 Out << "E";
5803 break;
5804 }
5805
5806 case Expr::PackExpansionExprClass:
5807 NotPrimaryExpr();
5808 Out << "sp";
5809 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
5810 break;
5811
5812 case Expr::SizeOfPackExprClass: {
5813 NotPrimaryExpr();
5814 auto *SPE = cast<SizeOfPackExpr>(E);
5815 if (SPE->isPartiallySubstituted()) {
5816 Out << "sP";
5817 for (const auto &A : SPE->getPartialArguments())
5818 mangleTemplateArg(A, false);
5819 Out << "E";
5820 break;
5821 }
5822
5823 Out << "sZ";
5824 const NamedDecl *Pack = SPE->getPack();
5825 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
5826 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
5827 else if (const NonTypeTemplateParmDecl *NTTP
5828 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
5829 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
5830 else if (const TemplateTemplateParmDecl *TempTP
5831 = dyn_cast<TemplateTemplateParmDecl>(Pack))
5832 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
5833 else
5834 mangleFunctionParam(cast<ParmVarDecl>(Pack));
5835 break;
5836 }
5837
5838 case Expr::MaterializeTemporaryExprClass:
5839 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5840 goto recurse;
5841
5842 case Expr::CXXFoldExprClass: {
5843 NotPrimaryExpr();
5844 auto *FE = cast<CXXFoldExpr>(E);
5845 if (FE->isLeftFold())
5846 Out << (FE->getInit() ? "fL" : "fl");
5847 else
5848 Out << (FE->getInit() ? "fR" : "fr");
5849
5850 if (FE->getOperator() == BO_PtrMemD)
5851 Out << "ds";
5852 else
5853 mangleOperatorName(
5854 BinaryOperator::getOverloadedOperator(FE->getOperator()),
5855 /*Arity=*/2);
5856
5857 if (FE->getLHS())
5858 mangleExpression(FE->getLHS());
5859 if (FE->getRHS())
5860 mangleExpression(FE->getRHS());
5861 break;
5862 }
5863
5864 case Expr::CXXThisExprClass:
5865 NotPrimaryExpr();
5866 Out << "fpT";
5867 break;
5868
5869 case Expr::CoawaitExprClass:
5870 // FIXME: Propose a non-vendor mangling.
5871 NotPrimaryExpr();
5872 Out << "v18co_await";
5873 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5874 break;
5875
5876 case Expr::DependentCoawaitExprClass:
5877 // FIXME: Propose a non-vendor mangling.
5878 NotPrimaryExpr();
5879 Out << "v18co_await";
5880 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
5881 break;
5882
5883 case Expr::CoyieldExprClass:
5884 // FIXME: Propose a non-vendor mangling.
5885 NotPrimaryExpr();
5886 Out << "v18co_yield";
5887 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5888 break;
5889 case Expr::SYCLUniqueStableNameExprClass: {
5890 const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
5891 NotPrimaryExpr();
5892
5893 Out << "u33__builtin_sycl_unique_stable_name";
5894 mangleType(USN->getTypeSourceInfo()->getType());
5895
5896 Out << "E";
5897 break;
5898 }
5899 case Expr::HLSLOutArgExprClass:
5900 llvm_unreachable(
5901 "cannot mangle hlsl temporary value; mangling wrong thing?");
5902 case Expr::OpenACCAsteriskSizeExprClass: {
5903 // We shouldn't ever be able to get here, but diagnose anyway.
5904 DiagnosticsEngine &Diags = Context.getDiags();
5905 unsigned DiagID = Diags.getCustomDiagID(
5907 "cannot yet mangle OpenACC Asterisk Size expression");
5908 Diags.Report(DiagID);
5909 return;
5910 }
5911 }
5912
5913 if (AsTemplateArg && !IsPrimaryExpr)
5914 Out << 'E';
5915}
5916
5917/// Mangle an expression which refers to a parameter variable.
5918///
5919/// <expression> ::= <function-param>
5920/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
5921/// <function-param> ::= fp <top-level CV-qualifiers>
5922/// <parameter-2 non-negative number> _ # L == 0, I > 0
5923/// <function-param> ::= fL <L-1 non-negative number>
5924/// p <top-level CV-qualifiers> _ # L > 0, I == 0
5925/// <function-param> ::= fL <L-1 non-negative number>
5926/// p <top-level CV-qualifiers>
5927/// <I-1 non-negative number> _ # L > 0, I > 0
5928///
5929/// L is the nesting depth of the parameter, defined as 1 if the
5930/// parameter comes from the innermost function prototype scope
5931/// enclosing the current context, 2 if from the next enclosing
5932/// function prototype scope, and so on, with one special case: if
5933/// we've processed the full parameter clause for the innermost
5934/// function type, then L is one less. This definition conveniently
5935/// makes it irrelevant whether a function's result type was written
5936/// trailing or leading, but is otherwise overly complicated; the
5937/// numbering was first designed without considering references to
5938/// parameter in locations other than return types, and then the
5939/// mangling had to be generalized without changing the existing
5940/// manglings.
5941///
5942/// I is the zero-based index of the parameter within its parameter
5943/// declaration clause. Note that the original ABI document describes
5944/// this using 1-based ordinals.
5945void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
5946 unsigned parmDepth = parm->getFunctionScopeDepth();
5947 unsigned parmIndex = parm->getFunctionScopeIndex();
5948
5949 // Compute 'L'.
5950 // parmDepth does not include the declaring function prototype.
5951 // FunctionTypeDepth does account for that.
5952 assert(parmDepth < FunctionTypeDepth.getDepth());
5953 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
5954 if (FunctionTypeDepth.isInResultType())
5955 nestingDepth--;
5956
5957 if (nestingDepth == 0) {
5958 Out << "fp";
5959 } else {
5960 Out << "fL" << (nestingDepth - 1) << 'p';
5961 }
5962
5963 // Top-level qualifiers. We don't have to worry about arrays here,
5964 // because parameters declared as arrays should already have been
5965 // transformed to have pointer type. FIXME: apparently these don't
5966 // get mangled if used as an rvalue of a known non-class type?
5967 assert(!parm->getType()->isArrayType()
5968 && "parameter's type is still an array type?");
5969
5970 if (const DependentAddressSpaceType *DAST =
5971 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
5972 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
5973 } else {
5974 mangleQualifiers(parm->getType().getQualifiers());
5975 }
5976
5977 // Parameter index.
5978 if (parmIndex != 0) {
5979 Out << (parmIndex - 1);
5980 }
5981 Out << '_';
5982}
5983
5984void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
5985 const CXXRecordDecl *InheritedFrom) {
5986 // <ctor-dtor-name> ::= C1 # complete object constructor
5987 // ::= C2 # base object constructor
5988 // ::= CI1 <type> # complete inheriting constructor
5989 // ::= CI2 <type> # base inheriting constructor
5990 //
5991 // In addition, C5 is a comdat name with C1 and C2 in it.
5992 // C4 represents a ctor declaration and is used by debuggers to look up
5993 // the various ctor variants.
5994 Out << 'C';
5995 if (InheritedFrom)
5996 Out << 'I';
5997 switch (T) {
5998 case Ctor_Complete:
5999 Out << '1';
6000 break;
6001 case Ctor_Base:
6002 Out << '2';
6003 break;
6004 case Ctor_Unified:
6005 Out << '4';
6006 break;
6007 case Ctor_Comdat:
6008 Out << '5';
6009 break;
6012 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
6013 }
6014 if (InheritedFrom)
6015 mangleName(InheritedFrom);
6016}
6017
6018void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
6019 // <ctor-dtor-name> ::= D0 # deleting destructor
6020 // ::= D1 # complete object destructor
6021 // ::= D2 # base object destructor
6022 //
6023 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
6024 // D4 represents a dtor declaration and is used by debuggers to look up
6025 // the various dtor variants.
6026 switch (T) {
6027 case Dtor_Deleting:
6028 Out << "D0";
6029 break;
6030 case Dtor_Complete:
6031 Out << "D1";
6032 break;
6033 case Dtor_Base:
6034 Out << "D2";
6035 break;
6036 case Dtor_Unified:
6037 Out << "D4";
6038 break;
6039 case Dtor_Comdat:
6040 Out << "D5";
6041 break;
6042 }
6043}
6044
6045// Helper to provide ancillary information on a template used to mangle its
6046// arguments.
6048 const CXXNameMangler &Mangler;
6052
6054 : Mangler(Mangler) {
6055 if (TemplateDecl *TD = TN.getAsTemplateDecl())
6056 ResolvedTemplate = TD;
6057 }
6058
6059 /// Information about how to mangle a template argument.
6060 struct Info {
6061 /// Do we need to mangle the template argument with an exactly correct type?
6063 /// If we need to prefix the mangling with a mangling of the template
6064 /// parameter, the corresponding parameter.
6066 };
6067
6068 /// Determine whether the resolved template might be overloaded on its
6069 /// template parameter list. If so, the mangling needs to include enough
6070 /// information to reconstruct the template parameter list.
6072 // Function templates are generally overloadable. As a special case, a
6073 // member function template of a generic lambda is not overloadable.
6074 if (auto *FTD = dyn_cast_or_null<FunctionTemplateDecl>(ResolvedTemplate)) {
6075 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
6076 if (!RD || !RD->isGenericLambda())
6077 return true;
6078 }
6079
6080 // All other templates are not overloadable. Partial specializations would
6081 // be, but we never mangle them.
6082 return false;
6083 }
6084
6085 /// Determine whether we need to prefix this <template-arg> mangling with a
6086 /// <template-param-decl>. This happens if the natural template parameter for
6087 /// the argument mangling is not the same as the actual template parameter.
6089 const TemplateArgument &Arg) {
6090 // For a template type parameter, the natural parameter is 'typename T'.
6091 // The actual parameter might be constrained.
6092 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
6093 return TTP->hasTypeConstraint();
6094
6095 if (Arg.getKind() == TemplateArgument::Pack) {
6096 // For an empty pack, the natural parameter is `typename...`.
6097 if (Arg.pack_size() == 0)
6098 return true;
6099
6100 // For any other pack, we use the first argument to determine the natural
6101 // template parameter.
6102 return needToMangleTemplateParam(Param, *Arg.pack_begin());
6103 }
6104
6105 // For a non-type template parameter, the natural parameter is `T V` (for a
6106 // prvalue argument) or `T &V` (for a glvalue argument), where `T` is the
6107 // type of the argument, which we require to exactly match. If the actual
6108 // parameter has a deduced or instantiation-dependent type, it is not
6109 // equivalent to the natural parameter.
6110 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
6111 return NTTP->getType()->isInstantiationDependentType() ||
6112 NTTP->getType()->getContainedDeducedType();
6113
6114 // For a template template parameter, the template-head might differ from
6115 // that of the template.
6116 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6117 TemplateName ArgTemplateName = Arg.getAsTemplateOrTemplatePattern();
6118 assert(!ArgTemplateName.getTemplateDeclAndDefaultArgs().second &&
6119 "A DeducedTemplateName shouldn't escape partial ordering");
6120 const TemplateDecl *ArgTemplate =
6121 ArgTemplateName.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6122 if (!ArgTemplate)
6123 return true;
6124
6125 // Mangle the template parameter list of the parameter and argument to see
6126 // if they are the same. We can't use Profile for this, because it can't
6127 // model the depth difference between parameter and argument and might not
6128 // necessarily have the same definition of "identical" that we use here --
6129 // that is, same mangling.
6130 auto MangleTemplateParamListToString =
6131 [&](SmallVectorImpl<char> &Buffer, const TemplateParameterList *Params,
6132 unsigned DepthOffset) {
6133 llvm::raw_svector_ostream Stream(Buffer);
6134 CXXNameMangler(Mangler.Context, Stream,
6135 WithTemplateDepthOffset{DepthOffset})
6136 .mangleTemplateParameterList(Params);
6137 };
6138 llvm::SmallString<128> ParamTemplateHead, ArgTemplateHead;
6139 MangleTemplateParamListToString(ParamTemplateHead,
6140 TTP->getTemplateParameters(), 0);
6141 // Add the depth of the parameter's template parameter list to all
6142 // parameters appearing in the argument to make the indexes line up
6143 // properly.
6144 MangleTemplateParamListToString(ArgTemplateHead,
6145 ArgTemplate->getTemplateParameters(),
6146 TTP->getTemplateParameters()->getDepth());
6147 return ParamTemplateHead != ArgTemplateHead;
6148 }
6149
6150 /// Determine information about how this template argument should be mangled.
6151 /// This should be called exactly once for each parameter / argument pair, in
6152 /// order.
6154 // We need correct types when the template-name is unresolved or when it
6155 // names a template that is able to be overloaded.
6157 return {true, nullptr};
6158
6159 // Move to the next parameter.
6160 const NamedDecl *Param = UnresolvedExpandedPack;
6161 if (!Param) {
6162 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
6163 "no parameter for argument");
6164 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
6165
6166 // If we reach a parameter pack whose argument isn't in pack form, that
6167 // means Sema couldn't or didn't figure out which arguments belonged to
6168 // it, because it contains a pack expansion or because Sema bailed out of
6169 // computing parameter / argument correspondence before this point. Track
6170 // the pack as the corresponding parameter for all further template
6171 // arguments until we hit a pack expansion, at which point we don't know
6172 // the correspondence between parameters and arguments at all.
6173 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
6174 UnresolvedExpandedPack = Param;
6175 }
6176 }
6177
6178 // If we encounter a pack argument that is expanded into a non-pack
6179 // parameter, we can no longer track parameter / argument correspondence,
6180 // and need to use exact types from this point onwards.
6181 if (Arg.isPackExpansion() &&
6182 (!Param->isParameterPack() || UnresolvedExpandedPack)) {
6184 return {true, nullptr};
6185 }
6186
6187 // We need exact types for arguments of a template that might be overloaded
6188 // on template parameter type.
6189 if (isOverloadable())
6190 return {true, needToMangleTemplateParam(Param, Arg) ? Param : nullptr};
6191
6192 // Otherwise, we only need a correct type if the parameter has a deduced
6193 // type.
6194 //
6195 // Note: for an expanded parameter pack, getType() returns the type prior
6196 // to expansion. We could ask for the expanded type with getExpansionType(),
6197 // but it doesn't matter because substitution and expansion don't affect
6198 // whether a deduced type appears in the type.
6199 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
6200 bool NeedExactType = NTTP && NTTP->getType()->getContainedDeducedType();
6201 return {NeedExactType, nullptr};
6202 }
6203
6204 /// Determine if we should mangle a requires-clause after the template
6205 /// argument list. If so, returns the expression to mangle.
6207 if (!isOverloadable())
6208 return nullptr;
6209 return ResolvedTemplate->getTemplateParameters()->getRequiresClause();
6210 }
6211};
6212
6213void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6214 const TemplateArgumentLoc *TemplateArgs,
6215 unsigned NumTemplateArgs) {
6216 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6217 Out << 'I';
6218 TemplateArgManglingInfo Info(*this, TN);
6219 for (unsigned i = 0; i != NumTemplateArgs; ++i) {
6220 mangleTemplateArg(Info, i, TemplateArgs[i].getArgument());
6221 }
6222 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
6223 Out << 'E';
6224}
6225
6226void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6227 const TemplateArgumentList &AL) {
6228 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6229 Out << 'I';
6230 TemplateArgManglingInfo Info(*this, TN);
6231 for (unsigned i = 0, e = AL.size(); i != e; ++i) {
6232 mangleTemplateArg(Info, i, AL[i]);
6233 }
6234 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
6235 Out << 'E';
6236}
6237
6238void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6239 ArrayRef<TemplateArgument> Args) {
6240 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6241 Out << 'I';
6242 TemplateArgManglingInfo Info(*this, TN);
6243 for (unsigned i = 0; i != Args.size(); ++i) {
6244 mangleTemplateArg(Info, i, Args[i]);
6245 }
6246 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
6247 Out << 'E';
6248}
6249
6250void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo &Info,
6251 unsigned Index, TemplateArgument A) {
6252 TemplateArgManglingInfo::Info ArgInfo = Info.getArgInfo(Index, A);
6253
6254 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6255 if (ArgInfo.TemplateParameterToMangle &&
6256 !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
6257 // The template parameter is mangled if the mangling would otherwise be
6258 // ambiguous.
6259 //
6260 // <template-arg> ::= <template-param-decl> <template-arg>
6261 //
6262 // Clang 17 and before did not do this.
6263 mangleTemplateParamDecl(ArgInfo.TemplateParameterToMangle);
6264 }
6265
6266 mangleTemplateArg(A, ArgInfo.NeedExactType);
6267}
6268
6269void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
6270 // <template-arg> ::= <type> # type or template
6271 // ::= X <expression> E # expression
6272 // ::= <expr-primary> # simple expressions
6273 // ::= J <template-arg>* E # argument pack
6274 if (!A.isInstantiationDependent() || A.isDependent())
6275 A = Context.getASTContext().getCanonicalTemplateArgument(A);
6276
6277 switch (A.getKind()) {
6279 llvm_unreachable("Cannot mangle NULL template argument");
6280
6282 mangleType(A.getAsType());
6283 break;
6285 // This is mangled as <type>.
6286 mangleType(A.getAsTemplate());
6287 break;
6289 // <type> ::= Dp <type> # pack expansion (C++0x)
6290 Out << "Dp";
6291 mangleType(A.getAsTemplateOrTemplatePattern());
6292 break;
6294 mangleTemplateArgExpr(A.getAsExpr());
6295 break;
6297 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
6298 break;
6300 // <expr-primary> ::= L <mangled-name> E # external name
6301 ValueDecl *D = A.getAsDecl();
6302
6303 // Template parameter objects are modeled by reproducing a source form
6304 // produced as if by aggregate initialization.
6305 if (A.getParamTypeForDecl()->isRecordType()) {
6306 auto *TPO = cast<TemplateParamObjectDecl>(D);
6307 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
6308 TPO->getValue(), /*TopLevel=*/true,
6309 NeedExactType);
6310 break;
6311 }
6312
6313 ASTContext &Ctx = Context.getASTContext();
6314 APValue Value;
6315 if (D->isCXXInstanceMember())
6316 // Simple pointer-to-member with no conversion.
6317 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
6318 else if (D->getType()->isArrayType() &&
6320 A.getParamTypeForDecl()) &&
6321 !isCompatibleWith(LangOptions::ClangABI::Ver11))
6322 // Build a value corresponding to this implicit array-to-pointer decay.
6323 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
6325 /*OnePastTheEnd=*/false);
6326 else
6327 // Regular pointer or reference to a declaration.
6328 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
6329 ArrayRef<APValue::LValuePathEntry>(),
6330 /*OnePastTheEnd=*/false);
6331 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
6332 NeedExactType);
6333 break;
6334 }
6336 mangleNullPointer(A.getNullPtrType());
6337 break;
6338 }
6340 mangleValueInTemplateArg(A.getStructuralValueType(),
6342 /*TopLevel=*/true, NeedExactType);
6343 break;
6345 // <template-arg> ::= J <template-arg>* E
6346 Out << 'J';
6347 for (const auto &P : A.pack_elements())
6348 mangleTemplateArg(P, NeedExactType);
6349 Out << 'E';
6350 }
6351 }
6352}
6353
6354void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
6355 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6356 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
6357 return;
6358 }
6359
6360 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
6361 // correctly in cases where the template argument was
6362 // constructed from an expression rather than an already-evaluated
6363 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
6364 // 'Li0E'.
6365 //
6366 // We did special-case DeclRefExpr to attempt to DTRT for that one
6367 // expression-kind, but while doing so, unfortunately handled ParmVarDecl
6368 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
6369 // the proper 'Xfp_E'.
6370 E = E->IgnoreParenImpCasts();
6371 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6372 const ValueDecl *D = DRE->getDecl();
6373 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
6374 Out << 'L';
6375 mangle(D);
6376 Out << 'E';
6377 return;
6378 }
6379 }
6380 Out << 'X';
6381 mangleExpression(E);
6382 Out << 'E';
6383}
6384
6385/// Determine whether a given value is equivalent to zero-initialization for
6386/// the purpose of discarding a trailing portion of a 'tl' mangling.
6387///
6388/// Note that this is not in general equivalent to determining whether the
6389/// value has an all-zeroes bit pattern.
6390static bool isZeroInitialized(QualType T, const APValue &V) {
6391 // FIXME: mangleValueInTemplateArg has quadratic time complexity in
6392 // pathological cases due to using this, but it's a little awkward
6393 // to do this in linear time in general.
6394 switch (V.getKind()) {
6395 case APValue::None:
6398 return false;
6399
6400 case APValue::Struct: {
6401 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6402 assert(RD && "unexpected type for record value");
6403 unsigned I = 0;
6404 for (const CXXBaseSpecifier &BS : RD->bases()) {
6405 if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
6406 return false;
6407 ++I;
6408 }
6409 I = 0;
6410 for (const FieldDecl *FD : RD->fields()) {
6411 if (!FD->isUnnamedBitField() &&
6412 !isZeroInitialized(FD->getType(), V.getStructField(I)))
6413 return false;
6414 ++I;
6415 }
6416 return true;
6417 }
6418
6419 case APValue::Union: {
6420 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6421 assert(RD && "unexpected type for union value");
6422 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
6423 for (const FieldDecl *FD : RD->fields()) {
6424 if (!FD->isUnnamedBitField())
6425 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
6426 isZeroInitialized(FD->getType(), V.getUnionValue());
6427 }
6428 // If there are no fields (other than unnamed bitfields), the value is
6429 // necessarily zero-initialized.
6430 return true;
6431 }
6432
6433 case APValue::Array: {
6434 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6435 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
6436 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
6437 return false;
6438 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
6439 }
6440
6441 case APValue::Vector: {
6442 const VectorType *VT = T->castAs<VectorType>();
6443 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
6444 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
6445 return false;
6446 return true;
6447 }
6448
6449 case APValue::Int:
6450 return !V.getInt();
6451
6452 case APValue::Float:
6453 return V.getFloat().isPosZero();
6454
6456 return !V.getFixedPoint().getValue();
6457
6459 return V.getComplexFloatReal().isPosZero() &&
6460 V.getComplexFloatImag().isPosZero();
6461
6463 return !V.getComplexIntReal() && !V.getComplexIntImag();
6464
6465 case APValue::LValue:
6466 return V.isNullPointer();
6467
6469 return !V.getMemberPointerDecl();
6470 }
6471
6472 llvm_unreachable("Unhandled APValue::ValueKind enum");
6473}
6474
6475static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
6478 if (const ArrayType *AT = Ctx.getAsArrayType(T))
6479 T = AT->getElementType();
6480 else if (const FieldDecl *FD =
6481 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
6482 T = FD->getType();
6483 else
6484 T = Ctx.getCanonicalTagType(
6485 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
6486 }
6487 return T;
6488}
6489
6491 DiagnosticsEngine &Diags,
6492 const FieldDecl *FD) {
6493 // According to:
6494 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
6495 // For the purposes of mangling, the name of an anonymous union is considered
6496 // to be the name of the first named data member found by a pre-order,
6497 // depth-first, declaration-order walk of the data members of the anonymous
6498 // union.
6499
6500 if (FD->getIdentifier())
6501 return FD->getIdentifier();
6502
6503 // The only cases where the identifer of a FieldDecl would be blank is if the
6504 // field represents an anonymous record type or if it is an unnamed bitfield.
6505 // There is no type to descend into in the case of a bitfield, so we can just
6506 // return nullptr in that case.
6507 if (FD->isBitField())
6508 return nullptr;
6509 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
6510
6511 // Consider only the fields in declaration order, searched depth-first. We
6512 // don't care about the active member of the union, as all we are doing is
6513 // looking for a valid name. We also don't check bases, due to guidance from
6514 // the Itanium ABI folks.
6515 for (const FieldDecl *RDField : RD->fields()) {
6516 if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
6517 return II;
6518 }
6519
6520 // According to the Itanium ABI: If there is no such data member (i.e., if all
6521 // of the data members in the union are unnamed), then there is no way for a
6522 // program to refer to the anonymous union, and there is therefore no need to
6523 // mangle its name. However, we should diagnose this anyway.
6524 unsigned DiagID = Diags.getCustomDiagID(
6525 DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
6526 Diags.Report(UnionLoc, DiagID);
6527
6528 return nullptr;
6529}
6530
6531void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
6532 bool TopLevel,
6533 bool NeedExactType) {
6534 // Ignore all top-level cv-qualifiers, to match GCC.
6535 Qualifiers Quals;
6536 T = getASTContext().getUnqualifiedArrayType(T, Quals);
6537
6538 // A top-level expression that's not a primary expression is wrapped in X...E.
6539 bool IsPrimaryExpr = true;
6540 auto NotPrimaryExpr = [&] {
6541 if (TopLevel && IsPrimaryExpr)
6542 Out << 'X';
6543 IsPrimaryExpr = false;
6544 };
6545
6546 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
6547 switch (V.getKind()) {
6548 case APValue::None:
6550 Out << 'L';
6551 mangleType(T);
6552 Out << 'E';
6553 break;
6554
6556 llvm_unreachable("unexpected value kind in template argument");
6557
6558 case APValue::Struct: {
6559 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6560 assert(RD && "unexpected type for record value");
6561
6562 // Drop trailing zero-initialized elements.
6563 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());
6564 while (
6565 !Fields.empty() &&
6566 (Fields.back()->isUnnamedBitField() ||
6567 isZeroInitialized(Fields.back()->getType(),
6568 V.getStructField(Fields.back()->getFieldIndex())))) {
6569 Fields.pop_back();
6570 }
6571 ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
6572 if (Fields.empty()) {
6573 while (!Bases.empty() &&
6574 isZeroInitialized(Bases.back().getType(),
6575 V.getStructBase(Bases.size() - 1)))
6576 Bases = Bases.drop_back();
6577 }
6578
6579 // <expression> ::= tl <type> <braced-expression>* E
6580 NotPrimaryExpr();
6581 Out << "tl";
6582 mangleType(T);
6583 for (unsigned I = 0, N = Bases.size(); I != N; ++I)
6584 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
6585 for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
6586 if (Fields[I]->isUnnamedBitField())
6587 continue;
6588 mangleValueInTemplateArg(Fields[I]->getType(),
6589 V.getStructField(Fields[I]->getFieldIndex()),
6590 false);
6591 }
6592 Out << 'E';
6593 break;
6594 }
6595
6596 case APValue::Union: {
6597 assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
6598 const FieldDecl *FD = V.getUnionField();
6599
6600 if (!FD) {
6601 Out << 'L';
6602 mangleType(T);
6603 Out << 'E';
6604 break;
6605 }
6606
6607 // <braced-expression> ::= di <field source-name> <braced-expression>
6608 NotPrimaryExpr();
6609 Out << "tl";
6610 mangleType(T);
6611 if (!isZeroInitialized(T, V)) {
6612 Out << "di";
6613 IdentifierInfo *II = (getUnionInitName(
6614 T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
6615 if (II)
6616 mangleSourceName(II);
6617 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
6618 }
6619 Out << 'E';
6620 break;
6621 }
6622
6623 case APValue::Array: {
6624 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6625
6626 NotPrimaryExpr();
6627 Out << "tl";
6628 mangleType(T);
6629
6630 // Drop trailing zero-initialized elements.
6631 unsigned N = V.getArraySize();
6632 if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
6633 N = V.getArrayInitializedElts();
6634 while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
6635 --N;
6636 }
6637
6638 for (unsigned I = 0; I != N; ++I) {
6639 const APValue &Elem = I < V.getArrayInitializedElts()
6640 ? V.getArrayInitializedElt(I)
6641 : V.getArrayFiller();
6642 mangleValueInTemplateArg(ElemT, Elem, false);
6643 }
6644 Out << 'E';
6645 break;
6646 }
6647
6648 case APValue::Vector: {
6649 const VectorType *VT = T->castAs<VectorType>();
6650
6651 NotPrimaryExpr();
6652 Out << "tl";
6653 mangleType(T);
6654 unsigned N = V.getVectorLength();
6655 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
6656 --N;
6657 for (unsigned I = 0; I != N; ++I)
6658 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
6659 Out << 'E';
6660 break;
6661 }
6662
6663 case APValue::Int:
6664 mangleIntegerLiteral(T, V.getInt());
6665 break;
6666
6667 case APValue::Float:
6668 mangleFloatLiteral(T, V.getFloat());
6669 break;
6670
6672 mangleFixedPointLiteral();
6673 break;
6674
6675 case APValue::ComplexFloat: {
6676 const ComplexType *CT = T->castAs<ComplexType>();
6677 NotPrimaryExpr();
6678 Out << "tl";
6679 mangleType(T);
6680 if (!V.getComplexFloatReal().isPosZero() ||
6681 !V.getComplexFloatImag().isPosZero())
6682 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
6683 if (!V.getComplexFloatImag().isPosZero())
6684 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
6685 Out << 'E';
6686 break;
6687 }
6688
6689 case APValue::ComplexInt: {
6690 const ComplexType *CT = T->castAs<ComplexType>();
6691 NotPrimaryExpr();
6692 Out << "tl";
6693 mangleType(T);
6694 if (V.getComplexIntReal().getBoolValue() ||
6695 V.getComplexIntImag().getBoolValue())
6696 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
6697 if (V.getComplexIntImag().getBoolValue())
6698 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
6699 Out << 'E';
6700 break;
6701 }
6702
6703 case APValue::LValue: {
6704 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6705 assert((T->isPointerOrReferenceType()) &&
6706 "unexpected type for LValue template arg");
6707
6708 if (V.isNullPointer()) {
6709 mangleNullPointer(T);
6710 break;
6711 }
6712
6713 APValue::LValueBase B = V.getLValueBase();
6714 if (!B) {
6715 // Non-standard mangling for integer cast to a pointer; this can only
6716 // occur as an extension.
6717 CharUnits Offset = V.getLValueOffset();
6718 if (Offset.isZero()) {
6719 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
6720 // a cast, because L <type> 0 E means something else.
6721 NotPrimaryExpr();
6722 Out << "rc";
6723 mangleType(T);
6724 Out << "Li0E";
6725 if (TopLevel)
6726 Out << 'E';
6727 } else {
6728 Out << "L";
6729 mangleType(T);
6730 Out << Offset.getQuantity() << 'E';
6731 }
6732 break;
6733 }
6734
6735 ASTContext &Ctx = Context.getASTContext();
6736
6737 enum { Base, Offset, Path } Kind;
6738 if (!V.hasLValuePath()) {
6739 // Mangle as (T*)((char*)&base + N).
6740 if (T->isReferenceType()) {
6741 NotPrimaryExpr();
6742 Out << "decvP";
6743 mangleType(T->getPointeeType());
6744 } else {
6745 NotPrimaryExpr();
6746 Out << "cv";
6747 mangleType(T);
6748 }
6749 Out << "plcvPcad";
6750 Kind = Offset;
6751 } else {
6752 // Clang 11 and before mangled an array subject to array-to-pointer decay
6753 // as if it were the declaration itself.
6754 bool IsArrayToPointerDecayMangledAsDecl = false;
6755 if (TopLevel && Ctx.getLangOpts().getClangABICompat() <=
6756 LangOptions::ClangABI::Ver11) {
6757 QualType BType = B.getType();
6758 IsArrayToPointerDecayMangledAsDecl =
6759 BType->isArrayType() && V.getLValuePath().size() == 1 &&
6760 V.getLValuePath()[0].getAsArrayIndex() == 0 &&
6761 Ctx.hasSimilarType(T, Ctx.getDecayedType(BType));
6762 }
6763
6764 if ((!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) &&
6765 !IsArrayToPointerDecayMangledAsDecl) {
6766 NotPrimaryExpr();
6767 // A final conversion to the template parameter's type is usually
6768 // folded into the 'so' mangling, but we can't do that for 'void*'
6769 // parameters without introducing collisions.
6770 if (NeedExactType && T->isVoidPointerType()) {
6771 Out << "cv";
6772 mangleType(T);
6773 }
6774 if (T->isPointerType())
6775 Out << "ad";
6776 Out << "so";
6777 mangleType(T->isVoidPointerType()
6778 ? getLValueType(Ctx, V).getUnqualifiedType()
6779 : T->getPointeeType());
6780 Kind = Path;
6781 } else {
6782 if (NeedExactType &&
6783 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
6784 !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6785 NotPrimaryExpr();
6786 Out << "cv";
6787 mangleType(T);
6788 }
6789 if (T->isPointerType()) {
6790 NotPrimaryExpr();
6791 Out << "ad";
6792 }
6793 Kind = Base;
6794 }
6795 }
6796
6797 QualType TypeSoFar = B.getType();
6798 if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
6799 Out << 'L';
6800 mangle(VD);
6801 Out << 'E';
6802 } else if (auto *E = B.dyn_cast<const Expr*>()) {
6803 NotPrimaryExpr();
6804 mangleExpression(E);
6805 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
6806 NotPrimaryExpr();
6807 Out << "ti";
6808 mangleType(QualType(TI.getType(), 0));
6809 } else {
6810 // We should never see dynamic allocations here.
6811 llvm_unreachable("unexpected lvalue base kind in template argument");
6812 }
6813
6814 switch (Kind) {
6815 case Base:
6816 break;
6817
6818 case Offset:
6819 Out << 'L';
6820 mangleType(Ctx.getPointerDiffType());
6821 mangleNumber(V.getLValueOffset().getQuantity());
6822 Out << 'E';
6823 break;
6824
6825 case Path:
6826 // <expression> ::= so <referent type> <expr> [<offset number>]
6827 // <union-selector>* [p] E
6828 if (!V.getLValueOffset().isZero())
6829 mangleNumber(V.getLValueOffset().getQuantity());
6830
6831 // We model a past-the-end array pointer as array indexing with index N,
6832 // not with the "past the end" flag. Compensate for that.
6833 bool OnePastTheEnd = V.isLValueOnePastTheEnd();
6834
6835 for (APValue::LValuePathEntry E : V.getLValuePath()) {
6836 if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
6837 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
6838 OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
6839 TypeSoFar = AT->getElementType();
6840 } else {
6841 const Decl *D = E.getAsBaseOrMember().getPointer();
6842 if (auto *FD = dyn_cast<FieldDecl>(D)) {
6843 // <union-selector> ::= _ <number>
6844 if (FD->getParent()->isUnion()) {
6845 Out << '_';
6846 if (FD->getFieldIndex())
6847 Out << (FD->getFieldIndex() - 1);
6848 }
6849 TypeSoFar = FD->getType();
6850 } else {
6851 TypeSoFar = Ctx.getCanonicalTagType(cast<CXXRecordDecl>(D));
6852 }
6853 }
6854 }
6855
6856 if (OnePastTheEnd)
6857 Out << 'p';
6858 Out << 'E';
6859 break;
6860 }
6861
6862 break;
6863 }
6864
6866 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6867 if (!V.getMemberPointerDecl()) {
6868 mangleNullPointer(T);
6869 break;
6870 }
6871
6872 ASTContext &Ctx = Context.getASTContext();
6873
6874 NotPrimaryExpr();
6875 if (!V.getMemberPointerPath().empty()) {
6876 Out << "mc";
6877 mangleType(T);
6878 } else if (NeedExactType &&
6879 !Ctx.hasSameType(
6880 T->castAs<MemberPointerType>()->getPointeeType(),
6881 V.getMemberPointerDecl()->getType()) &&
6882 !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6883 Out << "cv";
6884 mangleType(T);
6885 }
6886 Out << "adL";
6887 mangle(V.getMemberPointerDecl());
6888 Out << 'E';
6889 if (!V.getMemberPointerPath().empty()) {
6890 CharUnits Offset =
6891 Context.getASTContext().getMemberPointerPathAdjustment(V);
6892 if (!Offset.isZero())
6893 mangleNumber(Offset.getQuantity());
6894 Out << 'E';
6895 }
6896 break;
6897 }
6898
6899 if (TopLevel && !IsPrimaryExpr)
6900 Out << 'E';
6901}
6902
6903void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
6904 // <template-param> ::= T_ # first template parameter
6905 // ::= T <parameter-2 non-negative number> _
6906 // ::= TL <L-1 non-negative number> __
6907 // ::= TL <L-1 non-negative number> _
6908 // <parameter-2 non-negative number> _
6909 //
6910 // The latter two manglings are from a proposal here:
6911 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
6912 Out << 'T';
6913 Depth += TemplateDepthOffset;
6914 if (Depth != 0)
6915 Out << 'L' << (Depth - 1) << '_';
6916 if (Index != 0)
6917 Out << (Index - 1);
6918 Out << '_';
6919}
6920
6921void CXXNameMangler::mangleSeqID(unsigned SeqID) {
6922 if (SeqID == 0) {
6923 // Nothing.
6924 } else if (SeqID == 1) {
6925 Out << '0';
6926 } else {
6927 SeqID--;
6928
6929 // <seq-id> is encoded in base-36, using digits and upper case letters.
6930 char Buffer[7]; // log(2**32) / log(36) ~= 7
6931 MutableArrayRef<char> BufferRef(Buffer);
6932 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
6933
6934 for (; SeqID != 0; SeqID /= 36) {
6935 unsigned C = SeqID % 36;
6936 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
6937 }
6938
6939 Out.write(I.base(), I - BufferRef.rbegin());
6940 }
6941 Out << '_';
6942}
6943
6944void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
6945 bool result = mangleSubstitution(tname);
6946 assert(result && "no existing substitution for template name");
6947 (void) result;
6948}
6949
6950// <substitution> ::= S <seq-id> _
6951// ::= S_
6952bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
6953 // Try one of the standard substitutions first.
6954 if (mangleStandardSubstitution(ND))
6955 return true;
6956
6958 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
6959}
6960
6961/// Determine whether the given type has any qualifiers that are relevant for
6962/// substitutions.
6964 Qualifiers Qs = T.getQualifiers();
6965 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
6966}
6967
6968bool CXXNameMangler::mangleSubstitution(QualType T) {
6970 if (const auto *RD = T->getAsCXXRecordDecl())
6971 return mangleSubstitution(RD);
6972 }
6973
6974 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
6975
6976 return mangleSubstitution(TypePtr);
6977}
6978
6979bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
6980 if (TemplateDecl *TD = Template.getAsTemplateDecl())
6981 return mangleSubstitution(TD);
6982
6983 Template = Context.getASTContext().getCanonicalTemplateName(Template);
6984 return mangleSubstitution(
6985 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
6986}
6987
6988bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
6989 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
6990 if (I == Substitutions.end())
6991 return false;
6992
6993 unsigned SeqID = I->second;
6994 Out << 'S';
6995 mangleSeqID(SeqID);
6996
6997 return true;
6998}
6999
7000/// Returns whether S is a template specialization of std::Name with a single
7001/// argument of type A.
7002bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,
7003 QualType A) {
7004 if (S.isNull())
7005 return false;
7006
7007 const RecordType *RT = S->getAsCanonical<RecordType>();
7008 if (!RT)
7009 return false;
7010
7011 const ClassTemplateSpecializationDecl *SD =
7012 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
7013 if (!SD || !SD->getIdentifier()->isStr(Name))
7014 return false;
7015
7016 if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
7017 return false;
7018
7019 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
7020 if (TemplateArgs.size() != 1)
7021 return false;
7022
7023 if (TemplateArgs[0].getAsType() != A)
7024 return false;
7025
7027 return false;
7028
7029 return true;
7030}
7031
7032/// Returns whether SD is a template specialization std::Name<char,
7033/// std::char_traits<char> [, std::allocator<char>]>
7034/// HasAllocator controls whether the 3rd template argument is needed.
7035bool CXXNameMangler::isStdCharSpecialization(
7036 const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,
7037 bool HasAllocator) {
7038 if (!SD->getIdentifier()->isStr(Name))
7039 return false;
7040
7041 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
7042 if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
7043 return false;
7044
7045 QualType A = TemplateArgs[0].getAsType();
7046 if (A.isNull())
7047 return false;
7048 // Plain 'char' is named Char_S or Char_U depending on the target ABI.
7049 if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&
7050 !A->isSpecificBuiltinType(BuiltinType::Char_U))
7051 return false;
7052
7053 if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))
7054 return false;
7055
7056 if (HasAllocator &&
7057 !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))
7058 return false;
7059
7061 return false;
7062
7063 return true;
7064}
7065
7066bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
7067 // <substitution> ::= St # ::std::
7068 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
7069 if (isStd(NS)) {
7070 Out << "St";
7071 return true;
7072 }
7073 return false;
7074 }
7075
7076 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
7077 if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))
7078 return false;
7079
7080 if (TD->getOwningModuleForLinkage())
7081 return false;
7082
7083 // <substitution> ::= Sa # ::std::allocator
7084 if (TD->getIdentifier()->isStr("allocator")) {
7085 Out << "Sa";
7086 return true;
7087 }
7088
7089 // <<substitution> ::= Sb # ::std::basic_string
7090 if (TD->getIdentifier()->isStr("basic_string")) {
7091 Out << "Sb";
7092 return true;
7093 }
7094 return false;
7095 }
7096
7097 if (const ClassTemplateSpecializationDecl *SD =
7098 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
7099 if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
7100 return false;
7101
7103 return false;
7104
7105 // <substitution> ::= Ss # ::std::basic_string<char,
7106 // ::std::char_traits<char>,
7107 // ::std::allocator<char> >
7108 if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {
7109 Out << "Ss";
7110 return true;
7111 }
7112
7113 // <substitution> ::= Si # ::std::basic_istream<char,
7114 // ::std::char_traits<char> >
7115 if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {
7116 Out << "Si";
7117 return true;
7118 }
7119
7120 // <substitution> ::= So # ::std::basic_ostream<char,
7121 // ::std::char_traits<char> >
7122 if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {
7123 Out << "So";
7124 return true;
7125 }
7126
7127 // <substitution> ::= Sd # ::std::basic_iostream<char,
7128 // ::std::char_traits<char> >
7129 if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {
7130 Out << "Sd";
7131 return true;
7132 }
7133 return false;
7134 }
7135
7136 return false;
7137}
7138
7139void CXXNameMangler::addSubstitution(QualType T) {
7141 if (const auto *RD = T->getAsCXXRecordDecl()) {
7142 addSubstitution(RD);
7143 return;
7144 }
7145 }
7146
7147 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
7148 addSubstitution(TypePtr);
7149}
7150
7151void CXXNameMangler::addSubstitution(TemplateName Template) {
7152 if (TemplateDecl *TD = Template.getAsTemplateDecl())
7153 return addSubstitution(TD);
7154
7155 Template = Context.getASTContext().getCanonicalTemplateName(Template);
7156 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
7157}
7158
7159void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
7160 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
7161 Substitutions[Ptr] = SeqID++;
7162}
7163
7164void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
7165 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
7166 if (Other->SeqID > SeqID) {
7167 Substitutions.swap(Other->Substitutions);
7168 SeqID = Other->SeqID;
7169 }
7170}
7171
7172CXXNameMangler::AbiTagList
7173CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
7174 // When derived abi tags are disabled there is no need to make any list.
7175 if (DisableDerivedAbiTags)
7176 return AbiTagList();
7177
7178 llvm::raw_null_ostream NullOutStream;
7179 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
7180 TrackReturnTypeTags.disableDerivedAbiTags();
7181
7182 const FunctionProtoType *Proto =
7183 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
7184 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
7185 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
7186 TrackReturnTypeTags.mangleType(Proto->getReturnType());
7187 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
7188 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
7189
7190 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
7191}
7192
7193CXXNameMangler::AbiTagList
7194CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
7195 // When derived abi tags are disabled there is no need to make any list.
7196 if (DisableDerivedAbiTags)
7197 return AbiTagList();
7198
7199 llvm::raw_null_ostream NullOutStream;
7200 CXXNameMangler TrackVariableType(*this, NullOutStream);
7201 TrackVariableType.disableDerivedAbiTags();
7202
7203 TrackVariableType.mangleType(VD->getType());
7204
7205 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
7206}
7207
7208bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
7209 const VarDecl *VD) {
7210 llvm::raw_null_ostream NullOutStream;
7211 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
7212 TrackAbiTags.mangle(VD);
7213 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
7214}
7215
7216//
7217
7218/// Mangles the name of the declaration D and emits that name to the given
7219/// output stream.
7220///
7221/// If the declaration D requires a mangled name, this routine will emit that
7222/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
7223/// and this routine will return false. In this case, the caller should just
7224/// emit the identifier of the declaration (\c D->getIdentifier()) as its
7225/// name.
7226void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
7227 raw_ostream &Out) {
7228 const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
7230 "Invalid mangleName() call, argument is not a variable or function!");
7231
7232 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
7233 getASTContext().getSourceManager(),
7234 "Mangling declaration");
7235
7236 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
7237 auto Type = GD.getCtorType();
7238 CXXNameMangler Mangler(*this, Out, CD, Type);
7239 return Mangler.mangle(GlobalDecl(CD, Type));
7240 }
7241
7242 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
7243 auto Type = GD.getDtorType();
7244 CXXNameMangler Mangler(*this, Out, DD, Type);
7245 return Mangler.mangle(GlobalDecl(DD, Type));
7246 }
7247
7248 CXXNameMangler Mangler(*this, Out, D);
7249 Mangler.mangle(GD);
7250}
7251
7252void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
7253 raw_ostream &Out) {
7254 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
7255 Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
7256}
7257
7258void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
7259 raw_ostream &Out) {
7260 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
7261 Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
7262}
7263
7264/// Mangles the pointer authentication override attribute for classes
7265/// that have explicit overrides for the vtable authentication schema.
7266///
7267/// The override is mangled as a parameterized vendor extension as follows
7268///
7269/// <type> ::= U "__vtptrauth" I
7270/// <key>
7271/// <addressDiscriminated>
7272/// <extraDiscriminator>
7273/// E
7274///
7275/// The extra discriminator encodes the explicit value derived from the
7276/// override schema, e.g. if the override has specified type based
7277/// discrimination the encoded value will be the discriminator derived from the
7278/// type name.
7279static void mangleOverrideDiscrimination(CXXNameMangler &Mangler,
7280 ASTContext &Context,
7281 const ThunkInfo &Thunk) {
7282 auto &LangOpts = Context.getLangOpts();
7283 const CXXRecordDecl *ThisRD = Thunk.ThisType->getPointeeCXXRecordDecl();
7284 const CXXRecordDecl *PtrauthClassRD =
7285 Context.baseForVTableAuthentication(ThisRD);
7286 unsigned TypedDiscriminator =
7287 Context.getPointerAuthVTablePointerDiscriminator(ThisRD);
7288 Mangler.mangleVendorQualifier("__vtptrauth");
7289 auto &ManglerStream = Mangler.getStream();
7290 ManglerStream << "I";
7291 if (const auto *ExplicitAuth =
7292 PtrauthClassRD->getAttr<VTablePointerAuthenticationAttr>()) {
7293 ManglerStream << "Lj" << ExplicitAuth->getKey();
7294
7295 if (ExplicitAuth->getAddressDiscrimination() ==
7296 VTablePointerAuthenticationAttr::DefaultAddressDiscrimination)
7297 ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;
7298 else
7299 ManglerStream << "Lb"
7300 << (ExplicitAuth->getAddressDiscrimination() ==
7301 VTablePointerAuthenticationAttr::AddressDiscrimination);
7302
7303 switch (ExplicitAuth->getExtraDiscrimination()) {
7304 case VTablePointerAuthenticationAttr::DefaultExtraDiscrimination: {
7305 if (LangOpts.PointerAuthVTPtrTypeDiscrimination)
7306 ManglerStream << "Lj" << TypedDiscriminator;
7307 else
7308 ManglerStream << "Lj" << 0;
7309 break;
7310 }
7311 case VTablePointerAuthenticationAttr::TypeDiscrimination:
7312 ManglerStream << "Lj" << TypedDiscriminator;
7313 break;
7314 case VTablePointerAuthenticationAttr::CustomDiscrimination:
7315 ManglerStream << "Lj" << ExplicitAuth->getCustomDiscriminationValue();
7316 break;
7317 case VTablePointerAuthenticationAttr::NoExtraDiscrimination:
7318 ManglerStream << "Lj" << 0;
7319 break;
7320 }
7321 } else {
7322 ManglerStream << "Lj"
7323 << (unsigned)VTablePointerAuthenticationAttr::DefaultKey;
7324 ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;
7325 if (LangOpts.PointerAuthVTPtrTypeDiscrimination)
7326 ManglerStream << "Lj" << TypedDiscriminator;
7327 else
7328 ManglerStream << "Lj" << 0;
7329 }
7330 ManglerStream << "E";
7331}
7332
7333void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
7334 const ThunkInfo &Thunk,
7335 bool ElideOverrideInfo,
7336 raw_ostream &Out) {
7337 // <special-name> ::= T <call-offset> <base encoding>
7338 // # base is the nominal target function of thunk
7339 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
7340 // # base is the nominal target function of thunk
7341 // # first call-offset is 'this' adjustment
7342 // # second call-offset is result adjustment
7343
7344 assert(!isa<CXXDestructorDecl>(MD) &&
7345 "Use mangleCXXDtor for destructor decls!");
7346 CXXNameMangler Mangler(*this, Out);
7347 Mangler.getStream() << "_ZT";
7348 if (!Thunk.Return.isEmpty())
7349 Mangler.getStream() << 'c';
7350
7351 // Mangle the 'this' pointer adjustment.
7352 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
7354
7355 // Mangle the return pointer adjustment if there is one.
7356 if (!Thunk.Return.isEmpty())
7357 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
7359
7360 Mangler.mangleFunctionEncoding(MD);
7361 if (!ElideOverrideInfo)
7362 mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);
7363}
7364
7365void ItaniumMangleContextImpl::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
7367 const ThunkInfo &Thunk,
7368 bool ElideOverrideInfo,
7369 raw_ostream &Out) {
7370 // <special-name> ::= T <call-offset> <base encoding>
7371 // # base is the nominal target function of thunk
7372 CXXNameMangler Mangler(*this, Out, DD, Type);
7373 Mangler.getStream() << "_ZT";
7374
7375 auto &ThisAdjustment = Thunk.This;
7376 // Mangle the 'this' pointer adjustment.
7377 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
7378 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
7379
7380 Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
7381 if (!ElideOverrideInfo)
7382 mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);
7383}
7384
7385/// Returns the mangled name for a guard variable for the passed in VarDecl.
7386void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
7387 raw_ostream &Out) {
7388 // <special-name> ::= GV <object name> # Guard variable for one-time
7389 // # initialization
7390 CXXNameMangler Mangler(*this, Out);
7391 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
7392 // be a bug that is fixed in trunk.
7393 Mangler.getStream() << "_ZGV";
7394 Mangler.mangleName(D);
7395}
7396
7397void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
7398 raw_ostream &Out) {
7399 // These symbols are internal in the Itanium ABI, so the names don't matter.
7400 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
7401 // avoid duplicate symbols.
7402 Out << "__cxx_global_var_init";
7403}
7404
7405void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
7406 raw_ostream &Out) {
7407 // Prefix the mangling of D with __dtor_.
7408 CXXNameMangler Mangler(*this, Out);
7409 Mangler.getStream() << "__dtor_";
7410 if (shouldMangleDeclName(D))
7411 Mangler.mangle(D);
7412 else
7413 Mangler.getStream() << D->getName();
7414}
7415
7416void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
7417 raw_ostream &Out) {
7418 // Clang generates these internal-linkage functions as part of its
7419 // implementation of the XL ABI.
7420 CXXNameMangler Mangler(*this, Out);
7421 Mangler.getStream() << "__finalize_";
7422 if (shouldMangleDeclName(D))
7423 Mangler.mangle(D);
7424 else
7425 Mangler.getStream() << D->getName();
7426}
7427
7428void ItaniumMangleContextImpl::mangleSEHFilterExpression(
7429 GlobalDecl EnclosingDecl, raw_ostream &Out) {
7430 CXXNameMangler Mangler(*this, Out);
7431 Mangler.getStream() << "__filt_";
7432 auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7433 if (shouldMangleDeclName(EnclosingFD))
7434 Mangler.mangle(EnclosingDecl);
7435 else
7436 Mangler.getStream() << EnclosingFD->getName();
7437}
7438
7439void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
7440 GlobalDecl EnclosingDecl, raw_ostream &Out) {
7441 CXXNameMangler Mangler(*this, Out);
7442 Mangler.getStream() << "__fin_";
7443 auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7444 if (shouldMangleDeclName(EnclosingFD))
7445 Mangler.mangle(EnclosingDecl);
7446 else
7447 Mangler.getStream() << EnclosingFD->getName();
7448}
7449
7450void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
7451 raw_ostream &Out) {
7452 // <special-name> ::= TH <object name>
7453 CXXNameMangler Mangler(*this, Out);
7454 Mangler.getStream() << "_ZTH";
7455 Mangler.mangleName(D);
7456}
7457
7458void
7459ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
7460 raw_ostream &Out) {
7461 // <special-name> ::= TW <object name>
7462 CXXNameMangler Mangler(*this, Out);
7463 Mangler.getStream() << "_ZTW";
7464 Mangler.mangleName(D);
7465}
7466
7467void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
7468 unsigned ManglingNumber,
7469 raw_ostream &Out) {
7470 // We match the GCC mangling here.
7471 // <special-name> ::= GR <object name>
7472 CXXNameMangler Mangler(*this, Out);
7473 Mangler.getStream() << "_ZGR";
7474 Mangler.mangleName(D);
7475 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
7476 Mangler.mangleSeqID(ManglingNumber - 1);
7477}
7478
7479void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
7480 raw_ostream &Out) {
7481 // <special-name> ::= TV <type> # virtual table
7482 CXXNameMangler Mangler(*this, Out);
7483 Mangler.getStream() << "_ZTV";
7484 Mangler.mangleCXXRecordDecl(RD);
7485}
7486
7487void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
7488 raw_ostream &Out) {
7489 // <special-name> ::= TT <type> # VTT structure
7490 CXXNameMangler Mangler(*this, Out);
7491 Mangler.getStream() << "_ZTT";
7492 Mangler.mangleCXXRecordDecl(RD);
7493}
7494
7495void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
7496 int64_t Offset,
7497 const CXXRecordDecl *Type,
7498 raw_ostream &Out) {
7499 // <special-name> ::= TC <type> <offset number> _ <base type>
7500 CXXNameMangler Mangler(*this, Out);
7501 Mangler.getStream() << "_ZTC";
7502 // Older versions of clang did not add the record as a substitution candidate
7503 // here.
7504 bool SuppressSubstitution =
7505 getASTContext().getLangOpts().getClangABICompat() <=
7506 LangOptions::ClangABI::Ver19;
7507 Mangler.mangleCXXRecordDecl(RD, SuppressSubstitution);
7508 Mangler.getStream() << Offset;
7509 Mangler.getStream() << '_';
7510 Mangler.mangleCXXRecordDecl(Type);
7511}
7512
7513void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
7514 // <special-name> ::= TI <type> # typeinfo structure
7515 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
7516 CXXNameMangler Mangler(*this, Out);
7517 Mangler.getStream() << "_ZTI";
7518 Mangler.mangleType(Ty);
7519}
7520
7521void ItaniumMangleContextImpl::mangleCXXRTTIName(
7522 QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7523 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
7524 CXXNameMangler Mangler(*this, Out, NormalizeIntegers);
7525 Mangler.getStream() << "_ZTS";
7526 Mangler.mangleType(Ty);
7527}
7528
7529void ItaniumMangleContextImpl::mangleCanonicalTypeName(
7530 QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7531 mangleCXXRTTIName(Ty, Out, NormalizeIntegers);
7532}
7533
7534void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
7535 llvm_unreachable("Can't mangle string literals");
7536}
7537
7538void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
7539 raw_ostream &Out) {
7540 CXXNameMangler Mangler(*this, Out);
7541 Mangler.mangleLambdaSig(Lambda);
7542}
7543
7544void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
7545 raw_ostream &Out) {
7546 // <special-name> ::= GI <module-name> # module initializer function
7547 CXXNameMangler Mangler(*this, Out);
7548 Mangler.getStream() << "_ZGI";
7549 Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
7550 if (M->isModulePartition()) {
7551 // The partition needs including, as partitions can have them too.
7552 auto Partition = M->Name.find(':');
7553 Mangler.mangleModuleNamePrefix(
7554 StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
7555 /*IsPartition*/ true);
7556 }
7557}
7558
7560 DiagnosticsEngine &Diags,
7561 bool IsAux) {
7562 return new ItaniumMangleContextImpl(
7563 Context, Diags,
7564 [](ASTContext &, const NamedDecl *) -> UnsignedOrNone {
7565 return std::nullopt;
7566 },
7567 IsAux);
7568}
7569
7572 DiscriminatorOverrideTy DiscriminatorOverride,
7573 bool IsAux) {
7574 return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,
7575 IsAux);
7576}
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:2691
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:188
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.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
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:891
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.
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:3720
Expr * getLHS() const
Definition Expr.h:4022
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2175
Expr * getRHS() const
Definition Expr.h:4024
Opcode getOpcode() const
Definition Expr.h:4017
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Kind getKind() const
Definition TypeBase.h:3212
Represents a base class of a C++ class.
Definition DeclCXX.h:146
ConstExprIterator const_arg_iterator
Definition ExprCXX.h:1669
bool isArrayForm() const
Definition ExprCXX.h:2646
bool isGlobalDelete() const
Definition ExprCXX.h:2645
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:3963
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the member name.
Definition ExprCXX.h:3971
unsigned getNumTemplateArgs() const
Retrieve the number of template arguments provided as part of this template-id.
Definition ExprCXX.h:4058
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments provided as part of this template-id.
Definition ExprCXX.h:4049
DeclarationName getMember() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4002
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:3990
Expr * getBase() const
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:3954
bool isImplicitAccess() const
True if this is an implicit access, i.e.
Definition ExprCXX.h:3946
ConstExprIterator const_arg_iterator
Definition ExprCXX.h:2564
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:1229
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:3793
unsigned getNumArgs() const
Retrieve the number of arguments.
Definition ExprCXX.h:3796
Expr * getExprOperand() const
Definition ExprCXX.h:1110
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:1099
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
arg_range arguments()
Definition Expr.h:3129
Expr * getSubExpr()
Definition Expr.h:3660
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:3285
Expr * getLHS() const
Definition Expr.h:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4348
Expr * getRHS() const
Definition Expr.h:4360
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:251
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:417
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:854
QualType getPointeeType() const
Definition TypeBase.h:4071
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies this declaration.
Definition ExprCXX.h:3556
unsigned getNumTemplateArgs() const
Definition ExprCXX.h:3605
DeclarationName getDeclName() const
Retrieve the name that this expression refers to.
Definition ExprCXX.h:3543
TemplateArgumentLoc const * getTemplateArgs() const
Definition ExprCXX.h:3598
IdentifierOrOverloadedOperator getName() const
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4225
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:231
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:904
llvm::APSInt getInitVal() const
Definition Decl.h:3440
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:3085
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3073
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
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:273
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
llvm::APFloat getValue() const
Definition Expr.h:1666
Represents a function declaration or definition.
Definition Decl.h:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3607
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4254
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4270
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
ValueDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition ExprCXX.h:4861
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5768
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5571
unsigned getNumParams() const
Definition TypeBase.h:5542
Qualifiers getMethodQuals() const
Definition TypeBase.h:5690
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5761
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5629
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5663
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:5718
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:5733
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5698
Declaration of a template function.
CallingConv getCC() const
Definition TypeBase.h:4630
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4486
bool isConsumed() const
Is this parameter considered "consumed" by Objective-C ARC?
Definition TypeBase.h:4508
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4499
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
ExtInfo getExtInfo() const
Definition TypeBase.h:4816
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4769
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4765
QualType getReturnType() const
Definition TypeBase.h:4800
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:5233
unsigned getNumInits() const
Definition Expr.h:5263
InitListExpr * getSyntacticForm() const
Definition Expr.h:5406
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
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:3409
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments provided as part of this template-id.
Definition Expr.h:3454
Expr * getBase() const
Definition Expr.h:3375
unsigned getNumTemplateArgs() const
Retrieve the number of template arguments provided as part of this template-id.
Definition Expr.h:3463
bool isArrow() const
Definition Expr.h:3482
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:273
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
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:1962
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
bool isExternallyVisible() const
Definition Decl.h:432
Represent a C++ namespace.
Definition Decl.h:591
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:642
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3261
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:3238
decls_iterator decls_begin() const
Definition ExprCXX.h:3215
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3226
TemplateArgumentLoc const * getTemplateArgs() const
Definition ExprCXX.h:3318
unsigned getNumTemplateArgs() const
Definition ExprCXX.h:3324
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3232
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
Represents a parameter to a function.
Definition Decl.h:1789
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1849
unsigned getFunctionScopeDepth() const
Definition Decl.h:1839
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8374
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:8325
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:8306
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:5125
field_range fields() const
Definition Decl.h:4512
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:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
const char * getStmtClassName() const
Definition Stmt.cpp:87
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3945
bool isUnion() const
Definition Decl.h:3919
virtual const char * getFloat128Mangling() const
Return the mangled code of __float128.
Definition TargetInfo.h:826
virtual const char * getIbm128Mangling() const
Return the mangled code of __ibm128.
Definition TargetInfo.h:829
virtual const char * getLongDoubleMangling() const
Return the mangled code of long double.
Definition TargetInfo.h:823
virtual const char * getBFloat16Mangling() const
Return the mangled code of bfloat.
Definition TargetInfo.h:834
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:262
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:250
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8267
ArrayRef< TypeSourceInfo * > getArgs() const
Retrieve the argument types.
Definition ExprCXX.h:2961
TypeTrait getTrait() const
Determine which type trait this expression uses.
Definition ExprCXX.h:2933
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBooleanType() const
Definition TypeBase.h:9008
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isDependentAddressSpaceType() const
Definition TypeBase.h:8687
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:712
bool isArrayType() const
Definition TypeBase.h:8621
bool isPointerType() const
Definition TypeBase.h:8522
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
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:9165
bool isReferenceType() const
Definition TypeBase.h:8546
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:1909
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:471
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8847
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8645
bool isOpenCLSpecificType() const
Definition TypeBase.h:8812
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9151
bool isPointerOrReferenceType() const
Definition TypeBase.h:8526
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
bool isRecordType() const
Definition TypeBase.h:8649
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:1426
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3384
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3453
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4228
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4212
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4193
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:722
Represents a variable declaration or definition.
Definition Decl.h:925
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:4173
QualType getElementType() const
Definition TypeBase.h:4187
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:425
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_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:561
@ Concept
The name was classified as a concept name.
Definition Sema.h:588
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:1745
@ 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:87
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