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