1 //===--- Mangle.cpp - Mangle C++ Names --------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implements generic name mangling support for blocks and Objective-C.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/Attr.h"
14 #include "clang/AST/ASTContext.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/Mangle.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/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 
28 #define MANGLE_CHECKER 0
29 
30 #if MANGLE_CHECKER
31 #include <cxxabi.h>
32 #endif
33 
34 using namespace clang;
35 
36 // FIXME: For blocks we currently mimic GCC's mangling scheme, which leaves
37 // much to be desired. Come up with a better mangling scheme.
38 
39 static void mangleFunctionBlock(MangleContext &Context,
40                                 StringRef Outer,
41                                 const BlockDecl *BD,
42                                 raw_ostream &Out) {
43   unsigned discriminator = Context.getBlockId(BD, true);
44   if (discriminator == 0)
45     Out << "__" << Outer << "_block_invoke";
46   else
47     Out << "__" << Outer << "_block_invoke_" << discriminator+1;
48 }
49 
50 void MangleContext::anchor() { }
51 
52 enum StdOrFastCC {
53   SOF_OTHER,
54   SOF_FAST,
55   SOF_STD
56 };
57 
58 static bool isExternC(const NamedDecl *ND) {
59   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
60     return FD->isExternC();
61   return cast<VarDecl>(ND)->isExternC();
62 }
63 
64 static StdOrFastCC getStdOrFastCallMangling(const ASTContext &Context,
65                                             const NamedDecl *ND) {
66   const TargetInfo &TI = Context.getTargetInfo();
67   const llvm::Triple &Triple = TI.getTriple();
68   if (!Triple.isOSWindows() || Triple.getArch() != llvm::Triple::x86)
69     return SOF_OTHER;
70 
71   if (Context.getLangOpts().CPlusPlus && !isExternC(ND) &&
72       TI.getCXXABI() == TargetCXXABI::Microsoft)
73     return SOF_OTHER;
74 
75   const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
76   if (!FD)
77     return SOF_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 SOF_OTHER;
86   case CC_X86FastCall:
87     return SOF_FAST;
88   case CC_X86StdCall:
89     return SOF_STD;
90   }
91 }
92 
93 bool MangleContext::shouldMangleDeclName(const NamedDecl *D) {
94   const ASTContext &ASTContext = getASTContext();
95 
96   StdOrFastCC CC = getStdOrFastCallMangling(ASTContext, D);
97   if (CC != SOF_OTHER)
98     return true;
99 
100   // In C, functions with no attributes never need to be mangled. Fastpath them.
101   if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
102     return false;
103 
104   // Any decl can be declared with __asm("foo") on it, and this takes precedence
105   // over all other naming in the .o file.
106   if (D->hasAttr<AsmLabelAttr>())
107     return true;
108 
109   return shouldMangleCXXName(D);
110 }
111 
112 void MangleContext::mangleName(const NamedDecl *D, raw_ostream &Out) {
113   // Any decl can be declared with __asm("foo") on it, and this takes precedence
114   // over all other naming in the .o file.
115   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
116     // If we have an asm name, then we use it as the mangling.
117 
118     // Adding the prefix can cause problems when one file has a "foo" and
119     // another has a "\01foo". That is known to happen on ELF with the
120     // tricks normally used for producing aliases (PR9177). Fortunately the
121     // llvm mangler on ELF is a nop, so we can just avoid adding the \01
122     // marker.  We also avoid adding the marker if this is an alias for an
123     // LLVM intrinsic.
124     StringRef UserLabelPrefix =
125         getASTContext().getTargetInfo().getUserLabelPrefix();
126     if (!UserLabelPrefix.empty() && !ALA->getLabel().startswith("llvm."))
127       Out << '\01'; // LLVM IR Marker for __asm("foo")
128 
129     Out << ALA->getLabel();
130     return;
131   }
132 
133   const ASTContext &ASTContext = getASTContext();
134   StdOrFastCC CC = getStdOrFastCallMangling(ASTContext, D);
135   bool MCXX = shouldMangleCXXName(D);
136   const TargetInfo &TI = Context.getTargetInfo();
137   if (CC == SOF_OTHER || (MCXX && TI.getCXXABI() == TargetCXXABI::Microsoft)) {
138     if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
139       mangleObjCMethodName(OMD, Out);
140     else
141       mangleCXXName(D, Out);
142     return;
143   }
144 
145   Out << '\01';
146   if (CC == SOF_STD)
147     Out << '_';
148   else
149     Out << '@';
150 
151   if (!MCXX)
152     Out << D->getIdentifier()->getName();
153   else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
154     mangleObjCMethodName(OMD, Out);
155   else
156     mangleCXXName(D, Out);
157 
158   const FunctionDecl *FD = cast<FunctionDecl>(D);
159   const FunctionType *FT = FD->getType()->castAs<FunctionType>();
160   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT);
161   Out << '@';
162   if (!Proto) {
163     Out << '0';
164     return;
165   }
166   assert(!Proto->isVariadic());
167   unsigned ArgWords = 0;
168   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
169     if (!MD->isStatic())
170       ++ArgWords;
171   for (const auto &AT : Proto->param_types())
172     // Size should be aligned to DWORD boundary
173     ArgWords += llvm::RoundUpToAlignment(ASTContext.getTypeSize(AT), 32) / 32;
174   Out << 4 * ArgWords;
175 }
176 
177 void MangleContext::mangleGlobalBlock(const BlockDecl *BD,
178                                       const NamedDecl *ID,
179                                       raw_ostream &Out) {
180   unsigned discriminator = getBlockId(BD, false);
181   if (ID) {
182     if (shouldMangleDeclName(ID))
183       mangleName(ID, Out);
184     else {
185       Out << ID->getIdentifier()->getName();
186     }
187   }
188   if (discriminator == 0)
189     Out << "_block_invoke";
190   else
191     Out << "_block_invoke_" << discriminator+1;
192 }
193 
194 void MangleContext::mangleCtorBlock(const CXXConstructorDecl *CD,
195                                     CXXCtorType CT, const BlockDecl *BD,
196                                     raw_ostream &ResStream) {
197   SmallString<64> Buffer;
198   llvm::raw_svector_ostream Out(Buffer);
199   mangleCXXCtor(CD, CT, Out);
200   Out.flush();
201   mangleFunctionBlock(*this, Buffer, BD, ResStream);
202 }
203 
204 void MangleContext::mangleDtorBlock(const CXXDestructorDecl *DD,
205                                     CXXDtorType DT, const BlockDecl *BD,
206                                     raw_ostream &ResStream) {
207   SmallString<64> Buffer;
208   llvm::raw_svector_ostream Out(Buffer);
209   mangleCXXDtor(DD, DT, Out);
210   Out.flush();
211   mangleFunctionBlock(*this, Buffer, BD, ResStream);
212 }
213 
214 void MangleContext::mangleBlock(const DeclContext *DC, const BlockDecl *BD,
215                                 raw_ostream &Out) {
216   assert(!isa<CXXConstructorDecl>(DC) && !isa<CXXDestructorDecl>(DC));
217 
218   SmallString<64> Buffer;
219   llvm::raw_svector_ostream Stream(Buffer);
220   if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
221     mangleObjCMethodName(Method, Stream);
222   } else {
223     assert((isa<NamedDecl>(DC) || isa<BlockDecl>(DC)) &&
224            "expected a NamedDecl or BlockDecl");
225     if (isa<BlockDecl>(DC))
226       for (; DC && isa<BlockDecl>(DC); DC = DC->getParent())
227         (void) getBlockId(cast<BlockDecl>(DC), true);
228     assert(isa<NamedDecl>(DC) && "expected a NamedDecl");
229     const NamedDecl *ND = cast<NamedDecl>(DC);
230     if (!shouldMangleDeclName(ND) && ND->getIdentifier())
231       Stream << ND->getIdentifier()->getName();
232     else {
233       // FIXME: We were doing a mangleUnqualifiedName() before, but that's
234       // a private member of a class that will soon itself be private to the
235       // Itanium C++ ABI object. What should we do now? Right now, I'm just
236       // calling the mangleName() method on the MangleContext; is there a
237       // better way?
238       mangleName(ND, Stream);
239     }
240   }
241   Stream.flush();
242   mangleFunctionBlock(*this, Buffer, BD, Out);
243 }
244 
245 void MangleContext::mangleObjCMethodName(const ObjCMethodDecl *MD,
246                                          raw_ostream &Out) {
247   SmallString<64> Name;
248   llvm::raw_svector_ostream OS(Name);
249 
250   const ObjCContainerDecl *CD =
251   dyn_cast<ObjCContainerDecl>(MD->getDeclContext());
252   assert (CD && "Missing container decl in GetNameForMethod");
253   OS << (MD->isInstanceMethod() ? '-' : '+') << '[' << CD->getName();
254   if (const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(CD))
255     OS << '(' << *CID << ')';
256   OS << ' ';
257   MD->getSelector().print(OS);
258   OS << ']';
259 
260   Out << OS.str().size() << OS.str();
261 }
262