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