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