blob: a97ac58dd7815c73e7e2ffac7eca819d35526b44 [file] [log] [blame]
Douglas Gregor5f2bfd42009-02-13 00:10:09 +00001//===--------------------- Mangle.cpp - Mangle C++ Names ------------------===//
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 C++ name mangling according to the Itanium C++ ABI,
11// which is used in GCC 3.2 and newer (and many compilers that are
12// ABI-compatible with GCC):
13//
14// http://www.codesourcery.com/public/cxx-abi/abi.html
15//
16//===----------------------------------------------------------------------===//
17#include "Mangle.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/Support/raw_ostream.h"
23using namespace clang;
24
25namespace {
26 class VISIBILITY_HIDDEN CXXNameMangler {
27 ASTContext &Context;
28 llvm::raw_ostream &Out;
29
30 public:
31 CXXNameMangler(ASTContext &C, llvm::raw_ostream &os)
32 : Context(C), Out(os) { }
33
34 bool mangle(const NamedDecl *D);
35 void mangleFunctionEncoding(const FunctionDecl *FD);
36 void mangleName(const NamedDecl *ND);
37 void mangleUnqualifiedName(const NamedDecl *ND);
38 void mangleSourceName(const IdentifierInfo *II);
39 void mangleNestedName(const NamedDecl *ND);
40 void manglePrefix(const DeclContext *DC);
41 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
42 void mangleCVQualifiers(unsigned Quals);
43 void mangleType(QualType T);
44 void mangleType(const BuiltinType *T);
45 void mangleType(const FunctionType *T);
46 void mangleBareFunctionType(const FunctionType *T, bool MangleReturnType);
47 void mangleType(const TagType *T);
48 void mangleType(const ArrayType *T);
49 void mangleType(const MemberPointerType *T);
50 void mangleType(const TemplateTypeParmType *T);
51 void mangleExpression(Expr *E);
52 };
53}
54
55
56bool CXXNameMangler::mangle(const NamedDecl *D) {
57 // <mangled-name> ::= _Z <encoding>
58 // ::= <data name>
59 // ::= <special-name>
60
61 // FIXME: Actually use a visitor to decode these?
62 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
63 bool RequiresMangling = false;
64 // Clang's "overloadable" attribute extension to C/C++
65 if (FD->getAttr<OverloadableAttr>())
66 RequiresMangling = true;
67 else if (Context.getLangOptions().CPlusPlus) {
68 RequiresMangling = true;
69 if (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
70 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage()
71 == LinkageSpecDecl::lang_c) {
72 // Entities with C linkage are not mangled.
73 RequiresMangling = false;
74 }
75 }
76
77 if (RequiresMangling) {
78 Out << "_Z";
79 mangleFunctionEncoding(FD);
80 return true;
81 }
82 }
83
84 return false;
85}
86
87void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
88 // <encoding> ::= <function name> <bare-function-type>
89 mangleName(FD);
90 mangleBareFunctionType(FD->getType()->getAsFunctionType(), false);
91}
92
93static bool isStdNamespace(const DeclContext *DC) {
94 if (!DC->isNamespace() || !DC->getParent()->isTranslationUnit())
95 return false;
96
97 const NamespaceDecl *NS = cast<NamespaceDecl>(DC);
98 const IdentifierInfo *Name = NS->getIdentifier();
99 if (Name->getLength() != 3)
100 return false;
101
102 const char *Str = Name->getName();
103 if (Str[0] != 's' || Str[1] != 't' || Str[2] != 'd')
104 return false;
105
106 return true;
107}
108
109void CXXNameMangler::mangleName(const NamedDecl *ND) {
110 // <name> ::= <nested-name>
111 // ::= <unscoped-name>
112 // ::= <unscoped-template-name> <template-args>
113 // ::= <local-name> # See Scope Encoding below
114 //
115 // <unscoped-name> ::= <unqualified-name>
116 // ::= St <unqualified-name> # ::std::
117 if (ND->getDeclContext()->isTranslationUnit())
118 mangleUnqualifiedName(ND);
119 else if (isStdNamespace(ND->getDeclContext())) {
120 Out << "St";
121 mangleUnqualifiedName(ND);
122 } else {
123 mangleNestedName(ND);
124 }
125}
126
127void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND) {
128 // <unqualified-name> ::= <operator-name>
129 // ::= <ctor-dtor-name>
130 // ::= <source-name>
131 DeclarationName Name = ND->getDeclName();
132 switch (Name.getNameKind()) {
133 case DeclarationName::Identifier:
134 mangleSourceName(Name.getAsIdentifierInfo());
135 break;
136
137 case DeclarationName::ObjCZeroArgSelector:
138 case DeclarationName::ObjCOneArgSelector:
139 case DeclarationName::ObjCMultiArgSelector:
140 assert(false && "Can't mangle Objective-C selector names here!");
141 break;
142
143 case DeclarationName::CXXConstructorName:
144 // <ctor-dtor-name> ::= C1 # complete object constructor
145 // ::= C2 # base object constructor
146 // ::= C3 # complete object allocating constructor
147 //
148 // FIXME: We don't even have all of these constructors
149 // in the AST yet.
150 Out << "C1";
151 break;
152
153 case DeclarationName::CXXDestructorName:
154 // <ctor-dtor-name> ::= D0 # deleting destructor
155 // ::= D1 # complete object destructor
156 // ::= D2 # base object destructor
157 //
158 // FIXME: We don't even have all of these destructors in the AST
159 // yet.
160 Out << "D0";
161 break;
162
163 case DeclarationName::CXXConversionFunctionName:
164 assert(false && "Not sure how to mangle conversion functions yet");
165 break;
166
167 case DeclarationName::CXXOperatorName:
168 mangleOperatorName(Name.getCXXOverloadedOperator(),
169 cast<FunctionDecl>(ND)->getNumParams());
170 break;
171
172 case DeclarationName::CXXUsingDirective:
173 assert(false && "Can't mangle a using directive name!");
174 }
175}
176
177void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
178 // <source-name> ::= <positive length number> <identifier>
179 // <number> ::= [n] <non-negative decimal integer>
180 // <identifier> ::= <unqualified source code identifier>
181 Out << II->getLength() << II->getName();
182}
183
184void CXXNameMangler::mangleNestedName(const NamedDecl *ND) {
185 // <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E
186 // ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
187 // FIXME: no template support
188 Out << 'N';
189 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND))
190 mangleCVQualifiers(Method->getTypeQualifiers());
191 manglePrefix(ND->getDeclContext());
192 mangleUnqualifiedName(ND);
193 Out << 'E';
194}
195
196void CXXNameMangler::manglePrefix(const DeclContext *DC) {
197 // <prefix> ::= <prefix> <unqualified-name>
198 // ::= <template-prefix> <template-args>
199 // ::= <template-param>
200 // ::= # empty
201 // ::= <substitution>
202 // FIXME: We only handle mangling of namespaces and classes at the moment.
203 if (DC->getParent() != DC)
204 manglePrefix(DC);
205
206 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC))
207 mangleSourceName(Namespace->getIdentifier());
208 else if (const RecordDecl *Record = dyn_cast<RecordDecl>(DC))
209 mangleSourceName(Record->getIdentifier());
210}
211
212void
213CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
214 switch (OO) {
215 // <operator-name> ::= nw # new
216 case OO_New: Out << "nw"; break;
217 // ::= na # new[]
218 case OO_Array_New: Out << "na"; break;
219 // ::= dl # delete
220 case OO_Delete: Out << "dl"; break;
221 // ::= da # delete[]
222 case OO_Array_Delete: Out << "da"; break;
223 // ::= ps # + (unary)
224 // ::= pl # +
225 case OO_Plus: Out << (Arity == 1? "ps" : "pl"); break;
226 // ::= ng # - (unary)
227 // ::= mi # -
228 case OO_Minus: Out << (Arity == 1? "ng" : "mi"); break;
229 // ::= ad # & (unary)
230 // ::= an # &
231 case OO_Amp: Out << (Arity == 1? "ad" : "an"); break;
232 // ::= de # * (unary)
233 // ::= ml # *
234 case OO_Star: Out << (Arity == 1? "de" : "ml"); break;
235 // ::= co # ~
236 case OO_Tilde: Out << "co"; break;
237 // ::= dv # /
238 case OO_Slash: Out << "dv"; break;
239 // ::= rm # %
240 case OO_Percent: Out << "rm"; break;
241 // ::= or # |
242 case OO_Pipe: Out << "or"; break;
243 // ::= eo # ^
244 case OO_Caret: Out << "eo"; break;
245 // ::= aS # =
246 case OO_Equal: Out << "aS"; break;
247 // ::= pL # +=
248 case OO_PlusEqual: Out << "pL"; break;
249 // ::= mI # -=
250 case OO_MinusEqual: Out << "mI"; break;
251 // ::= mL # *=
252 case OO_StarEqual: Out << "mL"; break;
253 // ::= dV # /=
254 case OO_SlashEqual: Out << "dV"; break;
255 // ::= rM # %=
256 case OO_PercentEqual: Out << "rM"; break;
257 // ::= aN # &=
258 case OO_AmpEqual: Out << "aN"; break;
259 // ::= oR # |=
260 case OO_PipeEqual: Out << "oR"; break;
261 // ::= eO # ^=
262 case OO_CaretEqual: Out << "eO"; break;
263 // ::= ls # <<
264 case OO_LessLess: Out << "ls"; break;
265 // ::= rs # >>
266 case OO_GreaterGreater: Out << "rs"; break;
267 // ::= lS # <<=
268 case OO_LessLessEqual: Out << "lS"; break;
269 // ::= rS # >>=
270 case OO_GreaterGreaterEqual: Out << "rS"; break;
271 // ::= eq # ==
272 case OO_EqualEqual: Out << "eq"; break;
273 // ::= ne # !=
274 case OO_ExclaimEqual: Out << "ne"; break;
275 // ::= lt # <
276 case OO_Less: Out << "lt"; break;
277 // ::= gt # >
278 case OO_Greater: Out << "gt"; break;
279 // ::= le # <=
280 case OO_LessEqual: Out << "le"; break;
281 // ::= ge # >=
282 case OO_GreaterEqual: Out << "ge"; break;
283 // ::= nt # !
284 case OO_Exclaim: Out << "nt"; break;
285 // ::= aa # &&
286 case OO_AmpAmp: Out << "aa"; break;
287 // ::= oo # ||
288 case OO_PipePipe: Out << "oo"; break;
289 // ::= pp # ++
290 case OO_PlusPlus: Out << "pp"; break;
291 // ::= mm # --
292 case OO_MinusMinus: Out << "mm"; break;
293 // ::= cm # ,
294 case OO_Comma: Out << "cm"; break;
295 // ::= pm # ->*
296 case OO_ArrowStar: Out << "pm"; break;
297 // ::= pt # ->
298 case OO_Arrow: Out << "pt"; break;
299 // ::= cl # ()
300 case OO_Call: Out << "cl"; break;
301 // ::= ix # []
302 case OO_Subscript: Out << "ix"; break;
303 // UNSUPPORTED: ::= qu # ?
304
305 case OO_None:
306 case NUM_OVERLOADED_OPERATORS:
307 assert(false && "Not an ovelroaded operator");
308 break;
309 }
310}
311
312void CXXNameMangler::mangleCVQualifiers(unsigned Quals) {
313 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
314 if (Quals & QualType::Restrict)
315 Out << 'r';
316 if (Quals & QualType::Volatile)
317 Out << 'V';
318 if (Quals & QualType::Const)
319 Out << 'K';
320}
321
322void CXXNameMangler::mangleType(QualType T) {
323 // Only operate on the canonical type!
324 T = Context.getCanonicalType(T);
325
326 // FIXME: Should we have a TypeNodes.def to make this easier? (YES!)
327
328 // <type> ::= <CV-qualifiers> <type>
329 mangleCVQualifiers(T.getCVRQualifiers());
330
331 // ::= <builtin-type>
332 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr()))
333 mangleType(BT);
334 // ::= <function-type>
335 else if (const FunctionType *FT = dyn_cast<FunctionType>(T.getTypePtr()))
336 mangleType(FT);
337 // ::= <class-enum-type>
338 else if (const TagType *TT = dyn_cast<TagType>(T.getTypePtr()))
339 mangleType(TT);
340 // ::= <array-type>
341 else if (const ArrayType *AT = dyn_cast<ArrayType>(T.getTypePtr()))
342 mangleType(AT);
343 // ::= <pointer-to-member-type>
344 else if (const MemberPointerType *MPT
345 = dyn_cast<MemberPointerType>(T.getTypePtr()))
346 mangleType(MPT);
347 // ::= <template-param>
348 else if (const TemplateTypeParmType *TypeParm
349 = dyn_cast<TemplateTypeParmType>(T.getTypePtr()))
350 mangleType(TypeParm);
351 // FIXME: ::= <template-template-param> <template-args>
352 // FIXME: ::= <substitution> # See Compression below
353 // ::= P <type> # pointer-to
354 else if (const PointerType *PT = dyn_cast<PointerType>(T.getTypePtr())) {
355 Out << 'P';
356 mangleType(PT->getPointeeType());
357 }
358 // ::= R <type> # reference-to
359 // ::= O <type> # rvalue reference-to (C++0x)
360 else if (const ReferenceType *RT = dyn_cast<ReferenceType>(T.getTypePtr())) {
361 // FIXME: rvalue references
362 Out << 'R';
363 mangleType(RT->getPointeeType());
364 }
365 // ::= C <type> # complex pair (C 2000)
366 else if (const ComplexType *CT = dyn_cast<ComplexType>(T.getTypePtr())) {
367 Out << 'C';
368 mangleType(CT->getElementType());
369 } else if (const VectorType *VT = dyn_cast<VectorType>(T.getTypePtr())) {
370 // GNU extension: vector types
371 Out << "U8__vector";
372 mangleType(VT->getElementType());
373 }
374 // FIXME: ::= G <type> # imaginary (C 2000)
375 // FIXME: ::= U <source-name> <type> # vendor extended type qualifier
376 else
377 assert(false && "Cannot mangle unknown type");
378}
379
380void CXXNameMangler::mangleType(const BuiltinType *T) {
381 // <builtin-type> ::= v # void
382 // ::= w # wchar_t
383 // ::= b # bool
384 // ::= c # char
385 // ::= a # signed char
386 // ::= h # unsigned char
387 // ::= s # short
388 // ::= t # unsigned short
389 // ::= i # int
390 // ::= j # unsigned int
391 // ::= l # long
392 // ::= m # unsigned long
393 // ::= x # long long, __int64
394 // ::= y # unsigned long long, __int64
395 // ::= n # __int128
396 // UNSUPPORTED: ::= o # unsigned __int128
397 // ::= f # float
398 // ::= d # double
399 // ::= e # long double, __float80
400 // UNSUPPORTED: ::= g # __float128
401 // NOT HERE: ::= z # ellipsis
402 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
403 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
404 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
405 // UNSUPPORTED: ::= Dh # IEEE 754r half-precision floating point (16 bits)
406 // UNSUPPORTED: ::= Di # char32_t
407 // UNSUPPORTED: ::= Ds # char16_t
408 // ::= u <source-name> # vendor extended type
409 switch (T->getKind()) {
410 case BuiltinType::Void: Out << 'v'; break;
411 case BuiltinType::Bool: Out << 'b'; break;
412 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
413 case BuiltinType::UChar: Out << 'h'; break;
414 case BuiltinType::UShort: Out << 't'; break;
415 case BuiltinType::UInt: Out << 'j'; break;
416 case BuiltinType::ULong: Out << 'm'; break;
417 case BuiltinType::ULongLong: Out << 'y'; break;
418 case BuiltinType::SChar: Out << 'a'; break;
419 case BuiltinType::WChar: Out << 'w'; break;
420 case BuiltinType::Short: Out << 's'; break;
421 case BuiltinType::Int: Out << 'i'; break;
422 case BuiltinType::Long: Out << 'l'; break;
423 case BuiltinType::LongLong: Out << 'x'; break;
424 case BuiltinType::Float: Out << 'f'; break;
425 case BuiltinType::Double: Out << 'd'; break;
426 case BuiltinType::LongDouble: Out << 'e'; break;
427
428 case BuiltinType::Overload:
429 case BuiltinType::Dependent:
430 assert(false &&
431 "Overloaded and dependent types shouldn't get to name mangling");
432 break;
433 }
434}
435
436void CXXNameMangler::mangleType(const FunctionType *T) {
437 // <function-type> ::= F [Y] <bare-function-type> E
438 Out << 'F';
439 // FIXME: We don't have enough information in the AST to produce the
440 // 'Y' encoding for extern "C" function types.
441 mangleBareFunctionType(T, /*MangleReturnType=*/true);
442 Out << 'E';
443}
444
445void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
446 bool MangleReturnType) {
447 // <bare-function-type> ::= <signature type>+
448 if (MangleReturnType)
449 mangleType(T->getResultType());
450
451 const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(T);
452 assert(Proto && "Can't mangle K&R function prototypes");
453
454 for (FunctionTypeProto::arg_type_iterator Arg = Proto->arg_type_begin(),
455 ArgEnd = Proto->arg_type_end();
456 Arg != ArgEnd; ++Arg)
457 mangleType(*Arg);
458}
459
460void CXXNameMangler::mangleType(const TagType *T) {
461 // <class-enum-type> ::= <name>
462 mangleName(T->getDecl());
463}
464
465void CXXNameMangler::mangleType(const ArrayType *T) {
466 // <array-type> ::= A <positive dimension number> _ <element type>
467 // ::= A [<dimension expression>] _ <element type>
468 Out << 'A';
469 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
470 Out << CAT->getSize();
471 else if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(T))
472 mangleExpression(VAT->getSizeExpr());
473 else if (const DependentSizedArrayType *DSAT
474 = dyn_cast<DependentSizedArrayType>(T))
475 mangleExpression(DSAT->getSizeExpr());
476
477 Out << '_';
478 mangleType(T->getElementType());
479}
480
481void CXXNameMangler::mangleType(const MemberPointerType *T) {
482 // <pointer-to-member-type> ::= M <class type> <member type>
483 Out << 'M';
484 mangleType(QualType(T->getClass(), 0));
485 mangleType(T->getPointeeType());
486}
487
488void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
489 // <template-param> ::= T_ # first template parameter
490 // ::= T <parameter-2 non-negative number> _
491 if (T->getIndex() == 0)
492 Out << "T_";
493 else
494 Out << 'T' << (T->getIndex() - 1) << '_';
495}
496
497void CXXNameMangler::mangleExpression(Expr *E) {
498 assert(false && "Cannot mangle expressions yet");
499}
500
501namespace clang {
502 /// \brief Mangles the name of the declaration D and emits that name
503 /// to the given output stream.
504 ///
505 /// If the declaration D requires a mangled name, this routine will
506 /// emit that mangled name to \p os and return true. Otherwise, \p
507 /// os will be unchanged and this routine will return false. In this
508 /// case, the caller should just emit the identifier of the declaration
509 /// (\c D->getIdentifier()) as its name.
510 bool mangleName(const NamedDecl *D, ASTContext &Context,
511 llvm::raw_ostream &os) {
512 CXXNameMangler Mangler(Context, os);
513 return Mangler.mangle(D);
514 }
515}
516