1//===--- Mangle.cpp - Mangle C++ Names --------------------------*- 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 generic name mangling support for blocks and Objective-C.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/AST/Mangle.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/Attr.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/AST/VTableBuilder.h"
22#include "clang/Basic/ABI.h"
23#include "clang/Basic/Builtins.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Mangler.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/Format.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace clang;
33
34void clang::mangleObjCMethodName(raw_ostream &OS, bool includePrefixByte,
35 bool isInstanceMethod, StringRef ClassName,
36 std::optional<StringRef> CategoryName,
37 StringRef MethodName, bool useDirectABI) {
38 assert(
39 !(includePrefixByte && useDirectABI) &&
40 "includePrefixByte and useDirectABI shouldn't be set at the same time");
41 // \01+[ContainerName(CategoryName) SelectorName]
42 // Or for direct ABI: +[ContainerName(CategoryName) SelectorName]D
43 if (includePrefixByte)
44 OS << "\01";
45 OS << (isInstanceMethod ? '-' : '+');
46 OS << '[';
47 OS << ClassName;
48 if (CategoryName)
49 OS << "(" << *CategoryName << ")";
50 OS << " ";
51 OS << MethodName;
52 OS << ']';
53 if (useDirectABI)
54 OS << 'D';
55}
56
57// FIXME: For blocks we currently mimic GCC's mangling scheme, which leaves
58// much to be desired. Come up with a better mangling scheme.
59
60static void mangleFunctionBlock(MangleContext &Context,
61 StringRef Outer,
62 const BlockDecl *BD,
63 raw_ostream &Out) {
64 unsigned discriminator = Context.getBlockId(BD, Local: true);
65 if (discriminator == 0)
66 Out << "__" << Outer << "_block_invoke";
67 else
68 Out << "__" << Outer << "_block_invoke_" << discriminator+1;
69}
70
71void MangleContext::anchor() { }
72
73enum CCMangling {
74 CCM_Other,
75 CCM_Fast,
76 CCM_RegCall,
77 CCM_Vector,
78 CCM_Std,
79 CCM_WasmMainArgcArgv
80};
81
82static bool isExternC(const NamedDecl *ND) {
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: ND))
84 return FD->isExternC();
85 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: ND))
86 return VD->isExternC();
87 return false;
88}
89
90static CCMangling getCallingConvMangling(const ASTContext &Context,
91 const NamedDecl *ND) {
92 const TargetInfo &TI = Context.getTargetInfo();
93 const llvm::Triple &Triple = TI.getTriple();
94
95 // On wasm, the argc/argv form of "main" is renamed so that the startup code
96 // can call it with the correct function signature.
97 if (Triple.isWasm())
98 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: ND))
99 if (FD->isMain() && FD->getNumParams() == 2)
100 return CCM_WasmMainArgcArgv;
101
102 if (!TI.shouldUseMicrosoftCCforMangling())
103 return CCM_Other;
104
105 if (Context.getLangOpts().CPlusPlus && !isExternC(ND) &&
106 TI.getCXXABI() == TargetCXXABI::Microsoft)
107 return CCM_Other;
108
109 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: ND);
110 if (!FD)
111 return CCM_Other;
112 QualType T = FD->getType();
113
114 const FunctionType *FT = T->castAs<FunctionType>();
115
116 CallingConv CC = FT->getCallConv();
117 switch (CC) {
118 default:
119 return CCM_Other;
120 case CC_X86FastCall:
121 return CCM_Fast;
122 case CC_X86StdCall:
123 return CCM_Std;
124 case CC_X86VectorCall:
125 return CCM_Vector;
126 }
127}
128
129bool MangleContext::shouldMangleDeclName(const NamedDecl *D) {
130 // Any decl can be declared with __asm("foo") on it, and this takes precedence
131 // over all other naming in the .o file.
132 if (D->hasAttr<AsmLabelAttr>())
133 return true;
134
135 return shouldMangleDeclNameIgnoringAsmLabel(D);
136}
137
138bool MangleContext::shouldMangleDeclNameIgnoringAsmLabel(const NamedDecl *D) {
139 const ASTContext &ASTContext = getASTContext();
140
141 CCMangling CC = getCallingConvMangling(Context: ASTContext, ND: D);
142 if (CC != CCM_Other)
143 return true;
144
145 // If the declaration has an owning module for linkage purposes that needs to
146 // be mangled, we must mangle its name.
147 if (!D->hasExternalFormalLinkage() && D->getOwningModuleForLinkage())
148 return true;
149
150 // C functions with internal linkage have to be mangled with option
151 // -funique-internal-linkage-names.
152 if (!getASTContext().getLangOpts().CPlusPlus &&
153 isUniqueInternalLinkageDecl(ND: D))
154 return true;
155
156 // In C, functions with no attributes never need to be mangled. Fastpath them.
157 if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
158 return false;
159
160 // Declarations that don't have identifier names always need to be mangled.
161 if (isa<MSGuidDecl>(Val: D))
162 return true;
163
164 return shouldMangleCXXName(D);
165}
166
167namespace {
168// Visits a function body looking for a direct call back to the symbol the
169// function will link as. Detects both asm-label aliases and __builtin_*
170// wrappers (PR9614 / glibc btowc pattern).
171struct FunctionIsDirectlyRecursive
172 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
173 const StringRef Name;
174 const Builtin::Context &BI;
175 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
176 : Name(N), BI(C) {}
177
178 bool VisitCallExpr(const CallExpr *E) {
179 const FunctionDecl *FD = E->getDirectCallee();
180 if (!FD)
181 return false;
182 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
183 if (Attr && Name == Attr->getLabel())
184 return true;
185 unsigned BuiltinID = FD->getBuiltinID();
186 if (!BuiltinID || !BI.isLibFunction(ID: BuiltinID))
187 return false;
188 std::string BuiltinNameStr = BI.getName(ID: BuiltinID);
189 StringRef BuiltinName = BuiltinNameStr;
190 return BuiltinName.consume_front(Prefix: "__builtin_") && Name == BuiltinName;
191 }
192
193 bool VisitStmt(const Stmt *S) {
194 for (const Stmt *Child : S->children())
195 if (Child && this->Visit(S: Child))
196 return true;
197 return false;
198 }
199};
200} // namespace
201
202bool MangleContext::isTriviallyRecursive(const FunctionDecl *FD) {
203 StringRef Name;
204 if (shouldMangleDeclName(D: FD)) {
205 // C++-mangled functions can only recurse into themselves through an
206 // asm label that bypasses the mangled name.
207 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
208 if (!Attr)
209 return false;
210 Name = Attr->getLabel();
211 } else {
212 Name = FD->getName();
213 }
214
215 FunctionIsDirectlyRecursive Walker(Name, FD->getASTContext().BuiltinInfo);
216 const Stmt *Body = FD->getBody();
217 return Body ? Walker.Visit(S: Body) : false;
218}
219
220/// Given an LLDB function call label, this function prints the label
221/// into \c Out, together with the structor type of \c GD (if the
222/// decl is a constructor/destructor). LLDB knows how to handle mangled
223/// names with this encoding.
224///
225/// Example input label:
226/// $__lldb_func::123:456:~Foo
227///
228/// Example output:
229/// $__lldb_func:D1:123:456:~Foo
230///
231static void emitLLDBAsmLabel(llvm::StringRef label, GlobalDecl GD,
232 llvm::raw_ostream &Out) {
233 assert(label.starts_with(LLDBManglingABI::FunctionLabelPrefix));
234
235 Out << LLDBManglingABI::FunctionLabelPrefix;
236
237 if (auto *Ctor = llvm::dyn_cast<clang::CXXConstructorDecl>(Val: GD.getDecl())) {
238 Out << "C";
239 if (Ctor->getInheritedConstructor().getConstructor())
240 Out << "I";
241 Out << GD.getCtorType();
242 } else if (llvm::isa<clang::CXXDestructorDecl>(Val: GD.getDecl())) {
243 Out << "D" << GD.getDtorType();
244 }
245
246 Out << label.substr(Start: LLDBManglingABI::FunctionLabelPrefix.size());
247}
248
249void MangleContext::mangleName(GlobalDecl GD, raw_ostream &Out) {
250 const NamedDecl *D = cast<NamedDecl>(Val: GD.getDecl());
251
252 // Any decl can be declared with __asm("foo") on it, and this takes precedence
253 // over all other naming in the .o file.
254 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
255 // If we have an asm name, then we use it as the mangling.
256
257 // If the label is an alias for an LLVM intrinsic,
258 // do not add a "\01" prefix.
259 if (ALA->getLabel().starts_with(Prefix: "llvm.")) {
260 Out << ALA->getLabel();
261 return;
262 }
263
264 // Adding the prefix can cause problems when one file has a "foo" and
265 // another has a "\01foo". That is known to happen on ELF with the
266 // tricks normally used for producing aliases (PR9177). Fortunately the
267 // llvm mangler on ELF is a nop, so we can just avoid adding the \01
268 // marker.
269 StringRef UserLabelPrefix =
270 getASTContext().getTargetInfo().getUserLabelPrefix();
271#ifndef NDEBUG
272 char GlobalPrefix =
273 llvm::DataLayout(getASTContext().getTargetInfo().getDataLayoutString())
274 .getGlobalPrefix();
275 assert((UserLabelPrefix.empty() && !GlobalPrefix) ||
276 (UserLabelPrefix.size() == 1 && UserLabelPrefix[0] == GlobalPrefix));
277#endif
278 if (!UserLabelPrefix.empty())
279 Out << '\01'; // LLVM IR Marker for __asm("foo")
280
281 if (ALA->getLabel().starts_with(Prefix: LLDBManglingABI::FunctionLabelPrefix))
282 emitLLDBAsmLabel(label: ALA->getLabel(), GD, Out);
283 else
284 Out << ALA->getLabel();
285
286 return;
287 }
288
289 mangleNameIgnoringAsmLabel(GD, Out);
290}
291
292void MangleContext::mangleNameIgnoringAsmLabel(GlobalDecl GD,
293 raw_ostream &Out) {
294 const ASTContext &ASTContext = getASTContext();
295 const NamedDecl *D = cast<NamedDecl>(Val: GD.getDecl());
296
297 if (auto *GD = dyn_cast<MSGuidDecl>(Val: D))
298 return mangleMSGuidDecl(GD, Out);
299
300 CCMangling CC = getCallingConvMangling(Context: ASTContext, ND: D);
301
302 if (CC == CCM_WasmMainArgcArgv) {
303 Out << "__main_argc_argv";
304 return;
305 }
306
307 bool MCXX = shouldMangleCXXName(D);
308 const TargetInfo &TI = Context.getTargetInfo();
309 if (CC == CCM_Other || (MCXX && TI.getCXXABI() == TargetCXXABI::Microsoft)) {
310 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
311 mangleObjCMethodNameAsSourceName(MD: OMD, Out);
312 else
313 mangleCXXName(GD, Out);
314 return;
315 }
316
317 Out << '\01';
318 if (CC == CCM_Std)
319 Out << '_';
320 else if (CC == CCM_Fast)
321 Out << '@';
322 else if (CC == CCM_RegCall) {
323 if (getASTContext().getLangOpts().RegCall4)
324 Out << "__regcall4__";
325 else
326 Out << "__regcall3__";
327 }
328
329 if (!MCXX)
330 Out << D->getIdentifier()->getName();
331 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
332 mangleObjCMethodNameAsSourceName(MD: OMD, Out);
333 else
334 mangleCXXName(GD, Out);
335
336 const FunctionDecl *FD = cast<FunctionDecl>(Val: D);
337 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
338 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FT);
339 if (CC == CCM_Vector)
340 Out << '@';
341 Out << '@';
342 if (!Proto) {
343 Out << '0';
344 return;
345 }
346 assert(!Proto->isVariadic());
347 unsigned ArgWords = 0;
348 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
349 if (MD->isImplicitObjectMemberFunction())
350 ++ArgWords;
351 uint64_t DefaultPtrWidth = TI.getPointerWidth(AddrSpace: LangAS::Default);
352 for (const auto &AT : Proto->param_types()) {
353 // If an argument type is incomplete there is no way to get its size to
354 // correctly encode into the mangling scheme.
355 // Follow GCCs behaviour by simply breaking out of the loop.
356 if (AT->isIncompleteType())
357 break;
358 // Size should be aligned to pointer size.
359 ArgWords += llvm::alignTo(Value: ASTContext.getTypeSize(T: AT), Align: DefaultPtrWidth) /
360 DefaultPtrWidth;
361 }
362 Out << ((DefaultPtrWidth / 8) * ArgWords);
363}
364
365void MangleContext::mangleMSGuidDecl(const MSGuidDecl *GD,
366 raw_ostream &Out) const {
367 // For now, follow the MSVC naming convention for GUID objects on all
368 // targets.
369 MSGuidDecl::Parts P = GD->getParts();
370 Out << llvm::format(Fmt: "_GUID_%08" PRIx32 "_%04" PRIx32 "_%04" PRIx32 "_",
371 Vals: P.Part1, Vals: P.Part2, Vals: P.Part3);
372 unsigned I = 0;
373 for (uint8_t C : P.Part4And5) {
374 Out << llvm::format(Fmt: "%02" PRIx8, Vals: C);
375 if (++I == 2)
376 Out << "_";
377 }
378}
379
380void MangleContext::mangleGlobalBlock(const BlockDecl *BD,
381 const NamedDecl *ID,
382 raw_ostream &Out) {
383 unsigned discriminator = getBlockId(BD, Local: false);
384 if (ID) {
385 if (shouldMangleDeclName(D: ID))
386 mangleName(GD: ID, Out);
387 else {
388 Out << ID->getIdentifier()->getName();
389 }
390 }
391 if (discriminator == 0)
392 Out << "_block_invoke";
393 else
394 Out << "_block_invoke_" << discriminator+1;
395}
396
397void MangleContext::mangleCtorBlock(const CXXConstructorDecl *CD,
398 CXXCtorType CT, const BlockDecl *BD,
399 raw_ostream &ResStream) {
400 SmallString<64> Buffer;
401 llvm::raw_svector_ostream Out(Buffer);
402 mangleName(GD: GlobalDecl(CD, CT), Out);
403 mangleFunctionBlock(Context&: *this, Outer: Buffer, BD, Out&: ResStream);
404}
405
406void MangleContext::mangleDtorBlock(const CXXDestructorDecl *DD,
407 CXXDtorType DT, const BlockDecl *BD,
408 raw_ostream &ResStream) {
409 SmallString<64> Buffer;
410 llvm::raw_svector_ostream Out(Buffer);
411 mangleName(GD: GlobalDecl(DD, DT), Out);
412 mangleFunctionBlock(Context&: *this, Outer: Buffer, BD, Out&: ResStream);
413}
414
415void MangleContext::mangleBlock(const DeclContext *DC, const BlockDecl *BD,
416 raw_ostream &Out) {
417 assert(!isa<CXXConstructorDecl>(DC) && !isa<CXXDestructorDecl>(DC));
418
419 SmallString<64> Buffer;
420 llvm::raw_svector_ostream Stream(Buffer);
421 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Val: DC)) {
422 mangleObjCMethodNameAsSourceName(MD: Method, Stream);
423 } else {
424 assert((isa<NamedDecl>(DC) || isa<BlockDecl>(DC)) &&
425 "expected a NamedDecl or BlockDecl");
426 for (; isa_and_nonnull<BlockDecl>(Val: DC); DC = DC->getParent())
427 (void)getBlockId(BD: cast<BlockDecl>(Val: DC), Local: true);
428 assert((isa<TranslationUnitDecl>(DC) || isa<NamedDecl>(DC)) &&
429 "expected a TranslationUnitDecl or a NamedDecl");
430 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: DC))
431 mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, ResStream&: Out);
432 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: DC))
433 mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, ResStream&: Out);
434 else if (auto ND = dyn_cast<NamedDecl>(Val: DC)) {
435 if (!shouldMangleDeclName(D: ND) && ND->getIdentifier())
436 Stream << ND->getIdentifier()->getName();
437 else {
438 // FIXME: We were doing a mangleUnqualifiedName() before, but that's
439 // a private member of a class that will soon itself be private to the
440 // Itanium C++ ABI object. What should we do now? Right now, I'm just
441 // calling the mangleName() method on the MangleContext; is there a
442 // better way?
443 mangleName(GD: ND, Out&: Stream);
444 }
445 }
446 }
447 mangleFunctionBlock(Context&: *this, Outer: Buffer, BD, Out);
448}
449
450void MangleContext::mangleObjCMethodName(const ObjCMethodDecl *MD,
451 raw_ostream &OS,
452 bool includePrefixByte,
453 bool includeCategoryNamespace,
454 bool useDirectABI) const {
455 if (getASTContext().getLangOpts().ObjCRuntime.isGNUFamily()) {
456 // This is the mangling we've always used on the GNU runtimes, but it
457 // has obvious collisions in the face of underscores within class
458 // names, category names, and selectors; maybe we should improve it.
459
460 OS << (MD->isClassMethod() ? "_c_" : "_i_")
461 << MD->getClassInterface()->getName() << '_';
462
463 if (includeCategoryNamespace) {
464 if (auto category = MD->getCategory())
465 OS << category->getName();
466 }
467 OS << '_';
468
469 auto selector = MD->getSelector();
470 for (unsigned slotIndex = 0,
471 numArgs = selector.getNumArgs(),
472 slotEnd = std::max(a: numArgs, b: 1U);
473 slotIndex != slotEnd; ++slotIndex) {
474 if (auto name = selector.getIdentifierInfoForSlot(argIndex: slotIndex))
475 OS << name->getName();
476
477 // Replace all the positions that would've been ':' with '_'.
478 // That's after each slot except that a unary selector doesn't
479 // end in ':'.
480 if (numArgs)
481 OS << '_';
482 }
483
484 return;
485 }
486
487 // \01+[ContainerName(CategoryName) SelectorName]
488 auto CategoryName = std::optional<StringRef>();
489 StringRef ClassName = "";
490 if (const auto *CID = MD->getCategory()) {
491 if (const auto *CI = CID->getClassInterface()) {
492 ClassName = CI->getName();
493 if (includeCategoryNamespace) {
494 CategoryName = CID->getName();
495 }
496 }
497 } else if (const auto *CD =
498 dyn_cast<ObjCContainerDecl>(Val: MD->getDeclContext())) {
499 ClassName = CD->getName();
500 } else {
501 llvm_unreachable("Unexpected ObjC method decl context");
502 }
503 std::string MethodName;
504 llvm::raw_string_ostream MethodNameOS(MethodName);
505 MD->getSelector().print(OS&: MethodNameOS);
506 // Normal methods always have internal linkage, and we prefix them with '\01'
507 // for reasons that are somewhat lost to time. We suppress this for direct
508 // methods because they have non-internal linkage and we don't want to make it
509 // unnecessarily difficult to refer to them, e.g. in things like export lists.
510 // Direct methods also have a distinct ABI, so we add a suffix to make them
511 // obvious to tools like debuggers and to elevate incompatible uses into
512 // linker errors.
513 clang::mangleObjCMethodName(OS, includePrefixByte: includePrefixByte && !useDirectABI,
514 isInstanceMethod: MD->isInstanceMethod(), ClassName, CategoryName,
515 MethodName, useDirectABI);
516}
517
518void MangleContext::mangleObjCMethodNameAsSourceName(const ObjCMethodDecl *MD,
519 raw_ostream &Out) const {
520 SmallString<64> Name;
521 llvm::raw_svector_ostream OS(Name);
522
523 mangleObjCMethodName(MD, OS, /*includePrefixByte=*/false,
524 /*includeCategoryNamespace=*/true);
525 Out << OS.str().size() << OS.str();
526}
527
528class ASTNameGenerator::Implementation {
529 std::unique_ptr<MangleContext> MC;
530 llvm::DataLayout DL;
531
532public:
533 explicit Implementation(ASTContext &Ctx)
534 : MC(Ctx.createMangleContext()),
535 DL(Ctx.getTargetInfo().getDataLayoutString()) {}
536
537 bool writeName(const Decl *D, raw_ostream &OS) {
538 // First apply frontend mangling.
539 SmallString<128> FrontendBuf;
540 llvm::raw_svector_ostream FrontendBufOS(FrontendBuf);
541 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
542 if (FD->isDependentContext())
543 return true;
544 if (writeFuncOrVarName(D: FD, OS&: FrontendBufOS))
545 return true;
546 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
547 if (writeFuncOrVarName(D: VD, OS&: FrontendBufOS))
548 return true;
549 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
550 MC->mangleObjCMethodName(MD, OS, /*includePrefixByte=*/false,
551 /*includeCategoryNamespace=*/true);
552 return false;
553 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
554 writeObjCClassName(D: ID, OS&: FrontendBufOS);
555 } else {
556 return true;
557 }
558
559 // Now apply backend mangling.
560 llvm::Mangler::getNameWithPrefix(OS, GVName: FrontendBufOS.str(), DL);
561 return false;
562 }
563
564 std::string getName(const Decl *D) {
565 std::string Name;
566 {
567 llvm::raw_string_ostream OS(Name);
568 writeName(D, OS);
569 }
570 return Name;
571 }
572
573 enum ObjCKind {
574 ObjCClass,
575 ObjCMetaclass,
576 };
577
578 static StringRef getClassSymbolPrefix(ObjCKind Kind,
579 const ASTContext &Context) {
580 if (Context.getLangOpts().ObjCRuntime.isGNUFamily())
581 return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_";
582 return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_";
583 }
584
585 std::vector<std::string> getAllManglings(const ObjCContainerDecl *OCD) {
586 StringRef ClassName;
587 if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(Val: OCD))
588 ClassName = OID->getObjCRuntimeNameAsString();
589 else if (const auto *OID = dyn_cast<ObjCImplementationDecl>(Val: OCD))
590 ClassName = OID->getObjCRuntimeNameAsString();
591
592 if (ClassName.empty())
593 return {};
594
595 auto Mangle = [&](ObjCKind Kind, StringRef ClassName) -> std::string {
596 SmallString<40> Mangled;
597 auto Prefix = getClassSymbolPrefix(Kind, Context: OCD->getASTContext());
598 llvm::Mangler::getNameWithPrefix(OutName&: Mangled, GVName: Prefix + ClassName, DL);
599 return std::string(Mangled);
600 };
601
602 return {
603 Mangle(ObjCClass, ClassName),
604 Mangle(ObjCMetaclass, ClassName),
605 };
606 }
607
608 std::vector<std::string> getAllManglings(const Decl *D) {
609 if (const auto *OCD = dyn_cast<ObjCContainerDecl>(Val: D))
610 return getAllManglings(OCD);
611
612 if (!(isa<CXXRecordDecl>(Val: D) || isa<CXXMethodDecl>(Val: D)))
613 return {};
614
615 const NamedDecl *ND = cast<NamedDecl>(Val: D);
616
617 ASTContext &Ctx = ND->getASTContext();
618 std::unique_ptr<MangleContext> M(Ctx.createMangleContext());
619
620 std::vector<std::string> Manglings;
621
622 auto hasDefaultCXXMethodCC = [](ASTContext &C, const CXXMethodDecl *MD) {
623 auto DefaultCC = C.getDefaultCallingConvention(/*IsVariadic=*/false,
624 /*IsCXXMethod=*/true);
625 auto CC = MD->getType()->castAs<FunctionProtoType>()->getCallConv();
626 return CC == DefaultCC;
627 };
628
629 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Val: ND)) {
630 Manglings.emplace_back(args: getMangledStructor(ND: CD, StructorType: Ctor_Base));
631
632 if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily())
633 if (!CD->getParent()->isAbstract())
634 Manglings.emplace_back(args: getMangledStructor(ND: CD, StructorType: Ctor_Complete));
635
636 if (Ctx.getTargetInfo().getCXXABI().isMicrosoft())
637 if (CD->hasAttr<DLLExportAttr>() && CD->isDefaultConstructor())
638 if (!(hasDefaultCXXMethodCC(Ctx, CD) && CD->getNumParams() == 0))
639 Manglings.emplace_back(args: getMangledStructor(ND: CD, StructorType: Ctor_DefaultClosure));
640 } else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(Val: ND)) {
641 Manglings.emplace_back(args: getMangledStructor(ND: DD, StructorType: Dtor_Base));
642 if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily()) {
643 Manglings.emplace_back(args: getMangledStructor(ND: DD, StructorType: Dtor_Complete));
644 if (DD->isVirtual())
645 Manglings.emplace_back(args: getMangledStructor(ND: DD, StructorType: Dtor_Deleting));
646 }
647 } else if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: ND)) {
648 Manglings.emplace_back(args: getName(D: ND));
649 if (MD->isVirtual()) {
650 if (const auto *TIV = Ctx.getVTableContext()->getThunkInfo(GD: MD)) {
651 for (const auto &T : *TIV) {
652 std::string ThunkName;
653 std::string ContextualizedName =
654 getMangledThunk(MD, T, /* ElideOverrideInfo */ false);
655 if (Ctx.useAbbreviatedThunkName(VirtualMethodDecl: MD, MangledName: ContextualizedName))
656 ThunkName = getMangledThunk(MD, T, /* ElideOverrideInfo */ true);
657 else
658 ThunkName = ContextualizedName;
659 Manglings.emplace_back(args&: ThunkName);
660 }
661 }
662 }
663 }
664
665 return Manglings;
666 }
667
668private:
669 bool writeFuncOrVarName(const NamedDecl *D, raw_ostream &OS) {
670 if (MC->shouldMangleDeclName(D)) {
671 GlobalDecl GD;
672 if (const auto *CtorD = dyn_cast<CXXConstructorDecl>(Val: D))
673 GD = GlobalDecl(CtorD, Ctor_Complete);
674 else if (const auto *DtorD = dyn_cast<CXXDestructorDecl>(Val: D))
675 GD = GlobalDecl(DtorD, Dtor_Complete);
676 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
677 GD = FD->isReferenceableKernel() ? GlobalDecl(FD) : GlobalDecl(D);
678 } else
679 GD = GlobalDecl(D);
680 MC->mangleName(GD, Out&: OS);
681 return false;
682 } else {
683 IdentifierInfo *II = D->getIdentifier();
684 if (!II)
685 return true;
686 OS << II->getName();
687 return false;
688 }
689 }
690
691 void writeObjCClassName(const ObjCInterfaceDecl *D, raw_ostream &OS) {
692 OS << getClassSymbolPrefix(Kind: ObjCClass, Context: D->getASTContext());
693 OS << D->getObjCRuntimeNameAsString();
694 }
695
696 std::string getMangledStructor(const NamedDecl *ND, unsigned StructorType) {
697 std::string FrontendBuf;
698 llvm::raw_string_ostream FOS(FrontendBuf);
699
700 GlobalDecl GD;
701 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Val: ND))
702 GD = GlobalDecl(CD, static_cast<CXXCtorType>(StructorType));
703 else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(Val: ND))
704 GD = GlobalDecl(DD, static_cast<CXXDtorType>(StructorType));
705 MC->mangleName(GD, Out&: FOS);
706
707 std::string BackendBuf;
708 llvm::raw_string_ostream BOS(BackendBuf);
709
710 llvm::Mangler::getNameWithPrefix(OS&: BOS, GVName: FrontendBuf, DL);
711
712 return BackendBuf;
713 }
714
715 std::string getMangledThunk(const CXXMethodDecl *MD, const ThunkInfo &T,
716 bool ElideOverrideInfo) {
717 std::string FrontendBuf;
718 llvm::raw_string_ostream FOS(FrontendBuf);
719
720 MC->mangleThunk(MD, Thunk: T, ElideOverrideInfo, FOS);
721
722 std::string BackendBuf;
723 llvm::raw_string_ostream BOS(BackendBuf);
724
725 llvm::Mangler::getNameWithPrefix(OS&: BOS, GVName: FrontendBuf, DL);
726
727 return BackendBuf;
728 }
729};
730
731ASTNameGenerator::ASTNameGenerator(ASTContext &Ctx)
732 : Impl(std::make_unique<Implementation>(args&: Ctx)) {}
733
734ASTNameGenerator::~ASTNameGenerator() {}
735
736bool ASTNameGenerator::writeName(const Decl *D, raw_ostream &OS) {
737 return Impl->writeName(D, OS);
738}
739
740std::string ASTNameGenerator::getName(const Decl *D) {
741 return Impl->getName(D);
742}
743
744std::vector<std::string> ASTNameGenerator::getAllManglings(const Decl *D) {
745 return Impl->getAllManglings(D);
746}
747