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/Attr.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/Mangle.h"
20 #include "clang/AST/VTableBuilder.h"
21 #include "clang/Basic/ABI.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Mangler.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 
30 using namespace clang;
31 
32 // FIXME: For blocks we currently mimic GCC's mangling scheme, which leaves
33 // much to be desired. Come up with a better mangling scheme.
34 
35 static void mangleFunctionBlock(MangleContext &Context,
36                                 StringRef Outer,
37                                 const BlockDecl *BD,
38                                 raw_ostream &Out) {
39   unsigned discriminator = Context.getBlockId(BD, true);
40   if (discriminator == 0)
41     Out << "__" << Outer << "_block_invoke";
42   else
43     Out << "__" << Outer << "_block_invoke_" << discriminator+1;
44 }
45 
46 void MangleContext::anchor() { }
47 
48 enum CCMangling {
49   CCM_Other,
50   CCM_Fast,
51   CCM_RegCall,
52   CCM_Vector,
53   CCM_Std,
54   CCM_WasmMainArgcArgv
55 };
56 
57 static bool isExternC(const NamedDecl *ND) {
58   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
59     return FD->isExternC();
60   if (const VarDecl *VD = dyn_cast<VarDecl>(ND))
61     return VD->isExternC();
62   return false;
63 }
64 
65 static CCMangling getCallingConvMangling(const ASTContext &Context,
66                                          const NamedDecl *ND) {
67   const TargetInfo &TI = Context.getTargetInfo();
68   const llvm::Triple &Triple = TI.getTriple();
69 
70   // On wasm, the argc/argv form of "main" is renamed so that the startup code
71   // can call it with the correct function signature.
72   // On Emscripten, users may be exporting "main" and expecting to call it
73   // themselves, so we can't mangle it.
74   if (Triple.isWasm() && !Triple.isOSEmscripten())
75     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
76       if (FD->isMain() && FD->hasPrototype() && FD->param_size() == 2)
77         return CCM_WasmMainArgcArgv;
78 
79   if (!Triple.isOSWindows() || !Triple.isX86())
80     return CCM_Other;
81 
82   if (Context.getLangOpts().CPlusPlus && !isExternC(ND) &&
83       TI.getCXXABI() == TargetCXXABI::Microsoft)
84     return CCM_Other;
85 
86   const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
87   if (!FD)
88     return CCM_Other;
89   QualType T = FD->getType();
90 
91   const FunctionType *FT = T->castAs<FunctionType>();
92 
93   CallingConv CC = FT->getCallConv();
94   switch (CC) {
95   default:
96     return CCM_Other;
97   case CC_X86FastCall:
98     return CCM_Fast;
99   case CC_X86StdCall:
100     return CCM_Std;
101   case CC_X86VectorCall:
102     return CCM_Vector;
103   }
104 }
105 
106 bool MangleContext::shouldMangleDeclName(const NamedDecl *D) {
107   const ASTContext &ASTContext = getASTContext();
108 
109   CCMangling CC = getCallingConvMangling(ASTContext, D);
110   if (CC != CCM_Other)
111     return true;
112 
113   // If the declaration has an owning module for linkage purposes that needs to
114   // be mangled, we must mangle its name.
115   if (!D->hasExternalFormalLinkage() && D->getOwningModuleForLinkage())
116     return true;
117 
118   // In C, functions with no attributes never need to be mangled. Fastpath them.
119   if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
120     return false;
121 
122   // Any decl can be declared with __asm("foo") on it, and this takes precedence
123   // over all other naming in the .o file.
124   if (D->hasAttr<AsmLabelAttr>())
125     return true;
126 
127   // Declarations that don't have identifier names always need to be mangled.
128   if (isa<MSGuidDecl>(D))
129     return true;
130 
131   return shouldMangleCXXName(D);
132 }
133 
134 void MangleContext::mangleName(GlobalDecl GD, raw_ostream &Out) {
135   const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
136   // Any decl can be declared with __asm("foo") on it, and this takes precedence
137   // over all other naming in the .o file.
138   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
139     // If we have an asm name, then we use it as the mangling.
140 
141     // If the label isn't literal, or if this is an alias for an LLVM intrinsic,
142     // do not add a "\01" prefix.
143     if (!ALA->getIsLiteralLabel() || ALA->getLabel().startswith("llvm.")) {
144       Out << ALA->getLabel();
145       return;
146     }
147 
148     // Adding the prefix can cause problems when one file has a "foo" and
149     // another has a "\01foo". That is known to happen on ELF with the
150     // tricks normally used for producing aliases (PR9177). Fortunately the
151     // llvm mangler on ELF is a nop, so we can just avoid adding the \01
152     // marker.
153     char GlobalPrefix =
154         getASTContext().getTargetInfo().getDataLayout().getGlobalPrefix();
155     if (GlobalPrefix)
156       Out << '\01'; // LLVM IR Marker for __asm("foo")
157 
158     Out << ALA->getLabel();
159     return;
160   }
161 
162   if (auto *GD = dyn_cast<MSGuidDecl>(D))
163     return mangleMSGuidDecl(GD, Out);
164 
165   const ASTContext &ASTContext = getASTContext();
166   CCMangling CC = getCallingConvMangling(ASTContext, D);
167 
168   if (CC == CCM_WasmMainArgcArgv) {
169     Out << "__main_argc_argv";
170     return;
171   }
172 
173   bool MCXX = shouldMangleCXXName(D);
174   const TargetInfo &TI = Context.getTargetInfo();
175   if (CC == CCM_Other || (MCXX && TI.getCXXABI() == TargetCXXABI::Microsoft)) {
176     if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
177       mangleObjCMethodName(OMD, Out);
178     else
179       mangleCXXName(GD, Out);
180     return;
181   }
182 
183   Out << '\01';
184   if (CC == CCM_Std)
185     Out << '_';
186   else if (CC == CCM_Fast)
187     Out << '@';
188   else if (CC == CCM_RegCall)
189     Out << "__regcall3__";
190 
191   if (!MCXX)
192     Out << D->getIdentifier()->getName();
193   else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
194     mangleObjCMethodName(OMD, Out);
195   else
196     mangleCXXName(GD, Out);
197 
198   const FunctionDecl *FD = cast<FunctionDecl>(D);
199   const FunctionType *FT = FD->getType()->castAs<FunctionType>();
200   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT);
201   if (CC == CCM_Vector)
202     Out << '@';
203   Out << '@';
204   if (!Proto) {
205     Out << '0';
206     return;
207   }
208   assert(!Proto->isVariadic());
209   unsigned ArgWords = 0;
210   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
211     if (!MD->isStatic())
212       ++ArgWords;
213   for (const auto &AT : Proto->param_types())
214     // Size should be aligned to pointer size.
215     ArgWords +=
216         llvm::alignTo(ASTContext.getTypeSize(AT), TI.getPointerWidth(0)) /
217         TI.getPointerWidth(0);
218   Out << ((TI.getPointerWidth(0) / 8) * ArgWords);
219 }
220 
221 void MangleContext::mangleMSGuidDecl(const MSGuidDecl *GD, raw_ostream &Out) {
222   // For now, follow the MSVC naming convention for GUID objects on all
223   // targets.
224   MSGuidDecl::Parts P = GD->getParts();
225   Out << llvm::format("_GUID_%08" PRIx32 "_%04" PRIx32 "_%04" PRIx32 "_",
226                       P.Part1, P.Part2, P.Part3);
227   unsigned I = 0;
228   for (uint8_t C : P.Part4And5) {
229     Out << llvm::format("%02" PRIx8, C);
230     if (++I == 2)
231       Out << "_";
232   }
233 }
234 
235 void MangleContext::mangleGlobalBlock(const BlockDecl *BD,
236                                       const NamedDecl *ID,
237                                       raw_ostream &Out) {
238   unsigned discriminator = getBlockId(BD, false);
239   if (ID) {
240     if (shouldMangleDeclName(ID))
241       mangleName(ID, Out);
242     else {
243       Out << ID->getIdentifier()->getName();
244     }
245   }
246   if (discriminator == 0)
247     Out << "_block_invoke";
248   else
249     Out << "_block_invoke_" << discriminator+1;
250 }
251 
252 void MangleContext::mangleCtorBlock(const CXXConstructorDecl *CD,
253                                     CXXCtorType CT, const BlockDecl *BD,
254                                     raw_ostream &ResStream) {
255   SmallString<64> Buffer;
256   llvm::raw_svector_ostream Out(Buffer);
257   mangleName(GlobalDecl(CD, CT), Out);
258   mangleFunctionBlock(*this, Buffer, BD, ResStream);
259 }
260 
261 void MangleContext::mangleDtorBlock(const CXXDestructorDecl *DD,
262                                     CXXDtorType DT, const BlockDecl *BD,
263                                     raw_ostream &ResStream) {
264   SmallString<64> Buffer;
265   llvm::raw_svector_ostream Out(Buffer);
266   mangleName(GlobalDecl(DD, DT), Out);
267   mangleFunctionBlock(*this, Buffer, BD, ResStream);
268 }
269 
270 void MangleContext::mangleBlock(const DeclContext *DC, const BlockDecl *BD,
271                                 raw_ostream &Out) {
272   assert(!isa<CXXConstructorDecl>(DC) && !isa<CXXDestructorDecl>(DC));
273 
274   SmallString<64> Buffer;
275   llvm::raw_svector_ostream Stream(Buffer);
276   if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
277     mangleObjCMethodName(Method, Stream);
278   } else {
279     assert((isa<NamedDecl>(DC) || isa<BlockDecl>(DC)) &&
280            "expected a NamedDecl or BlockDecl");
281     if (isa<BlockDecl>(DC))
282       for (; DC && isa<BlockDecl>(DC); DC = DC->getParent())
283         (void) getBlockId(cast<BlockDecl>(DC), true);
284     assert((isa<TranslationUnitDecl>(DC) || isa<NamedDecl>(DC)) &&
285            "expected a TranslationUnitDecl or a NamedDecl");
286     if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
287       mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out);
288     else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
289       mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out);
290     else if (auto ND = dyn_cast<NamedDecl>(DC)) {
291       if (!shouldMangleDeclName(ND) && ND->getIdentifier())
292         Stream << ND->getIdentifier()->getName();
293       else {
294         // FIXME: We were doing a mangleUnqualifiedName() before, but that's
295         // a private member of a class that will soon itself be private to the
296         // Itanium C++ ABI object. What should we do now? Right now, I'm just
297         // calling the mangleName() method on the MangleContext; is there a
298         // better way?
299         mangleName(ND, Stream);
300       }
301     }
302   }
303   mangleFunctionBlock(*this, Buffer, BD, Out);
304 }
305 
306 void MangleContext::mangleObjCMethodNameWithoutSize(const ObjCMethodDecl *MD,
307                                                     raw_ostream &OS) {
308   const ObjCContainerDecl *CD =
309   dyn_cast<ObjCContainerDecl>(MD->getDeclContext());
310   assert (CD && "Missing container decl in GetNameForMethod");
311   OS << (MD->isInstanceMethod() ? '-' : '+') << '[';
312   if (const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(CD)) {
313     OS << CID->getClassInterface()->getName();
314     OS << '(' << *CID << ')';
315   } else {
316     OS << CD->getName();
317   }
318   OS << ' ';
319   MD->getSelector().print(OS);
320   OS << ']';
321 }
322 
323 void MangleContext::mangleObjCMethodName(const ObjCMethodDecl *MD,
324                                          raw_ostream &Out) {
325   SmallString<64> Name;
326   llvm::raw_svector_ostream OS(Name);
327 
328   mangleObjCMethodNameWithoutSize(MD, OS);
329   Out << OS.str().size() << OS.str();
330 }
331 
332 class ASTNameGenerator::Implementation {
333   std::unique_ptr<MangleContext> MC;
334   llvm::DataLayout DL;
335 
336 public:
337   explicit Implementation(ASTContext &Ctx)
338       : MC(Ctx.createMangleContext()), DL(Ctx.getTargetInfo().getDataLayout()) {
339   }
340 
341   bool writeName(const Decl *D, raw_ostream &OS) {
342     // First apply frontend mangling.
343     SmallString<128> FrontendBuf;
344     llvm::raw_svector_ostream FrontendBufOS(FrontendBuf);
345     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
346       if (FD->isDependentContext())
347         return true;
348       if (writeFuncOrVarName(FD, FrontendBufOS))
349         return true;
350     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
351       if (writeFuncOrVarName(VD, FrontendBufOS))
352         return true;
353     } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
354       MC->mangleObjCMethodNameWithoutSize(MD, OS);
355       return false;
356     } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
357       writeObjCClassName(ID, FrontendBufOS);
358     } else {
359       return true;
360     }
361 
362     // Now apply backend mangling.
363     llvm::Mangler::getNameWithPrefix(OS, FrontendBufOS.str(), DL);
364     return false;
365   }
366 
367   std::string getName(const Decl *D) {
368     std::string Name;
369     {
370       llvm::raw_string_ostream OS(Name);
371       writeName(D, OS);
372     }
373     return Name;
374   }
375 
376   enum ObjCKind {
377     ObjCClass,
378     ObjCMetaclass,
379   };
380 
381   static StringRef getClassSymbolPrefix(ObjCKind Kind,
382                                         const ASTContext &Context) {
383     if (Context.getLangOpts().ObjCRuntime.isGNUFamily())
384       return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_";
385     return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_";
386   }
387 
388   std::vector<std::string> getAllManglings(const ObjCContainerDecl *OCD) {
389     StringRef ClassName;
390     if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
391       ClassName = OID->getObjCRuntimeNameAsString();
392     else if (const auto *OID = dyn_cast<ObjCImplementationDecl>(OCD))
393       ClassName = OID->getObjCRuntimeNameAsString();
394 
395     if (ClassName.empty())
396       return {};
397 
398     auto Mangle = [&](ObjCKind Kind, StringRef ClassName) -> std::string {
399       SmallString<40> Mangled;
400       auto Prefix = getClassSymbolPrefix(Kind, OCD->getASTContext());
401       llvm::Mangler::getNameWithPrefix(Mangled, Prefix + ClassName, DL);
402       return std::string(Mangled.str());
403     };
404 
405     return {
406         Mangle(ObjCClass, ClassName),
407         Mangle(ObjCMetaclass, ClassName),
408     };
409   }
410 
411   std::vector<std::string> getAllManglings(const Decl *D) {
412     if (const auto *OCD = dyn_cast<ObjCContainerDecl>(D))
413       return getAllManglings(OCD);
414 
415     if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
416       return {};
417 
418     const NamedDecl *ND = cast<NamedDecl>(D);
419 
420     ASTContext &Ctx = ND->getASTContext();
421     std::unique_ptr<MangleContext> M(Ctx.createMangleContext());
422 
423     std::vector<std::string> Manglings;
424 
425     auto hasDefaultCXXMethodCC = [](ASTContext &C, const CXXMethodDecl *MD) {
426       auto DefaultCC = C.getDefaultCallingConvention(/*IsVariadic=*/false,
427                                                      /*IsCXXMethod=*/true);
428       auto CC = MD->getType()->castAs<FunctionProtoType>()->getCallConv();
429       return CC == DefaultCC;
430     };
431 
432     if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND)) {
433       Manglings.emplace_back(getMangledStructor(CD, Ctor_Base));
434 
435       if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily())
436         if (!CD->getParent()->isAbstract())
437           Manglings.emplace_back(getMangledStructor(CD, Ctor_Complete));
438 
439       if (Ctx.getTargetInfo().getCXXABI().isMicrosoft())
440         if (CD->hasAttr<DLLExportAttr>() && CD->isDefaultConstructor())
441           if (!(hasDefaultCXXMethodCC(Ctx, CD) && CD->getNumParams() == 0))
442             Manglings.emplace_back(getMangledStructor(CD, Ctor_DefaultClosure));
443     } else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND)) {
444       Manglings.emplace_back(getMangledStructor(DD, Dtor_Base));
445       if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily()) {
446         Manglings.emplace_back(getMangledStructor(DD, Dtor_Complete));
447         if (DD->isVirtual())
448           Manglings.emplace_back(getMangledStructor(DD, Dtor_Deleting));
449       }
450     } else if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(ND)) {
451       Manglings.emplace_back(getName(ND));
452       if (MD->isVirtual())
453         if (const auto *TIV = Ctx.getVTableContext()->getThunkInfo(MD))
454           for (const auto &T : *TIV)
455             Manglings.emplace_back(getMangledThunk(MD, T));
456     }
457 
458     return Manglings;
459   }
460 
461 private:
462   bool writeFuncOrVarName(const NamedDecl *D, raw_ostream &OS) {
463     if (MC->shouldMangleDeclName(D)) {
464       GlobalDecl GD;
465       if (const auto *CtorD = dyn_cast<CXXConstructorDecl>(D))
466         GD = GlobalDecl(CtorD, Ctor_Complete);
467       else if (const auto *DtorD = dyn_cast<CXXDestructorDecl>(D))
468         GD = GlobalDecl(DtorD, Dtor_Complete);
469       else if (D->hasAttr<CUDAGlobalAttr>())
470         GD = GlobalDecl(cast<FunctionDecl>(D));
471       else
472         GD = GlobalDecl(D);
473       MC->mangleName(GD, OS);
474       return false;
475     } else {
476       IdentifierInfo *II = D->getIdentifier();
477       if (!II)
478         return true;
479       OS << II->getName();
480       return false;
481     }
482   }
483 
484   void writeObjCClassName(const ObjCInterfaceDecl *D, raw_ostream &OS) {
485     OS << getClassSymbolPrefix(ObjCClass, D->getASTContext());
486     OS << D->getObjCRuntimeNameAsString();
487   }
488 
489   std::string getMangledStructor(const NamedDecl *ND, unsigned StructorType) {
490     std::string FrontendBuf;
491     llvm::raw_string_ostream FOS(FrontendBuf);
492 
493     GlobalDecl GD;
494     if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND))
495       GD = GlobalDecl(CD, static_cast<CXXCtorType>(StructorType));
496     else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND))
497       GD = GlobalDecl(DD, static_cast<CXXDtorType>(StructorType));
498     MC->mangleName(GD, FOS);
499 
500     std::string BackendBuf;
501     llvm::raw_string_ostream BOS(BackendBuf);
502 
503     llvm::Mangler::getNameWithPrefix(BOS, FOS.str(), DL);
504 
505     return BOS.str();
506   }
507 
508   std::string getMangledThunk(const CXXMethodDecl *MD, const ThunkInfo &T) {
509     std::string FrontendBuf;
510     llvm::raw_string_ostream FOS(FrontendBuf);
511 
512     MC->mangleThunk(MD, T, FOS);
513 
514     std::string BackendBuf;
515     llvm::raw_string_ostream BOS(BackendBuf);
516 
517     llvm::Mangler::getNameWithPrefix(BOS, FOS.str(), DL);
518 
519     return BOS.str();
520   }
521 };
522 
523 ASTNameGenerator::ASTNameGenerator(ASTContext &Ctx)
524     : Impl(std::make_unique<Implementation>(Ctx)) {}
525 
526 ASTNameGenerator::~ASTNameGenerator() {}
527 
528 bool ASTNameGenerator::writeName(const Decl *D, raw_ostream &OS) {
529   return Impl->writeName(D, OS);
530 }
531 
532 std::string ASTNameGenerator::getName(const Decl *D) {
533   return Impl->getName(D);
534 }
535 
536 std::vector<std::string> ASTNameGenerator::getAllManglings(const Decl *D) {
537   return Impl->getAllManglings(D);
538 }
539